Taking Baby Steps with ScriptCS

I’ve been following the ScriptCS project with great interest over the last couple of months. As you may know by now, I’ve been searching for a more lightweight .NET development experience for quite some time. The ScriptCS project is here to fulfill this desperate need. Driven by the open-source .NET community, this wonderful initiative promises to unleash C# from Visual Studio which is exactly what I’ve been looking for.

Being heavily inspired by the node.js development workflow, ScriptCS is built on top of Roslyn and makes heavy use of NuGet for installing packages and script packs. You can get up and running in no time by installing ScriptCS using Chocolatey. If you didn’t have Chocolatey installed already (like me), then it can be easily done by running the following Powershell command:

@powershell -NoProfile -ExecutionPolicy Unrestricted -Command "iex ((New-Object Net.WebClient).DownloadString(‘https://chocolatey.org/install.ps1′))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin 

Now we can install ScriptCS by simply running the following command:

cinst scriptcs

That’s all we need!

Now in order to do something useful with it, we can clone the samples repository to our dev machine and try to run the Nancy sample application. Navigate to the Nancy folder in a command prompt and run the command “scriptcs -install” to install all package dependencies defined in the packages.config file. Next run the following command to start the web application:

image

Now open up your favorite browser, navigate to http://localhost:1234 and et voilà:

image

Amazing isn’t it?

I do recognize that the project is still very much a work in progress. Also something that’s not entirely clear for me is the deployment story. The road map mentions some kind of export functionality to an .exe or a Visual Studio Project. In any case, there should be an easy way to convert the code files into binary form.

Something that I also would love to see is support for Mono. How cool would it be to develop and run C# code using ScriptCS on Mac and Linux?

The future for ScriptCS certainly looks bright and I’m very much looking forward to where this particular road is taking the .NET universe. Take a look at the wiki and start familiarize yourself with ScriptCS as it’s going to open up very interesting opportunities for future .NET development.

Until next time.

SqlBulkCopy for Generic List<T> (useful for Entity Framework & NHibernate)

A common complaint of the Entity Framework is slow insert times for larger datasets. Last night I was trying to insert a catalog of 15k products and it was taking a very long time (I gave up after 5 minutes). I recalled this post a while back from Mikael Eliasson demonstrating SqlBulkCopy using .NET. I had used BCP in SQL server, but not from .NET. I took Mikael’s example and roughed out a reusable generic version below, which produced 15k inserts in 2.4s or +- 6200 rows per second. I upped it to 4 catalogs, 224392 rows in 39s, for +- 5750 rps (changing between 4 files). These are pretty decent records too, 41 columns and a few of the fields have a meaty char count. Good enough I say.

public static void BulkInsert<T>(string connection, string tableName, IList<T> list)
{
     using (var bulkCopy = new SqlBulkCopy(connection))
     {
          bulkCopy.BatchSize = list.Count;
          bulkCopy.DestinationTableName = tableName;

          var table = new DataTable();
          var props = TypeDescriptor.GetProperties(typeof(T))
                                     //Dirty hack to make sure we only have system data types 
                                     //i.e. filter out the relationships/collections
                                     .Cast<PropertyDescriptor>()
                                     .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
                                     .ToArray();
              
          foreach (var propertyInfo in props)
          {             
               bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
               table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
          }

          var values = new object[props.Length];
          foreach (var item in list)
          {
               for (var i = 0; i < values.Length; i++)
               {
                    values[i] = props[i].GetValue(item);
               }

               table.Rows.Add(values);
          }

          bulkCopy.WriteToServer(table);
     }
}

This works off just a basic list of items which property names match the table column names. Given that most POCO based ORM’s generally match the schema exactly, it works great with EF code first objects.

To use I just build up a list of objects, pick the connection string off the DbContext and then call BulkInsert to save to the DB. Note that in this case I am just adding items to a List<T>, not the EF DbSet<T>.

var imports = new List<Product>();
//Load up the imports

//Pass in cnx, tablename, and list of imports
BulkInsert(context.Database.Connection.ConnectionString, "Products", imports);

Dynamic in C# is Broken

Earlier this week, I ran into an issue while using the dynamic keyword in C#. I learned from C# in Depth that there are a couple of restrictions with dynamic, most notably when using extension methods or converting lambda expressions. But apparently there are more restrictions than meets the eye, which came as an unpleasant surprise. Let’s look at some code.

public interface IPresenter
{
    void Start(dynamic startupData);
}

public interface ISpecificPresenter : IPresenter
{}

public class SpecificPresenter : ISpecificPresenter
{
    public void Start(dynamic startupData)
    {
        // ...
    }
}

Here we have an interface called IPresenter with a single method on it named Start. Notice that the Start method has a single parameter which is defined as dynamic. We also have another interface called ISpecificPresenter that inherits from IPresenter. Finally we have a concrete class that implements the ISpecificPresenter interface. So far, so good.

Next we have a class called Activator that we use to kick-off a particular presenter.

public class Activator
{
    public void Start<TPresenter>(dynamic startupData)
        where TPresenter : IPresenter
    {
        var presenter = ObjectFactory.GetInstance<TPresenter>();
        presenter.Start(startupData);
    }
}

The Activator class has a generic Start method with a parameter named startupData that is also dynamic. Here we simply get an instance of a requested presenter from StructureMap and call its Start method. This is how to call the Start method of the Activator class :

var activator = new Activator();
activator.Start<ISpecificPresenter>(new{});

When we run this code, we get the following exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ‘ISpecificPresenter’ does not contain a definition for ‘Start’.

This had me stumped for a while until I added a cast from ISpecificPresenter to IPresenter in the Start method of the Activator class.

public class Activator
{
    public void Start<TPresenter>(dynamic startupData)
        where TPresenter : IPresenter
    {
        var presenter = (IPresenter)ObjectFactory.GetInstance<TPresenter>();
        presenter.Start(startupData);
    }
}

Now everything works as expected. But I’m not entirely sure why this isn’t behaving as I expected. I guess it has something to do with the fact that the Start method is defined on the IPresenter interface and not on the ISpecificPresenter interface.

image

Although I very much like the flexibility that dynamic objects bring to the C# language, I’m also starting to think that it might not be such a good idea to bring dynamic concepts to a statically typed language. Running into these kind of issues and limitations reinforces this growing opinion.

I would much appreciate it if anyone could enlighten me with a good explanation.

Until next time.

Book Review: C# in Depth–2nd Edition

I really learned a lot from reading the first edition of C# in Depth, so I was very glad that I finally found some time to make my way through the second edition. The content on C# 2.0 and 3.0 was only slightly revised compared to the first edition. Never change a winning combination :-).

But the final part of the book was the one that most interested me. This part discusses the features provided by the C# 4.0 compiler like optional parameters, named parameters, covariance/contravariance and last but not least, the dynamic keyword that got it’s very own chapter. The last chapter for this final part of the book is completely devoted to Code Contracts, which is not a language feature. I personally don’t like the way that Code Contracts are currently implemented by the .NET framework. I do hope that these concepts are going to be part of the C# language one day, which will be a major improvement regarding enforcing such contracts. Until that day, I think I’m going to stick with my own implementation.  

Anyway, I still think that the title of this book is spot on. If you want to bring your C# skills to the next level, then this book will be you guide. This book is filled with knowledge that only a true C# language expert can deliver. Definitely worth the time and effort.

Happy reading.

The Black Art of P/Invoke and Marshaling in .NET

Last week I finally managed to hunt down and resolve a bug that I had been chasing for quite some time. A couple of years ago I built an ASP.NET web service that makes use of a native library to provide most of its functionality. This native DLL exposes a C API, much like the Win32 API, that we’ve been using for integrating a highly-expensive product from a certain vendor into our system.

I didn’t notice any issues during the initial development of this web service, in fact, I was very pleased with how easy it was to use and integrate this API. Until this very day, I still consider this as one of the nicest and most stable C API’s I’ve ever come across. After I finished most of the features for the web service, I ran a couple of load tests in order to determine whether the respective product could withstand a fair amount of requests and also to detect any glitches that might come up in the interop layer. Nothing major turned up, so we decided to bring this service into production and go on with out merry lives.

Aft first we didn’t receive any complaints. Everything worked out as expected, until earlier this year, we noticed some failures of the application pool for our web service in IIS. The event log showed some random crashes of the CLR (= very bad) with some highly obscure error message. These issues occurred completely random. One day, there were about five to six application pool crashes after which it behaved very stable again, sometimes for months in a row.

After doing some investigation on my part, which also involved stretching my shallow knowledge of WinDbg, I found out that .NET runtime was doing a complete shutdown after an AccessViolationException being thrown. This exception reported the following issue:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The first thing I considered was a memory leak turning up somewhere. It’s unmanaged code after all, right? After reviewing the code that uses the imported native functions, I discovered two potential memory leaks that might come up during some edge case scenarios. So I fixed those, but unfortunately it didn’t resolve the problem.

I tried a couple of other things and also approached the issue from a couple of different angles. I’m not going to bore you with the details here, but it clearly didn’t solve anything. I started to become a bit frustrated with this problem. At some point, I was even convinced that this was all caused by the native library itself and not in our code, which is a classic mistake in most long debugging sessions. The good thing was that I was able to reproduce the problem on my machine, by running the load tests with a particular high load. I noticed that there was also a certain pattern in the number of requests between each crash of the application pool.

Vastly determined to fix this, I decided to read up on some information about P/Invoke and marshaling in .NET. I ended up reading this blog post on P/Invoke and memory related issues. While it didn’t provide a clear solution, reading that blog post certainly guided me in the right direction. I started to turn off feature by feature until I was able to isolate the cause of the crash to a single function call. The native function in question has the following signature:

char* FunctionThatReturnsAString();

As it turned out, I created the following P/Invoke prototype for this native function in C#:

[DllImport("SomeProduct.dll")]
public static extern String FunctionThatReturnsAString();

At first sight (and even after a number of subsequent reviews), there seems to be nothing wrong with the way the char * return value is marshaled to a String. I started reading the excellent documentation for this function again, and it explicitly mentioned that the caller should not cleanup the memory for the return value. The allocated memory for the return value is always cleaned up by the native function itself.

Doing some more research on marshaling strings, I found out that in case the native function does its own cleanup, an IntPtr must be returned by the C# prototype declaration instead of a String.

Most c-style strings returned by native functions must be cleaned up by the calling code. For this common scenario, when the return value is marshaled to a String, the interop marshaler assumes that it has to free the unmanaged memory returned by the function. In our case, this actually means that the interop marshaler tried to cleanup memory that at some point was already freed up by the native function or vice versa.  

So I changed the return value for the P/Invoke prototype declaration to an IntPtr. This way, the interop marshaler does not automatically free the memory that is referenced by the IntPtr.

[DllImport("SomeProduct.dll")]
public static extern IntPtr FunctionThatReturnsAString();

Marshaling the data referenced by the IntPtr to a string is quite easy. This can be done using the Marshal.PtrToStringAuto method.

The lesson I learned here is that we need to watch out for these kind of issues when using interop with unmanaged code. On the surface everything seems to work out just fine, but one can still run into some nasty issues afterwards. Carefully considering how to correctly marshal data from and to unmanaged code is an essential technique and sometimes feels like a black art that is not suited for the faint of heart, like myself :-).

Don’t Parse That XML!

I’ve talked a few times about how the best code you can write is code you never write.  One of the major places I end up seeing developer writing code that they don’t need to write is when parsing XML.

A word of caution before I go into how to not have to parse XML!

What I am going to describe is not always going to be the best solution.  It is an easy solution that will cover simple processing of XML files.  For a large XML file, the solutions I am going to suggest might be memory intensive and take too long.

Seems like everyone is doing it

I’ve walked into so many software development shops and seen code to parse XML files.  It seems to be one of those really common things that not enough developers realize can be completely automated.

