Thursday, 19 June 2008

COM Scripting in Groovy

Today I needed to test a COM component to make sure it worked as I expected, and to learn a bit about it at the same time. This isn't as easy as it used to be! COM components have fallen seriously out of favour (and for good reason), the effect of this seems to be that the components live on but the consuming languages aren't easily available. I could have created a wrapper using .net but this always seems an ugly and overweight solution.

Groovy has a far more elegant way of handling COM, involving no compilation (apart from what is done in memory) and everything you need comes with the Groovy SDK. In hardly took any time to get this small example of how to send an SMS using the Esendex COM component.

import org.codehaus.groovy.scriptom.*

Scriptom.inApartment {
   def service = new ActiveXObject("Esendex.SendService2");
   service.Initialise("MyUserName", "MyPassword", "MyAccount");
   service.SendMessage("441234567890", "Hello", 1);

The above code is a mashup of the examples on the Scriptom Page and the Esendex VB SDK Page. Its mostly self explanatory, the inApartment method takes a closure containing your COM scripting. Note that the third argument in the SendMessage call, 1, tells the COM object that the SMS is a text message. Remember to install the COM dll using regsvr32 and replace the username, password and account info with your own.

Advantages over VB6 and VBA? Its really easy to thread, and you don't have to find that decade old installation disc :)

No comments: