Having fun with HTML 5 History API – part three

Part 1 – Description of the problem
Part 2 – simple history replacement
Part 3 – additional history items – this article

As we’ve seen in the previous parts, we can alter the history of the current page navigation by replacing the current URL with a new one (this freedom has limits, of course, and we can’t alter the protocol or the host). For women is very important to show off a nice makeup. You can get a smooth makeup with advises from makeup professionals.

What we’ll explore in this part is creating new history items while not leaving the page. In order to achieve this, we’ll make use of

history.pushState( ... )

and an event called popstate :

window.addEventListener('popstate', function () { /* ... */ });

First we’ll need to replace all replaceState calls to pushState calls. The parameters stay the same:

function loadModels(make, pushState, onSuccess) {
    $.ajax({
        cache: true,
        type: 'GET',
        url: '@Url.Action("GetModelsByMake")',
        data: { 'makeId': make },
        success: function (data) {
            if (pushState)
                history.pushState(null, null, "/Home/Selector?mkId=" + make);
            var models = $("#SelectedModel");
            models.empty();
            models.append($("<option></option>").attr("value", "").text(" -- please select a model -- "));
            $.each(data, function (key, val) {
                models.append($("<option></option>").attr("value", val.Id).text(val.Text));
            });
            $('#divModel').show();
            if (onSuccess)
                onSuccess();
        },
        error: function (xhr, ajaxOptions, error) {
            alert(error);
            $('#divModel').hide();
        }
    });
}

// ...

function modelChanged() {
    var makeId = getParameterByName("mkId", document.location.href);
    var modelId = $("#SelectedModel").val();
    if (!modelId)
        history.pushState(null, null, "/Home/Selector?mkId=" + makeId);
    else
        history.pushState(null, null, "/Home/Selector?mkId=" + makeId + "&mdId=" + modelId);
}

Read more »

Having fun with HTML 5 History API – part two

Part 1 – Description of the problem
Part 2 – this article (simple history replacement)
Part 3 – additional history items

As we saw earlier in part 1, hitting the back button into a page with filled in fields will not restore (all) the values, but merely the ones that exist at the time of the page loading. In some cases, for example cascading dropdowns, will not be shown or exist at all at the time of the page load.

What we will accomplish in this part is to push into the query string (without reloading the page!) the selected make and the selected model (where applicable).

We are going to make use of

history.replaceState(...)

function. There is a W3C standard available for this function (and others).  Note that this is supported on all browsers, but only the recent versions.

To do so we need a few things:

  • A function to parse (a) query string; sadly JavaScript does not have anything built in, not even jQuery is of much help..
  • Change the URL upon changing of selection
  • Restore selection from the URL – including cascading

Great! Let’s start.

Upon a bit of searching around which turned into stackoverflowing, I reached the most voted question on this matter called ‘How can I get query string values in JavaScript?‘.

I really looked for a quick-simple-and-standards-compliant-and-so-on solution but the best I could scavenge was this:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Ugly but it works.

Read more »

Having fun with HTML 5 History API – part one

Part 1 – this article
Part 2 – simple history replacement
Part 3 – additional history items

Have you ever come across a web page with a few fields, let’s say cascading drop downs, you know like these:

… and after carefully filling in the fields you submit, and you are taken to the next page. Only to find out that you made a mistake and you push the back button in your browser. Guess what, now (almost) all your fields are reset and you have to begin all over again. Frustrating.

Apart from that, I have noticed that “infinite scrolling” has really taken off in a lot of sites, some news site (for example this one – at least at the time of the writing) even change the URL as you scroll down into the next article.

And then I wondered, how could I use this gimmick into solving the first issue (i.e. losing fields information after pressing back) and I came up with two possible solutions to this. I will showcase a small PoC for each one in the next two parts.

First let’s consider the following minimal web project (ASP.NET MVC but since this is about JavaScript, the back end doesn’t really matter) with two drop-downs. The first dropdown will let you choose a make of automobiles and the second one will let you choose a model from that particular make. In the end you press continue and you are directed to a new page:

01

Read more »

When Stackoverflow goes looney like a leftie

I was recently doing reviews on Stackoverflow when a ‘go home you’re drunk’ page ‘caught’ me. Lookie here:

stackoThis was supposed to be a test to catch ‘speeding’ reviewers. I admit that C/C++ are not my strongest points but I can understand code in C/C++ and rarely even write in them.

I guess they went overboard this time.

Local meetup – AngularJS intro

Lately I’ve been toying with AngularJS and I wanted to share my findings in a short practical presentation. I will be building a small SPA (single page application) with AngularJS and run through the most commonly used directives and features of the framework.

If you are in Bucharest on 8th of December, after work (19:00) drop by and have a look 🙂 The presentation will be in the ADCES group, the location being Electronic Arts (AFI Park 2).

Entrance is free, just register on this event either via Facebook or via Meetup. Hope to see you there 🙂

PS: Did I tell you that we’re having beers afterwards? 😉

Visual Studio smart replace

Let’s say you need to replace an expression in many files in Visual Studio with another expression. The case in question is replacing

nameof(someVariable)
to
"someVariable"

Sure you can try to replace

nameof(
to
"

but this will leave the double quote open and we don’t want this. Searching on the internetz and finding some stackoverflow solution and with the help of a second pair of eyes from a colleague we managed to find a solution like so:

Hit CTRL-SHIFT-H in Visual Studio and check “Use Regular Expressions”. Then select your scope, for example “Entire solution” and use the following expressions:

Find what:
nameof\(([a-zA-z]+)\)

Replace with:
"$1"

This will do the job. Let’s analyze the expressions a bit. The “Find what:” one, first. ‘nameof’ is the literal occurence of ‘nameof’. The first round bracket is preceded by backslash because we need to escape it. This is because the round bracket is used in the regular expressions syntax while in our case we need to literally find it. This was the ‘\(‘ part.

Now there is the ‘([a-zA-z]+)’ part. This has several sub-parts. The round brackets mean that the whole segment should be captured. We’ll later see why and what this is. Next, the square bracket part means that this should match any letter be it uppercase or lowercase (yes, I didn’t handle digits or underscores etc. which may be used in parameter/variable names, that is left as an exercise to the reader :P). The plus sign means the square bracket part may occur multiple times. This means that a parameter/variable name may have more than one such character. Finally we close this part with the round bracket.

The final part in the “Find what:” expression is a literal closing round bracket which, again, is escaped by being prefixed with a backslash.

In the “Replace with:” expression, the captured part in the previous expression (what is enclosed in the regular-expression-syntax round brackets) is expressed as $1, as first numbered. Finally we enclose this in double quotes because that is what we need.

As for why I had to rollback from C# 6 nameof expression to a stringly-typed version, that’s a story for another time, I guess.

Cross-platform browser keyboard shortcuts

As of recently I began working on a Mac-book pro and I have to get used to a keyboard with different keys and different layout. One of the most used piece of software today is a browser. I routinely use Opera but there are still sites that don’t work well with it, although it uses pretty much the same rendering engine like Chrome.

I suspect these issues arise from the fact that Chrome tends to become the new IE 6 for many web developers (i.e. : write a page, test it in Chrome, it works, the rest of browsers doesn’t matter to me, continue to next page etc.).

I consider, just like Scott Hanselman, that using the keyboard is the most efficient way to command a computer (and not the mouse / touchpad) therefore I strive to use it to the max. However, switching from OS X to the Windows virtual machine back and forth can be confusing since there are different shortcuts. For example F5 in Windows refreshes the window while in OS X it doesn’t (be it because by default you have to press Fn and then F5 in order to send F5 otherwise a media function will be sent or because this key does not do this function).

Therefore I gathered a few useful shortcut keys that work in both Windows and OS X so I can use them. Many of them work across all major browsers (IE, Firefox, Chrome, Opera and Safari). Use Command (Cmd) key in OS X and Control (Ctrl) in Windows. I’ll include only the secondary key(s) in the table below since the primary key should be held down. I am planning to update this table several times.

Function Second key Internet Explorer Opera for Windows Opera for Mac Chrome for Windows Chrome for Mac
Quit (Close) app Q  x
Close tab (window) W  ✓
Refresh tab R  ✓
Open a new tab T  ✓
Open last closed tab SHIFT-T  ✓
View source U  ✓  x
Print page P  ✓
Select all page content A  ✓
Save current page to computer S  ✓
Add to favorites / bookmark D  ✓
Find in page F  ✓
Find again G  ✓
Show history H  ✓  x
View downloads J  ✓  x
Focus the address bar L  ✓
Undo Z  ✓
Cut X  ✓
Copy C  ✓
Paste V  ✓
Open a new window N  ✓
Open a new private window SHIFT-N  ✓

✓ = available
x = unavailable
[white_space] = not yet verified

(work in progress)

Dear readers, what other useful shortcuts is this table missing?

Quick trick : Copy file path

Are you in a command line prompt and you need the full path of the file as an argument? You don’t need to type all of the path manually, not even pre-complete it using TABs. Just navigate to the file.
Here comes the trick part : hold SHIFT while right-clicking it. The context menu will look like so :

SHIFT-right-click-copy-as-path-contextual-menu-command

I wrote before about the SHIFT-right click so this is somehow connected.

You will then have the full path of the file in the clipboard ready to be pasted wherever you need.

Hope this helps someone! 🙂

Overriding and overloading in Java and .NET – differences, changes and gotchas

Foraying even more in the fundamentals of Java (coming from a .NET background) I’ve come across some interesting things, along with changes in Java SE 5. But first let’s clear up a bit these two notions (overloading and overriding).

Overriding

Is a language feature that allows a subclass/inheriting class to have a method identical (we’ll later see a slight exception to this) to the one in the base class/superclass in every way except the implementation. That is, to have the same return type, the same name, same paramater types, same parameter order, just the code (and the parameter names) can differ.

This is by no means a definitive definition, Wikipedia, .NET CLS’s and JLS may very well differ slightly.

A typical C# overriding example (yes, I also dislike animal examples but they are so eaaaasyyyy to come up with) :

public class Dog 
{
    public virtual void MakeSound()
    {
         Console.WriteLine("Bark.");
    }
}

public class Hound : Dog
{
    public override void MakeSound()
    {
         Console.WriteLine("Wooofff!!!");
    }
}

Java developers unaware of the intricacies of C# will wonder what is that “virtual” thing. In C# all methods are “final” (sealed) by default unlike Java where methods are “virtual” (non-final / non-sealed) by default. This is a profound difference which we’ll discuss later. The “:” stands for “extends”. We’ll discuss the “override” keyword soon, also.

The equivalent piece of code in Java would look like :

public class Dog {
    public void makeSound() {
        System.out.println("Bark.");
    }
}

public class Hound extends Dog {
    public void makeSound() {
        System.out.println("Woofff!!!");
    }
}

Read more »

Numeric literals in Java 7 and in C#

In both Java and C# it’s quite easy to express integer numerical literals. You can use both decimal and hexadecimal base to represent the value. Only for the hexadecimal base you need to prefix the value with 0x. For decimal base values that exceed 2^31-1 you need to provide a suffix (typically L) specifying this fact so the compiler will treat it like a long integer value. C# also provides unsigned long values (U prefix). In both languages the casing of the suffix does not matter.

Java : (notice, there are no unsigned primitives in Java)

int i1 = 23; // integer, decimal
int h1 = 0x17; // integer, hexadecimal
long i2 = 12345678900L; // long integer (64 bit signed integer)

C# :

int i1 = 23;
int h1 = 0x17;
ulong u1 = 12345678900U;
long i2 = 12345678900L;

As you might have read in Beginning Java for .NET developers on slide 14, beginning in Java 7 you can also use two more features, that are not present in C# (at least at the time of this writing) :

Binary base :

int b1 = 0b11001010;

Underscores in literals (no matter which base) :

int b1 = 0b1100_1010;
long myCardNumber = 2315_2432_2111_1110;
int thousandsSeparated = 123_456_000;

The restrictions on the underscore placing is that you may not place it at the beginning of the value (prefix) or at the end (suffix). Also, for non-integer literals, you may not place it adjacent to the decimal separator.

For floating-point literals you must use the dot as decimal separator (if you need to specify a fraction, if not, you’re not required). You must use F for float-single-precision (32 bit) and D for float-double-precision (64 bit). Moreover in C# you have also the M suffix corresponding to the decimal (128 bit) value type.

C# :

float x1 = 0.001F;
double x2 = 12.33D;
decimal x3 = 111.2M;
float x4 = 33F;

Java :

float f1 = 0.001F;
double f2 = 12.31D;
float f3 = 123F;