I have started to wonder if it is self-propagating.  If developers have a tendency to see it being manually parsed in one place, assume that there is not a better way, then propagate that manual parsing to the next place they go.

Why is it so bad?

First of all, it is not an easy task to parse XML.  Even when using an XML parsing library there is a large amount of code that has to be written, especially for a complex XSD.

XML parsing code is also very fragile.  If the structure of an XML file changes, the code will have to be modified, and the modification can have cascading effects.

Manually generated XML parsing code cannot be regenerated if the structure of the XML changes.

Most importantly, any code you have to write runs the risk of introducing bugs and complexity into the system.

It’s so simple you wouldn’t believe it

So, how simple is it to automatically parse XML into objects?

Very simple.  First I am going to give you the basic pattern, then I am going to tell you how to do it in both C# and Java.

Basic pattern:

  1. Use a tool to generate an inferred XSD from your XML file.  (You can skip this step if you already have an XSD file.)
  2. Use a code generation tool to generate your classes automatically from the XSD file.
  3. In your code, deserialize your XML file into an object tree using the framework you generated the classes from.

If you are doing something more complex than this, without a really good reason, you are doing it wrong!

Learning how to do this in your language of choice is a very important tool to put into your tool bag.  There are many times that I have run into the need to parse XML files, where I have saved many hours of development time, by knowing how to automatically deserialize my XML files into objects.

There are two main ways in which XML serialization frameworks work.

  1. Serializers that auto-generate the classes from the XSD files.
  2. Serializers that use annotations or attributes on classes.

Using a serializer that auto-generates the classes from an XSD is the easiest to use and can work in most cases.  If you need more control over the generation of the XML, you might want to use an attribute or annotation based framework.

One of the biggest barriers in getting started with an XML framework is knowing what to use and how to use it.  I am going to cover 3 options that will get you going for C#, Java SE, and Java Android development.

C# (XSD.exe)

XML serialization is so easy in C# because it is built right into the .NET framework.

The only real piece of magic you need to know is the XSD.exe tool which is installed with Visual Studio.  This one tool can be run to infer an XSD from your XML file and then again to take that XSD and produce fully serializable / deserializable classes.

If you have an XML file named myFile.xml, you can simply go to the Visual Studio command prompt and type:

xsd myFile.xml

Which will produce a myFile.xsd.

Then type

xsd myFile.xsd /c

This will generate a set of classes that you can add to your project, and then you can deserialize an xml file with this simple code:

   1: XmlSerializer serializer = 

   2: new XmlSerializer(typeof(MyFile));

   3:  

   4: Stream reader = new FileStream("myFile.xml",FileMode.Open);

   5:  

   6: MyFile myFile = (MyFile) serializer.Deserialize(reader);

 
It really is that simple.  There is no excuse for hand writing XML parsing code when you can literally take an XML file you have never seen before and turn it into an object in memory in 10 minutes.
The serialization framework and XSD tool provide options for using attributes to control how the XML is generated also.

Java (JAXB)

The steps are slightly more complicated with JAXB, but it is still fairly easy.

First we have to generate an XSD file from an XML file.  JAXB doesn’t do this itself as far as I know, but there is another tool we can use called Trang.

First step, download Trang, then run it like so:

java –jar trang.jar –I xml –O xsd myFile.xml myFile.xsd

You can also use the XSD.exe tool from Visual Studio if you have it installed or download it.  There are a few other tools out there as well.

Once you have the XSD file, or if you already had one you had written, you need to generate Java classes using JAXB’s tool like so:

xjc –p my.package.name myFile.xsd –d myDirectory

Running this command will produce Java files that represent the elements in your XML document.

Finally, to create your objects you can use the JAXB unmarshaller.

   1: JAXBContext jc = JAXBContext.newInstance("my.package.name");

   2: Unmarshaller unmarshaller = jc.createUnmarshaller();

   3: MyFile myFile = (MyFile) unmarshaller.unmarshal(new File( "myFile.xml"));

Not as simple as the C# example, but really quite simple.  I’ve omitted the steps like downloading JAXB and adding it to your class path, but you can see that the process really is not very painful at all.

