Tuesday, 25 May 2010

Moved

This blog has moved to m14i.wordpress.com

Friday, 7 May 2010

GTUG Stockholm May meeing

I just came back from GTUG May meeting, my first GTUG meeting ever, and I got to give a presentation on web applications for iPhone and Android.

GTUG is hosted by what can be described as one of the jolliest and friendliest developers I’ve ever met, Peter Svensson. We all met up at Ottoboni, located near Skanstull, enough seating for around 60 people. A great view towards Globen and a selection of Subway sandwiches lay on the tables unwrapped and ready to be enjoyed along with a liberal amount of white bag-in-box (or cask: whichever wording you prefer) of white wine.

The first speaker was Tom Blackmore, famous for his work at Hitta.Se and an expert when it comes to GIS (geographical information systems). Tom talked about how one can create a relationship between raw data and locations. He went on further to explain how Googles geolocation API worked by showing examples of coordinate look-up queries for addresses as well as reverse look-ups, i.e., getting the street name from a GPS location.

And then it was my turn. My stunning new MacBook Pro was eager to show the world how well it could render PDF formatted slide shows and wow the world with its aesthetic beauty. However, it turned out that I had an incompatibility issue with one of my VGA adapter cables and was forced to use Tom’s computer. Being all brainy and all I backed up everything to a USB memory stick, physical paper as well as Dropbox.

So finally I began my presentation and, in what seemed mere seconds, I was already done. During these seconds of Michael-is-talking-now time, over 40 minutes of real time had elapsed. I came, presented, and felt like a mini rock star amongst like-minded people.

Next up was Justus Thorvaldsson, a young KTH:are giving a talk on GWT and how they used it to create RiskIt, an online game based on the same principles as the classic game of Risk. To end it all, a summary was given on the results of the Android Hackathon that took place on the 1st of May.

The end was nigh and the night was young. A bit of mingling and a beer at a random pub near Skanstull with some friendly GTUG:ians. See you all next time.

Thursday, 1 April 2010

Similarities and Differences between Java and C#

You're a Java developer about to embark on a C#.NET project or a C#.NET developer about to start work on some Java code or you're just curious about the differences between these two platforms. Whatever the case may be, fear not the new, because in this case, you will see that these languages have a lot in common.

In a sense, C# feels like the bastard child of Java and C++ and somehow even Python managed to get in on the action (yield and dynamic variables). As mentioned on the wiki page, C# began its life as an extension of Java designed by Microsoft. But Sun disagreed with Microsoft's design suggestion as Sun felt that they went against Java's philosophy of keeping things simple. Thus C# was born and this is the reason why there is so much of an overlap between Java and C#. Being a new language, it had the advantage being able to adapt to the wants and needs of developers to include many new programming aspects such as lambda expressions and dynamic variables.

Namespace and Package

In Java, one is forced to map the package structure to the file structure. This isn't the case in C# where namespace acts pretty much like namespace in C++ and you can have your C# files wherever you want as long as they are in the project path. In Java, one writes import to include functionality while in C# one would write using.
The Java Way
The C# Way

Naming Conventions

Anything that is public in C# is written in Pascal case, private member variables have an "_" (underscore) prefix followed by camel case, variables declared inside functions use camel case. In Java, you use Pascal case for class names and camel case for class members. This can be seen in the images above where I wrote some example code.

Constants in most languages are represented using SCREAMING_CAPS, all uppercase with underscore separators. This is discouraged in C# but fine in Java. C# also suggests that developers use Hungarian notation for helping identify the type of the variable.

Since C# doesn't distinguish between implementing an interface and extending a class, which is the case in Java, interface declarations have a "I" (capital i) prefix, such as IDisposable.

At this stage you will have also noticed that C# uses C style block declarations where open curly brace is on a new line, while Java has the open curly brace on the same line as the expression or declaration, the exception in both cases being inline blocks.


Implementing Interfaces and Extending Classes

While Java uses the keywords implements and extends, C# uses the colon (:) to show that a class implements an interface or extends a class. C# syntax doesn't differentiate between the two whereas Java is strict about which keyword should be used.
The Java Way


The C# Way

Getters and Setters

You will have already noticed that Java uses a naming convention for declaring getters and setters while C# uses the keywords get and set. In C#, variables that are accessed via accessors are properties and are accessed using conventional dot notation, much like a public variable in Java. In Java, many frameworks make use of the naming convention to simplify accessing variables via getters and setters, such as Javas expression language used in JSP's.

Primitives

