Saturday, June 26, 2010

Enter a Parallel Universe Using IKVM.NET

IKVM.NET is something I’ve been playing with for a while now, but seeing this awesome trailer today reminded me that I should write a post about it.

I always considered Java to be some kind of parallel universe compared to .NET where a lot of interesting lessons can be learned. I never did any serious Java development throughout my professional career, but I like to follow up on the trends in the Java community. Although the Java community suffers from some of the same diseases as the .NET community, the wide-spread acceptance of open-source and the adoption of new, fascinating languages on top of the JVM is an interesting evolution that I feel is lacking in the .NET world. Although the CLR/DLR is probably better designed to host a wider diversity of programming languages than the JVM, the rise of programming languages like Scala, Clojure, Groovy and others is more sparse in the Java universe. Some of the most useful open-source projects in .NET today  initially started out by porting the code of established Java libraries, like NUnit, NHibernate and Spring.NET, etc. …. Anyway, we’re wandering off.

Did you ever need to interoperate with a Java library while developing .NET applications? I have to admit, it doesn’t come up very often but when it does (especially when using IBM products ;-) ), IKVM.NET might save you from a whole lot of trouble.

With IKVM.NET its possible to use Java API’s from a .NET application or even to use the Java language to develop .NET applications. Let me show you a quick example.

Say for example that you’re done with the DateTime class in .NET and you need a library that gives you more power in dealing with dates and time in your .NET applications. You do a little searching on the web and there it is, a full blown API like Joda Time (I’m well aware that honorable Jon Skeet has ported this framework to .NET already, but bear with me).

All we have to do to start using Joda Time in a .NET application is to download joda-time.jar and feed it to the ikvmc.exe command-line tool that comes with the binaries of IKVM.NET. Out comes a full blown .NET assembly by executing the following command:

ikvmc -target:library joda-time-1.6.jar

There are a whole slew of other options that you can specify here, like signing the resulting assembly (who still does that, really), specifying the assembly version, etc. …

This is how the generated assembly looks like in Reflector.

Reflector

The following block of code is small utility that I developed to deal with the time zone arithmetic for the Europe Virtual ALT.NET.

using System;
using System.Windows.Forms;
using org.joda.time;
using org.joda.time.format;
using DateTime = org.joda.time.DateTime;
using TimeZone = java.util.TimeZone;

public partial class Main : Form
{
    private const String London = "Europe/London";
    private const String Brussels = "Europe/Brussels";
    private const String EST = "EST";
    private const String MST = "MST";
    private const String PST = "PST";

    public Main()
    {
        InitializeComponent();
        DateTimeTextBox.Text = CurrentDateAndTime();
    }

    private void ConvertButton_Click(Object sender, EventArgs e)
    {
        var dateTime = new DateTime(DateTimeTextBox.Text, DateTimeZone.UTC);

        var london = ConvertToTimeZone(London, dateTime);
        var brussels = ConvertToTimeZone(Brussels, dateTime);
        var est = ConvertToTimeZone(EST, dateTime);
        var mst = ConvertToTimeZone(MST, dateTime);
        var pst = ConvertToTimeZone(PST, dateTime);

        var formatter = BuildDateTimeFormatter();
        
        ResultTextBox.Text = String.Format(
            "{0} UK, {1} Brussels, {2} EST, {3} MST and {4} PST.",
            london.toString(formatter),
            brussels.toString(formatter),
            est.toString(formatter),
            mst.toString(formatter),
            pst.toString(formatter));
    }

    private static String CurrentDateAndTime()
    {
        return new DateTime(DateTimeZone.UTC).ToString();
    }

    private static DateTime ConvertToTimeZone(String timeZone, DateTime dateTime)
    {
        var targetTimeZone = DateTimeZone
            .forTimeZone(TimeZone.getTimeZone(timeZone));
        return dateTime.toDateTime(targetTimeZone);
    }
    
    private static DateTimeFormatter BuildDateTimeFormatter()
    {
        return new DateTimeFormatterBuilder()
            .appendHourOfHalfday(2)
            .appendLiteral(":")
            .appendMinuteOfHour(2)
            .appendLiteral(" ")
            .appendHalfdayOfDayText()
            .toFormatter();  
    }
}

The distribution of IKVM.NET also comes with .NET implementation of a whole slew of Java class libraries that you can directly use in a .NET application whenever needed.

IKVM

But remember, as with all things that seem too good to be true, there are a couple of major downsides as well. The one that you run into fairly quickly is generics. I tried generating a .NET assembly from Make It Easy the other day and I noticed that some of the types in the resulting assembly where plain classes while they were defined as generics in the original JAR file. The explanation that I found was that Java checks generics only at compile time and not at runtime. In .NET generics are provided at runtime. If the generics from Java would convert to .NET, then every Java compiler warning would produce a runtime error. All the old code would not run. There is many old code in the Java VM itself.

The IKVM.NET blog is a great resource for some of the other interoperability issues you might experience. Maybe this will come in handy someday, who knows?

Till next time.

Friday, June 25, 2010

Learning JavaScript – Checking The Declaration of a Variable

Judging from my previous post, some people might have come to the conclusion that I’m in the process of learning a wonderful programming language called JavaScript. Well, they’re right! It is a fascinating programming language although it has its quirks and pitfalls.

Have a look at the following piece of code:

var someString = "Hi there";
if(someVariable)
    someString = "Hello JS Ninja";

The if statement tries to check for the existence of a variable called someVariable which is not declared. Because it’s not declared, the code generated the following reference error:

"someVariable is not defined"

Nonetheless, the following line of code nicely outputs the text “Hi there” which means that the previous code block still executes.

alert(someString);

Suppose we did bother to declare someVariable but that it doesn’t contain a value that evaluates to true. In that case we’d still have the same outcome which is not what we intended. 

A better way to check for the existence of someVariable is to use typeof instead:

var someString = "Hi there";
if("undefined" ==! typeof someVariable)
    someString = "Hello JS Ninja";

This still yields the same output as the previous code sample but now without the reference error. typeof always returns a string no matter what, but the difference now is that we’re testing whether the variable has a value besides undefined.

So the following piece of code outputs “Hello JS Ninja” on the screen:

var someString = "Hi there";
var someVariable = false;

if("undefined" !== typeof someVariable)
    someString = "Hello JS Ninja";

alert(someString);

On the other hand, the following piece of code again results in the message “Hi there”:

var someString = "Hi there";
var someVariable;
if("undefined" !== typeof someVariable)
    someString = "Hello JS Ninja";

alert(someString);

This is the part where I usually get a headache and have to go search for aspirin.

Till next time.