JAXB also provides some options for customizing the serialization and deserialization.

Android (Simple XML)

You can’t use JAXB with Android.  It seems like because of the Dalvik VM, the reflection part of JAXB doesn’t work.

I found a pretty good and small XML framework that I am using in my Android app that seems to do the trick nicely.  You have to annotate your classes and create them by hand, but it is very simple and straightforward to do so.

The tool is called “Simple XML.”

You can find lots of examples on the “tutorial” tab on the web page.

Basically, you download Simple XML, add the jars to you class path, and create class files with some annotations to specify how to deserialize or serialize your XML.

Here is a small example of an annotated class, from the Simple XML website.

   1: @Root

   2: public class Example {

   3:  

   4:    @Element

   5:    private String text;

   6:  

   7:    @Attribute

   8:    private int index;

   9:  

  10:    public Example() {

  11:       super();

  12:    }  

  13:  

  14:    public Example(String text, int index) {

  15:       this.text = text;

  16:       this.index = index;

  17:    }

  18:  

  19:    public String getMessage() {

  20:       return text;

  21:    }

  22:  

  23:    public int getId() {

  24:       return index;

  25:    }

  26: }

 

To deserialize this xml you just use the following code.

   1: Serializer serializer = new Persister();

   2: File source = new File("example.xml");

   3:  

   4: Example example = serializer.read(Example.class, source)

Very simple and straightforward.  The only downside is generating the Java class files yourself, but that isn’t really very hard to do using the annotations.

No excuses

So there you have it, XML serialization frameworks abound to make your life easier when dealing with XML.  For most simple cases you should never handwrite XML parsing code, even when using a library to help you do it.

Now that I’ve shown you how easy it is, there really are no excuses!

As always, you can subscribe to this RSS feed to follow my posts on elegant code.  Feel free to check out my main personal blog at http://simpleprogrammer.com, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter here.

CreateDelegate<T> – An Exercise in Using Expressions

In a previous blog post I showed a basic example of how to use the Delegate.CreateDelegate() method as an alternative to the slow MethodInfo.Invoke() for dynamically invoking a method of a class at runtime. The only downside of using CreateDelegate is that its not strongly typed. This is usually not a problem when the signature of the method that must be invoked is known at compile as is the case in the example shown in the blog post mentioned earlier.

var subject = new Subject();
var doSomething = (Func<String, String>)
    Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething");
Console.WriteLine(doSomething("Hello Freggles"));

Here we’re simply able to cast the result to the requested delegate type. But what if a generic method must be invoked for which the type parameters can vary at runtime? You can still use the CreateDelegate method, but you can’t cast the result to a strongly typed delegate type. This means that in order to invoke the created delegate, the DynamicInvoke method must be called on the returned Delegate object. This has the nasty side effect that when the original method being called throws an exception, the DynamicInvoke method wraps the original exception in a TargetInvocationException.  

So in order to find a better way and also exercise my Expressions-fu, I tried to come up with a CreateDelegate<T> extension method that can be used to a create a strongly typed delegate for a MethodInfo object.

Suppose we have to dynamically invoke a method with the following signature:

private void Map<TDomainEvent, TEvent>(TDomainEvent domainEvent, TEvent @event)
    where TDomainEvent : IDomainEvent
    where TEvent : IEvent
{
    ...
}

Given an instance of IDomainEvent and IEvent, using the CreateDelegate<T> extension method that I’m about to show, we can dynamically invoke this method using the following code:

var action = GetType()
    .GetMethod("Map", methodBindings)
    .MakeGenericMethod(domainEvent.GetType(), @event.GetType())
    .CreateDelegate<Action<IDomainEvent, IEvent>>(this);

action(domainEvent, @event);

Here we determine a specific MethodInfo object for the Map method using the types of the event objects we have. Now here’s the code for the strongly typed CreateDelegate extension method.