C# implements string as a primitive whereas Java implements String as an object. Generally, Java has a class definition of all primitives such as int and Integer, this is not the case for C# where a primitive is the class. Thus, in Java you would write
int i = Integer.parseInt("2");
and in C#
int i = int.Parse("2");
This also means that you can use primitives in generics freely, which is not the case for Java generics where you are required to use an object instead.

C# specialties

C# is a gigantic language when compared to Java which is a much more compact language but used for similar tasks as C#. C# has a plethora of keywords that have a slightly different name than in Java or non-existent in Java, such as ref and out. For a detailed keyword comparison, follow this link.

For Java Developers

If you're new to C#, make absolutely sure that you familiarize yourself with linq and lambda expressions. These are two very powerful C# features, one could say a killer-app for C# that makes for very elegant solutions. Also, the use of implicitly typed variables using the keyword var. 

For a very detailed comparison, check out the Wikipedia link: comparison of Java and C# as well as very thorough analysis of the differences between the two languages

Sunday, 28 February 2010

Windows 7 x64 on Non-unibody MacBook Pro with OS X Leopard

Installing Windows 7 x64 on my MacBook Pro wasn't an "it just works" experience. It is only as of Boot Camp 3 that Apple supports the installation of Windows 7 on a Mac computer, this means that you have to do some minor hacking to be able to use the Boot Camp installation found on the OS X Leopard install disk.

I created a partition by using Disk Utility in OS X and selected the Windows 7 DVD as the startup drive. I rebooted my computer and was greeted by a blank black screen with a blinking cursor.

Searching the internet only led to more frustration as it seems that no solution was available. But in the end, I found a post at a forum where the poster describes how they were able to get around this problem. The solution was the following:
  1. Turn off computer
  2. Remove battery
  3. Wait 20 seconds
  4. Insert battery
  5. Start computer
  6. et voila
Certainly a wtf moment. Never expected this to work, but it did and I was happy.

The installation procedure was completely painless. I was able to use Windows 7 straight after the installation procedure. But, always a but, I wasn't able to install Boot Camp, instead I got an error: 2229 when I tried to launch the setup file.

The problem was solved by using the instructions found here. Basically, you open the BootCampe64.msi file with an msi editor such as InstEd It! and drop the LaunchCondition table. If it still doesn't work, try changing all references from VersionNT = 600 to VersionNT >= 600 in all the tables. VersionNT = 600 refers to Windows Vista while VersionNT >= is Windows Vista and above - Windows 7 has 610, I think.

So almost everything works now, except for sound. To get sound working, I had to 
  1. Extract the RealTekSetup.exe file found on the OS X install disk in the Boot Camp/Drivers directory (do this with 7-Zip)
  2. Open Control Panel -> System 
  3. Expand the "Sound, video and game controllers" node and right click on the audio device item and chose update driver software
  4. Choose the folder that contains the files from the extracted RealTekSetup.exe file
  5. Windows found the files and installed the drivers without any problems
And now, as far as I can tell, everything really does work.

Wednesday, 17 February 2010

Speeding Up Interaction by Cancelling Events

At my last project (I'm an IT-Consultant), I was helping fine-tune as well as bug fix the customers JavaScript based map application. One feature of the map application was that the user could interact with the map, i.e., pan around as well as zoom in, which would then trigger a search inside the given bounding box. A search executes an Ajax REST call to the search service, which can take up to around 500ms to respond, depending on the search criteria as well as the number of results found.

The problem was that several searches could be queued within just a few milliseconds, thus resulting in several searches being executed back-to-back each taking around a half second to complete. Very frustrating for the user. Solving this problem proved to be quite easy - fact of the matter is that only the last search is of importance to the user, within a given time frame - say 300ms. This led to the implementation of a cancelling queue or what I call a null queue, i.e., all searches that are queued within less than 300ms of each other are subject to being cancelled, only the last search in the queue will be executed. This is a lot like a timeout for autocomplete.

/**
 * Instantiate a NullQueue and set the threshold timeout value
 * to be used for nulling items in the queue.
 * 
 * @constructor
 * @param {Integer} threshold The timeout value
 */
function NullQueue(threshold) {
 
    this.threshold = threshold;
    this.queue = [];
    this.timerId = null;
 
}

/**
 * Push an item on to the queue. 
 * 
 * Every time an item is pushed on to the queue, the 
 * timeout is reset.
 * 
 * @param {Function} item Item to execute
 */
NullQueue.prototype.push = function(item){
 
    var me = this;
 
    me.queue.push(item);
 
    if (null !== me.timerId) {
        clearTimeout(me.timerId);
    }
 
    me.timerId = setTimeout(function(){
        me.process();
    }, me.threshold);
};


/**
 * Process the queue.
 * 
 * All items, except for the last item in the queue
 * are nulled. The last item is then executed.
 * 
 * @private
 */
NullQueue.prototype.process = function() {
 
    var me = this;
 
    var item = me.queue[me.queue.length - 1];
    me.queue = [];
 
    item.call();
};



/**
 * Test the NullQueue implementation
 * 
 * Move the mouse around inside the browser. Your current cursor
 * coordinates will be shown in an alert when you hold the cursor
 * still for 500ms.
 * 
 * @test
 */
function testNullQueue(){

    var testQueue = new NullQueue(500);
 
    document.addEventListener("mousemove", function(ev){
 
        testQueue.push(function(){
              alert("Mouse: x=" + ev.pageX + ", y=" + ev.pageY);
        });
  
    }, false);
}

testNullQueue();

Saturday, 7 November 2009

The Funky Side of Webkit on iPod Touch

Here are some things that I noticed that make developing webapps a bit of a pain for webkit on iPod Touch. At this stage I'd like to mention that these problems occurred on a 2nd generation iPod Touch. The 3rd generation iPod Touch has a much more mature variation of webkit. Granted webkit (or Safari, whichever name you prefer) has functionality that goes way above and beyond what you would normally expect from a mobile based web browser - but there are aspects that remind me of what it can be like to develop for a browser that sometimes behaves in unexpected ways.

css position: fixed doesn't work. instead you have to use a work-around.

css overflow: has lacking support meaning scrollbars do not appear when they are supposed to.

innerHTML is strict which can be a bit of a double edged sword. Strict is good because it ensures that whatever you end up injecting is valid, at the same time, it makes it harder to cache something that you would like to inject later (like table elements).

This property is usually the cause of NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7. Check if all XML tags are closed, that child elements are within their correct parent elements and the proper use of HTML entities.

innerHTML mangles ampersand (&). This happens when I use XHR to load a remote document that contains links with a query string and try to inject it using the innerHTML property.

A work-around is to use a different separator, like pipe "|". This also entails parsing the URL before it is processed by the service to convert | to & by using server-side filters for example.

Provides only a portion of a document for viewing. When scrolling through a long list, you'll notice that 'dead space' can appear before a portion is loaded into view. This can lead to JavaScript problems when functionality is linked to markup (like this for example).

Graphical glitches can occur. This is probably linked to the overflow issue since I have a div with overflow hidden containing other divs with background images that are moved around (and outside) the container div. The images then break out from the container and intertwine with other elements on the page.

Friday, 6 November 2009

Automatic Pagination: The Infinite List using iUI and jQuery

Automatic pagination means that we progressively load in new data without the user having to actively click on a page link. This way, we can create lists that seem infinitely long since we automatically load the next page when the user is about to scroll to the end of the list.

The implementation is quite simple. We create an initial page that contains all the mark-up required to qualify as an HTML web page. In this page, we have an unordered list.

<ul>
    <li>an item</li>
    <li>another item</li>
    <li><a href="/get/more/items?page=2" target="_replace">Get more items</a></li>
</ul>

Note that the last item is an anchor which contains a URL with a pagination parameter. The page that it links to looks like the following piece of mark-up.

<li>even more items</li>
<li>list are great</li>
<li>itemized</li>
<li><a href="/get/more/items?page=3" target="_replace">Get more items</a></li>

Normally iUI would load the content when the user clicks on the link. But to automate the process, we can add a few lines of JavaScript to our web app.

/*** JS Code using iUI framework and jQuery ***/

var ns = {};

// Throttle the requests (in this case 1 second)
ns.throttle = 1000;
ns.isOkToLoad = true;

// Number of pixels before last element
ns.scrollPadding = 100;

(function() {

    ns.autoloadOnScroll = function(event) {

        if (!ns.isOkToLoad) return;

        var scrlHeight = window.document.body.scrollHeight;
        var scrlPos = window.innerHeight + window.scrollY;

        if (scrlHeight < (ns.scrollPadding + scrlPos)) {

            var link = $("a[target=_replace]").get(0);
            
            if (link) {
                setTimeout("ns.isOkToLoad = true", ns.throttle);
                ns.isOkToLoad = false;

                iui.showPageByHref(link.href, null, null, link, iui.unselect);
            }   
        }

    };

})();

$(function() {

    window.onscroll = ns.autoloadOnScroll;

});

You could set ns.isOkToLoad = true in the callback from the XHR (which is done inside iui.showPageByHref).

Links