public static class MethodInfoExtensions
{
    public static TDelegate CreateDelegate<TDelegate>(this MethodInfo method, 
                                                      Object instance) 
        where TDelegate : class
    {
        return CreateCachedDelegate<TDelegate>(method, 
            (typeArguments, parameterExpressions) =>
            {
                Expression<Func<Object>> instanceExpression = () => instance;
                return Expression.Call(Expression.Convert(instanceExpression.Body, 
                                                          instance.GetType()),
                                       method.Name,
                                       typeArguments,
                                       ProvideStrongArgumentsFor(method, 
                                                                 parameterExpressions));
            });
    }

    public static TDelegate CreateDelegate<TDelegate>(this MethodInfo method) 
        where TDelegate : class
    {
        return CreateCachedDelegate<TDelegate>(method, 
            (typeArguments, parameterExpressions) =>
                Expression.Call(method.DeclaringType, method.Name, typeArguments,
                                ProvideStrongArgumentsFor(method, parameterExpressions)));
    }

    private static TDelegate CreateCachedDelegate<TDelegate>(MethodBase method, 
        Func<Type[], ParameterExpression[], MethodCallExpression> getCallExpression)
        where TDelegate : class
    {
        var @delegate = GetFromCache<TDelegate>();
        if(null == @delegate)
        {
            @delegate = CreateDelegate<TDelegate>(method, getCallExpression);
            StoreInCache(@delegate);
        }

        return @delegate;
    }

    private static TDelegate GetFromCache<TDelegate>()
    {
        Object delegateObj;
        if(_delegateCache.TryGetValue(typeof(TDelegate), out delegateObj))
            return (TDelegate)delegateObj;

        return default(TDelegate);
    }

    private static void StoreInCache<TDelegate>(TDelegate @delegate)
    {
        _delegateCache.TryAdd(typeof(TDelegate), @delegate);
    }

    private static TDelegate CreateDelegate<TDelegate>(MethodBase method, 
        Func<Type[], ParameterExpression[], MethodCallExpression> getCallExpression)
    {
        var parameterExpressions = ExtractParameterExpressionsFrom<TDelegate>();
        CheckParameterCountsAreEqual(parameterExpressions, method.GetParameters());

        var call = getCallExpression(GetTypeArgumentsFor(method), parameterExpressions);

        var lambda = Expression.Lambda<TDelegate>(call, parameterExpressions);
        return lambda.Compile();
    }

    private static ParameterExpression[] ExtractParameterExpressionsFrom<TDelegate>()
    {
        return typeof(TDelegate)
            .GetMethod("Invoke")
            .GetParameters()
            .ToParameterExpressions()
            .ToArray();
    }

    private static void CheckParameterCountsAreEqual(
        IEnumerable<ParameterExpression> delegateParameters,
        IEnumerable<ParameterInfo> methodParameters)
    {
        if(delegateParameters.Count() != methodParameters.Count())
            throw new InvalidOperationException(
                "The number of parameters of the requested delegate does not match " +
                "the number parameters of the specified method.");
    }

    private static Type[] GetTypeArgumentsFor(MethodBase method)
    {
        var typeArguments = method.GetGenericArguments();
        return (typeArguments.Length > 0) ? typeArguments : null;
    }

    private static Expression[] ProvideStrongArgumentsFor(
        MethodInfo method, ParameterExpression[] parameterExpressions)
    {
        return method.GetParameters()
            .Select((parameter, index) => 
                Expression.Convert(parameterExpressions[index], 
                                   parameter.ParameterType))
            .ToArray();
    }

    private static readonly ConcurrentDictionary<Type, Object> _delegateCache =
        new ConcurrentDictionary<Type, Object>(); 
}

I actually provided two CreateDelegate methods here, one for instance methods (the first one) and one for static methods ( the second one). The created delegates are cached in a dictionary because the call of lambda.Compile() seems to be quite expensive.

Now I have to warn you that, based on first preliminary measurements, this implementation probably isn’t going to outperform  Delegate.CreateDelegate(). In fact, if you’re interested have a look at this approach first as it seems much faster. I added some spike code to the Elegant Code repository for those who fancy to take a look.  

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.