Friday, December 31, 2010

Grails, WebServices and .NET interoperability

This is just a quick note for all those that have tried to interop between Grails and .NET using Apache CXF or Apache Axis2 and failed miserably:

Don't use those libraries - instead use the good old grails-xfire plugin. This guy just works out of the box with .NET 3.5 and 4.0. In C# just add a web reference and you're all set!

More on this topic soon - stay tuned!

Thursday, December 30, 2010

Running PHP applications on .NET

Continuing my good fortune in integration between completely different platforms I've tried to integrate some PHP interpreter/compiler called Phalanger 2.0 with existing PHP applications and run them on .NET using VWD server.

PhpBB 3.x



Well, it was no easy thing to do but I've got it to work. And let me tell you it works fast!

One thing to note is that PhpBB did not like the included MySQL connector and I've had to download this one and install it instead.

WordPress



Well, after I've gotten PhpBB to work using the right web.config getting this guy to work was just a matter of minutes.

However getting it to display anything is a nightmare on the internal VWD server because it does not support default documents. So everytime I wanted to display a page I've had to append some stupid parameters to the URL so that the part "index.php" would not get lost.



Others (phpMyAdmin, MediaWiki)

The docs here state that Phalanger 2.0 is perfectly capable of running those 2 applications but as practice has shown there was absolutely no way to bend them to .NET environment. Pity...

I'm going to check how things are with pure IIS and its capabilities for defining the default document :)

Stay tuned!

Compiling Groovy 1.7.6 with IKVM

If you'd like to see how to compile Groovy 1.7.6 under IKVM.NET take a look at this archive. It contains everything you need to be able to turn the groovy-all-1.7.6.jar (and its dependencies) into both an executable (that runs the console) and a library that can then be embedded into a .NET application.

Beware: This is a 27MB download so it's not a small thing.

groovy-1.7.6-net.zip

A note about the compilation process

Please note that there are some issues during 2 phases of the compilation:
1. The first one occurs when compiling commons-logging-1.1.1.jar as it also requires LogKit which I was to lazy to collect and compile
2. The second one occurs while compiling Groovy itself as there are still some dependencies missing. They aren't however important enough to block the usage of compiled library and executable.

Let me know if you'll find this interesting and/or useful :)

Groovy scripting from C#

Well, after the last finding that the Groovy Console executes on IKVM.NET what must have followed was embedding of Groovy scripting capabilities in a C# application.



Here you can snatch the project along with everything needed to compile and run it (besides the .NET framework of course). Beware, it's a 19MB download (50MB+ after unzipping). I've created it using Visual C# Express 2010.

Have fun!

Groovy 1.7.6 under .NET

Well, I finally did it! It did require a huge leap of fate but it finally turned out possible: Groovy running on .NET using IKVM 0.44.0.5!



And not only running but also interoperating with .NET classes!



It's running extremely slow but stable enough to play around a bit with it.

Next step: using Groovy classes from .NET!

Wednesday, December 29, 2010

Grails, configuration and the logSql option

I've tried today to make the dataSource.logSql configurable from an external file so that after deployment I can decide if I want to see the SQL statements in logs or not.

After a previous success with changing the dataSource.url parameter in a properties file designated as an external configuration file I did exactly the same with the logSql option. It turned out not to work.

However what did work was when I included not a ".properties" file but a ".groovy" file as the override configuration and then configured the dataSource as follows:
dataSource {
logSql = false // disable SQL statements logging
}

I've included the external configuration from the environments block like this:
// set per-environment serverURL stem for creating absolute links
environments {
production {
grails.config.locations = [ "file:/etc/example/example-config.groovy" ]
grails.serverURL = "http://www.changeme.com"
}
...

That did the trick so I've tried to go one step further and completely reconfigure the dataSource that previously used an embedded HSQL database to use MySQL:
dataSource {
logSql = false
driverClassName = 'com.mysql.jdbc.Driver'
dialect = 'org.hibernate.dialect.MySQL5InnoDBDialect'
dbCreate = 'update'
url = 'jdbc:mysql://127.0.0.1:3306/example'
username = 'root'
password = ....
}
Obviously since there's no MySQL JDBC driver in my application I've had to supply one to the common libraries folder in Tomcat (in Ubuntu if you install Tomcat via apt-get then the folder is /var/lib/tomcat6/common, otherwise it's just the lib folder in your tomcat installation) and all worked just perfectly :)

This is probably the best thing that ever happened to web application deployment :D This way you're able to completely reconfigure your application (even the most intimate things like bean properties if you so desire) and all that from as many configuration files as I want (just one works as well).

To utilize the new capabilities I've also reconfigured logging:
log4j = {
appenders {
file name: "application", file: "/var/example/log/example.log"
file name: "stacktrace", file: "/var/example/log/stacktrace.log"
}

debug application: 'grails.app'

(the rest of usual logging settings here...)
}
.
That's soooo cool that I can do that :) It helps me be in line with what the admin of our production environment demands.

And best of all: NO DAMN XML WHATSOEVER :) I love being a Grails developer :)

Tuesday, December 28, 2010

Grails and application.gsp layout - revisited

Hi there folks!

While I'm developing applications in Grails I always like to have good names for things I create. Controllers, domain objects, views... The only thing I couldn't find a good name for until now was application layout.

As you can imagine the names application.gsp or main.gsp seem like a perfect match for application-wide layouts. The problem with main.gsp is that it's already taken by the scaffolding mechanism and it's very unlikely that the whole application will be based on scaffolded views. The problem with application.gsp however is much more severe. Once you create this guy it'll apply to everything even if there's no layout specified. This also applies not only to views but to static resources as well! So before you go ahead and create the application.gsp file be prepared to what's coming on to you.

But (as usual with Grails) there's hope :) You can rename the global catch-all name of the layout to use for everything in the conf/Config.groovy file:
grails.sitemesh.default.layout = "none"

This way I've specified that the layout named none.gsp will be used as the catch-all instead of application.gsp and so I can use the latter one for my evil purposes :)

I hope this will save someone the headache I've had trying to figure this out, especially with the selenium plugin or partial-renderings from actions (like the ones used in Ajah) that when married with the original application.gsp looks just wrong all along.

Monday, December 27, 2010

Rails 3.0 - more like Grails :)

Hi there folks!

I can't quite shake the feeling that the new Ruby on Rails in version 3 is more like Grails than it was before :)

Previously everything you did was invoked within the project. There was a script folder that contained scripts to execute. server, generate those are only a few of the examples. In Grails it is different: you get a global command called grails that invokes scripts from either the scripts folder within your project or from a global folder. Well, the new RoR works exactly the same way :) There's a rails command that does exactly the same work :)

Secondly there is the problem with plugins (or gems as they are called in the Ruby world). Previously you just had to know which gems you needed to run the project which was up to the original project creator to document it. In Grails we've always had the appliaction.properties file listing all the required plugins in their respective versions. In RoR 3.0 there's a Gemfile file serving exactly the same purpose :)

Man I like seeing ideas being borrowed between opensource projects! This makes the landscape so much more difficult to choose wrong when selecting the proper platform to do the job!

Grails and dynamically generated JavaScript

Hi!

I can already hear you guys explaining in thousands of words why such a thing is inherently bad. I understand that, I even encourage others to do static JavaScript instead of dynamically generated because it is simply better this way. There are however times when having such a thing comes incredibly handy. When?

- whenever you need to pass on some dynamically-generated variables (like URLs for example) and you only want to do it once
- whenever the code depends on some configuration option

There are more examples but the general rule in my opinion is: as long as you keep your JavaScript generation marginal you're on the safe side.

Let's see how we can implement such a thing.

No doubt there's more than one option to do that. The way I've chosen is in my opinion best because it separates the actual program logic from the generation of JavaScript. So what I've done was I've created a separate controller, called ScriptsController, that has some actions on it (usually actions that provide configuration options for the static part of the JavaScript code)
class ScriptsController {
def home = { }
}
In this case there are no variables passed on from controller to the view but as you can imagine there are possibilities to do that.

I'm using the outcome of this view as
<script 
type="text/javascript"
src="${g.createLink(controller: 'script', action: 'home')}.js">
</script>
and instead of rendering plain HTML code from my GSP I'm rendering JavaScript from /views/scripts/home.js.gsp:
<%@ page contentType="text/javascript"%>
var HomeLink = "${g.createLink(controller: 'home', action: 'index')}";

Because I am a very lazy man and the situation where I need the same set of dynamically-generated content in different views for one controller I've decided to create a tag for it:
class ExampleTagLib {
static namespace = 'g'

def script = { attrs ->
def link = g.createLink(
controller: 'scripts',
action: attrs.name ?: controllerName)
out << """<script type="text/javascript" src="${link}.js"></script>"""
}
}
So here I ask for the current controller's name (which is btw nicely preprocessed by Grails) and use that instead of passing in the same parameter value every time I need it even if the dynamic portion is named the same as the controller that called it. A convention, so to speak.

So here's the simples usage example:
<g:script />
What this will do it will look-up the current controller name and render a script tag that will access the outcome of an action with the same name as the current controller as the src. This is exactly the same as the first version if called from HomeController only shorter.

If however you need to get the script breaking this convention (for whatever reason like common scripts maybe) then the name parameter comes in handy
<g:script name="common" />
This way the common script will be requested.

As usual here's a ready-to-use example.

I hope this will help you out to write less dynamically-generated JavaScript but when you'll have to do it your code will be better structured.

Monday, December 20, 2010

Grails 1.3.6, code-coverage and NTLM authentication error

Hi folks!

Edit on April 25th, 2011

Mike was kind enough to apply a hotfix that I made to the code-coverage plugin. This hotfix disables loading of external DTDs while processing cobertura.xml file. To that end if you're using this one and facing the issue described below you'll want to upgrade the plugin to version 1.2.3.

It's been a bad, bad day today, let me tell you. I'm still pissed off... but let's start from the beginning.

At first it's been great because the new Grails came out. New means better (and in fact it is better), new features - the usual stuff. Right up until you're forced to work behind an NTLM-protected proxy.

Well, first of all I'd like to point out that giving access to the Internet only via proxy is just asking for trouble. There's tons of apps simply not working from behind a proxy, especially one that needs authentication. Just take all Java applications working on Linux with nothing but the core runtime library and you'll know what I mean.

However up until the previous (1.3.5) version of Grails this problem has been overcomed by using Ivy that registered an NTLM authentication provider and all was just nice and dandy.

But in this version guys have upgraded to version 2.2 of Ivy which turned this feature off until Ivy is really in need to download something from the net. This means that if there's anything counting on proxy being setup correctly you're going to find yourself in deep sh..t.

There are 2 methods to overcome this problem:

1. Downgrade to Grails 1.3.5 (I'd recommend that unless like me you really need some of the new features that came to be in 1.3.6 like the "run-script" thingy - extra handy!!!)
2. Install a proxy server that can communicate with an up-stream NTLM-protected proxy

If you're counting on some bad-ass sites telling you to set the http.proxyUser and http.proxyPassword system settings to get it to work again please be adviced that it's just plain not true. This had been so ages ago, but now things are a lot more complicated and this mechanism ain't working anymore. Period.

Just remember: if you'll see something like this:
java.io.IOException: Server returned HTTP response code: 407 for URL: http://cobertura.sourceforge.net/xml/coverage-04.dtd
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:677)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:1315)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:1282)
at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:283)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1194)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1090)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1003)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
at _Events.replaceClosureNamesInXmlReports(_Events.groovy:118)
at _Events$replaceClosureNamesInXmlReports.callCurrent(Unknown Source)
at _Events.replaceClosureNamesInReports(_Events.groovy:89)
at _Events$_run_closure2.doCall(_Events.groovy:42)
at _GrailsEvents_groovy$_run_closure5.doCall(_GrailsEvents_groovy:58)
at _GrailsEvents_groovy$_run_closure5.call(_GrailsEvents_groovy)
at _GrailsTest_groovy$_run_closure1.doCall(_GrailsTest_groovy:203)
at TestApp$_run_closure1.doCall(TestApp.groovy:82)
at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
at gant.Gant.withBuildListeners(Gant.groovy:427)
at gant.Gant.this$2$withBuildListeners(Gant.groovy)
at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
at gant.Gant.dispatch(Gant.groovy:415)
at gant.Gant.this$2$dispatch(Gant.groovy)
at gant.Gant.invokeMethod(Gant.groovy)
at gant.Gant.executeTargets(Gant.groovy:590)
at gant.Gant.executeTargets(Gant.groovy:589)

you're having issues with authorization (it's the 407 part of this call stack)

I hope this will help save someone tons of time that I spent to figure this damn thing out.

Oh! And if it'd not be enough it works just fine on Windows when you're logged in to the domain. Go figure!

Saturday, December 18, 2010

Grails T'n'T: Accessing current controller from a command object

Hi there folks!

This time we're going to talk about how to access the current controller instance from anywhere in the code. We're going to demonstrate this by the Command object example.

Imagine you're in a command object's method and want to call the render method. All would be nice and dandy if it'd be the controller itself but it turns out the command object is more like a domain class (with its ability to verify field values and so on) than anything else. But... there's hope!

Let's add the following method to our command object:
private getController() {
RequestContextHolder.
requestAttributes.
request.
getAttribute(GrailsApplicationAttributes.CONTROLLER)
}

This way we get a read-only property called controller that we can use to call the render method.

But there's more!

Imagine you'd like to access the current request, response or session from the command object. All you need to do is to get there via the controller:
controller.session
controller.request
controller.response

Even the params element of the controller is available!

I sure hope this will help you out in refactoring your code from the controller into external classes like the command objects.

Have fun!

Grails and external configuration - the easy way

Hi folks!

This time we're going to work towards the ability to change application's configuration after deployment. In spring what you usually do is allow for loading some settings from a configuration file first prior to setting the defaults. This way once a particular key has been set in the override it's not going to be overridden by the defaults in your applicationContext.xml or beans.xml (however you wanna call it).

In Grails thanks to the existence of another mechanism we can do it differently. We can instruct Grails to load overrides if they have been declared in either the system properties for currently running process (using the -D notation in JAVA_OPTS) or plain in environment options.

The first option is dead simple. What you need to do is to go to your conf/Config.groovy and uncomment the following lines near the top of the file (at least in the original one):
if(System.properties["${appName}.config.location"]) {
grails.config.locations << "file:" + System.properties["${appName}.config.location"]
}

Unfortunately when you do that and set the proper setting during the invocation of java process that started your application (that'd be Tomcat) you'll be presented with an error message like this:
log4j:ERROR Error initializing log4j: No signature of method: 
groovy.util.ConfigObject.leftShift() is applicable for argument
types: (java.lang.String) values: [file:]
Possible solutions: leftShift(java.util.Map$Entry), leftShift(java.util.Map)
groovy.lang.MissingMethodException: No signature of method:
groovy.util.ConfigObject.leftShift() is applicable for argument types:
(java.lang.String) values: [file:]
Possible solutions: leftShift(java.util.Map$Entry), leftShift(java.util.Map)
at Config.run(Config.groovy:17)
2010-12-18 22:30:46 org.apache.catalina.core.StandardContext start
SEVERE: Error listenerStart
2010-12-18 22:30:46 org.apache.catalina.core.StandardContext start
SEVERE: Context [/] startup failed due to previous errors

This is due to the fact that the grails.config.locations element is not set by default. To fix this simply add the following line just before the the code you've just uncommented:

grails.config.locations = []

Once that's done you're able to specify the additional config location in JAVA_OPTS and live is good :)

The other option is to change the predefined code to look for an environment variable instead:

if(System.getenv()["${appName}.config.location"]) {
grails.config.locations << "file:" + System.getenv()["${appName}.config.location"]
}

This way instead of looking for parameters specified via the -D option while invoking the Java virtual machine it'll look for an environment variable.

Surely you'll find more ways to specify the config file location. The beauty of this solution lies in diversity :)

I hope it'll help someone!

Grails 1.3.6 is here!

Hi folks!

Grails 1.3.6 is here and kicks ass again with one of the coolest features ever! The "run-script" command :)

I admit it has been possible for some time now as mentioned on some blogs but actually having it as part of the framework is a kick-ass productivity boost for anyone that needs to perform administrative tasks on regular basis!

Besides the feature mentioned above it is imperative that you check out the externalized configuration options possibility. This time I'll just simply say "finally"! This stuff has been missing from the framework for a long time! I know it was possible to implement override from an external configuration file but the way it looks now is just as it should be from the beginning!

Fantastic job Grails team! Thank you very very much!

Tuesday, December 14, 2010

Grails Routing plugin released!

Hi all,

Today I've released the first version of grails-routing plugin. It's a modernized version of the original grails-camel plugin by Chris Navta with some extras included.

First of all, if you plan to target Apache Camel 1.6.x this plugin is no good for you as it works only with 2.4.0. It's been ages since 1.6 was released and the original author did not express interest in providing an update.

Secondly there are 2 exciting features included:

- integration with grails-quartz plugin to allow jobs to send messages
- integration with Ivy to download all the necessary dependencies

As I am not leaving my audience without ready-to-use examples (by definition) you'll also find 3 of those:

- basic usage example
- Quartz plugin integration example
- ActiveMQ usage example

I hope it'll serve you well!

Sunday, December 5, 2010

Grails vs JSF - 6 months summary

Hi there folks!

I's been exactly 6 months since I left my previous team where I've had to endure JSF programming for more than a year. Starting July 6 this year I moved to another team where I was finally able to choose the technology I want to work with.

Here are some facts you might find interesting when choosing the web framework:

1. JSF.

- previous project status: in progress...
- team size: 4 developers, 1 architect (doing nothing but breaking the code and managing people since he is the official manager for the team), 2 QAs (doing nothing because of how JSF works)
- project size: too big; needs refactoring into smaller pieces.
- project complexity: waaaaay to high; needs refactoring into smaller pieces.
- code coverage: less than 20%; needs improvement.
- current project status: STILL NOT COMPLETED, 6 developers, 1 and the same architect, don't know about the QAs, but one of them loudly complains he doesn't want to have anything to do with this app :D
- overall experience: I hate my job and I want to die

2. Grails

- team size: 1 developer in the role of architect, QA and programmer and 1 database master, separate manager that does what she(!) is supposed to do which is to help people and not to kill their productivity!
- project size: a lot smaller
- project complexity:
UI: 4/10
server side: 2/10
- project releases from ground zero: 3 (this was a green field project)
- code coverage: constantly between 88% and 98%
- overall experience: I love my job again!

So if you think you're one of the great software architects and you don't need to code because there are others to do that: QUIT YOUR JOB AND STOP DOING ANY MORE DAMAGE!!!
And if you still consider JSF to be a viable option: change your profession! You're probably better of in politics :)

Man, I needed to get that out of my chest :D I'm feeling lucky!

Monday, November 29, 2010

Grails, plugins and tags with templates

Hi all,

If you've wondered if it's possible to render a view from a tag I rush to say it is absolutely possible. You just use the render method and specify the template to be rendered like in this example:
class ExampleTagLib {
def example = { attr, body ->
out << render(template: '/tags/example')
}
}

Ok, that was easy. However things get a little bit more interesting when we try to do the same thing from within a plugin. The problem here is that the render method tries to find the view to be rendered in the application and not in the plugin.
The remedy to this problem is simple: you need to append the plugin name as a parameter to the render method like this:
class ExampleTagLib {
def example = { attr, body ->
out << render(template: '/tags/example', plugin: 'example-plugin')
}
}

Here you can find a ready-to-run example.

Have fun!

Friday, November 26, 2010

STS and Grails - running JUnit tests from IDE

Hi folks!

Have you been wondering how to run JUnit 4 tests under STS so that the the tests are recognized and executed properly?

junit.framework.AssertionFailedError: No tests found in

I guess most of you writing tests for your Grails application have seen this one under Idea or STS. The IDE just doesn't see the right tests by itself... But there's hope!

Here's a definition of a class that when used in conjunction with the @RunWith annotation allows the IDE to run those test properly:
package com.aplaline.example.test;

import org.codehaus.groovy.grails.test.GrailsTestTargetPattern;
import org.codehaus.groovy.grails.test.junit4.runner.GrailsTestCaseRunner;

@SuppressWarnings("rawtypes")
public class GrailsJUnit4Runner extends GrailsTestCaseRunner {
public GrailsJUnit4Runner(Class testClass) {
super(testClass, new GrailsTestTargetPattern[0]);
}
}

And here's an example test that uses it:
package com.aplaline.example

import grails.test.*

import org.junit.Test;
import org.junit.runner.RunWith;
import com.aplaline.example.test.GrailsJUnit4Runner;

@RunWith(GrailsJUnit4Runner)
class CalculatorServiceTests extends GrailsUnitTestCase {
@Test
void canAddTwoNumbers() {
// given
def service = new CalculatorService()

// when
def actual = service.sum(1, 2)

// then
assert actual == 3
}
}

See - that wasn't hard, was it?

I hope it'll help you out test your code more efficiently :)

Have fun!!!

Grails, Quartz and JavaMelody

Hi there!

It was just another day, just another app... And yet another Spring gotcha that took 4 hours of my life away...

Let's start from the beginning.

We wanted to add Quartz scheduler to our existing app. The application was monitored from the beginning using the grails-melody plugin. All was nice and dandy right up to the point where we wanted to have the jobs displayed in the monitoring page.

The reason it was not displayed was that the Spring thingy that creates the scheduler is not a straight up implementation of the basic usage of Quartz pattern but it added one nasty thing to it: whenever a job is created it is removed from the central registry. I can't stress that enough that the path of least resistance has been sooo broken here!

What added to the disaster was that the guys that created the Quartz plugin forgot to make the necessary configuration option available to turn the misfeature off.

Result: it's just impossible to see monitoring of jobs in a humane way!

Here's what you need to do to make it work again (nasty hack - you've been warned!):

1. in GrailsMelodyConfig.groovy add the following line:

javamelody.'quartz-default-listener-disabled' = true

2. in spring/resources.groovy copy the imports and the definition of the following beans:

quartzJobFactory, quartzScheduler

3. copy the loadQuartzConfig private method and the line "def config = loadQuartzConfig()" from the QuartzGrailsPlugin.groovy

4. add the exposeSchedulerInRepository = true setting to quartzScheduler

That does the trick but it's as ughly as it gets.

Here's a working example.

I've submitted a bug report to the guys that maintain the Quartz plugin so that they make the necessary extension so that the infernal exposeSchedulerInRepository parameter is configurable.

Have fun!

Sunday, November 14, 2010

FreePascal, C# and COM

Hi there!

I've been skipping updates of FreePascal lately and since I've received the note that version 2.4.2 was released I've decided to do some investigations on how's the progress of this project.

This time I've decided to check how does it look like to implement a COM server in FP, then to write a client for that server in FP as well and at the end to create a client in C#!

First of all I need to emphasize that the FreePascal compiler as well as it's base library came a long long way since I've last checked them. Great work, guys! I'm really impressed! All I wanted to do was absolutely possible and the general impression was that I'm working with the good old Delphi compiler!

Having that out of my chest let's get back to the task.

We'll need some GUIDs. You can create them online here.

Define an interface in FP:
type
IHello = interface
['{8576CE04-E24A-11D4-BDE0-00A024BAF736}']
procedure DisplayMessage1(S: PChar); safecall;
procedure DisplayMessage2(S: WideString); safecall;
end;

That was easy, right? Just 2 methods that take a string in various form and judging by the name of those they'll display a message somewhere. Let's implement those:
// I've not found where the "ShowMessage" is declared...
procedure ShowMessage(Msg: AnsiString);
begin
MessageBox(0, PChar(Msg), 'Information', MB_OK or MB_ICONINFORMATION);
end;

{ THelloImpl }

procedure THelloImpl.DisplayMessage1(Msg: PChar); safecall;
begin
ShowMessage('MESSAGE USING PCHAR [' + Msg + ']');
end;

procedure THelloImpl.DisplayMessage2(Msg: WideString); safecall;
begin
ShowMessage('MESSAGE USING WIDESTRING [' + Msg + ']');
end;

Again, no magic here...

Let's see how we can do the registration in the COM-subsystem:
const
CLASS_Hello: TGUID = '{8576CE02-E24A-11D4-BDE0-00A024BAF736}';

TComObjectFactory.Create(
ComServer,
THelloImpl,
CLASS_Hello,
'Hello',
'An example COM Object!',
ciMultiInstance,
tmApartment);

Here you see the call to TComObjectFactory.Create. If you want to know what the specific parameters mean look at the Delphi's documentation online.

Now the final thing left to implement are the Co-classes used to instantiate this object:
  CoHello = class
class function Create: IHello;
class function CreateRemote(const MachineName: String): IHello;
end;

[...]

{ CoHello }

class function CoHello.Create: IHello;
begin
Result := CreateComObject(CLASS_Hello) as IHello;
end;

class function CoHello.CreateRemote(const MachineName: String): IHello;
begin
Result := CreateRemoteComObject(MachineName, CLASS_Hello) as IHello;
end;

This way we'll have it easier to deal with the actual instances :)

Let's have some client code, shall we?
var
Hello: IHello;

begin
CoInitialize(0);

Hello := CoHello.Create;
Hello.DisplayMessage1('Hello, world! using COM from FreePascal or Delphi');
Hello.DisplayMessage2('Hello, world! using COM from FreePascal or Delphi');
end.

Important: if it's a console application the CoInitialize(0) does not happen automatically! If you'd have it in a VCL (as in GUI) application the call to Application.Initialize does this for you so you don't need to do that twice.

And there's the whole thing in FreePascal. Let's see now how we can reuse this COM object from C#!
using System;
using System.Runtime.InteropServices;

namespace Client.Net {
[Guid("8576CE04-E24A-11D4-BDE0-00A024BAF736")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IHello {
void DisplayMessage1(
[In, MarshalAs(UnmanagedType.LPStr)] string message
);
void DisplayMessage2(
[In, MarshalAs(UnmanagedType.BStr)] string message
);
}

[ComImport]
[Guid("8576CE02-E24A-11D4-BDE0-00A024BAF736")]
class Hello { }

class Program {
[STAThread]
public static void Main(String[] args) {
var hello = new Hello() as IHello;
hello.DisplayMessage1("Hello, world! using COM from C#");
hello.DisplayMessage2("Hello, world! using COM from C#");
}
}
}

This might require a few words of explanation.

First of all the way you create instances of COM objects in C# is by using the "new" keyword, just like any other instances you might have. To sort of "map" the actual COM class to a C# class you define an empty class with 2 attributes: ComImport and Guid. This allows the compiler to do some magic behind the scenes and do the actual instantiation of COM objects instead.
Next is the funky-looking declaration of an interface. It also has 2 attributes on it: the Guid and an information that this interface is just a descendant of IUnknown, so it comes with no type library. This means that the late binding is out of question.
Last but not least - the threading model. Since we've registered the COM object in FP's COM subsystem to use the tmApartment we need to have it compatible in C# code as well. That's what the "STAThread" attribute is for.

Well, this was a wild ride, let me tell you :) But it was well worth it. Now I have the managed and not managed worlds at my fingertips for free!

As usual here's a ready to run example. It's been compiled for .NET 4.0 so if you don't have it you can build it for 3.5 as well.

Have fun!

Wednesday, October 27, 2010

GUG Poland emerged!

Hi folks!

I'd like to let you know that the grails community has one more place to find answers! This time it's a discussion group for polish speakers, GUG Poland.

Come join and let's bring the community the best help we can!

Grails - custom view engine

Hi there!

Following the last post I was wondering how hard it is to actually create your own artificial view engine for your custom file format. The reason for that might be for example that you want to create Excel files from data returned by an action (like a list of people for example).

I'll assume that the view engine will be completely artificial which means it will not use any resources other than the model being passed on from controller.

Here are the steps one needs to do to make it happen:

1. Register your format so that it is recognized by the system.
2. Implement the ViewResolver and register it as a bean in beans.groovy
3. Implement the actual View and it's "render" method.

Not going into the details here's an example that works. After you run it navigate to http://localhost:8080/example/home/index to see the HTML representation and then to http://localhost:8080/example/home/index.example to see the custom format being rendered instead of the GSP page.

Hope it helps someone :)

Grails and rendering different content types

Hi there Grails freaks!

I've discovered something ground breaking (well, at least for me) with the way Grails renders views so I thought I'll share it with the class :)

Imagine you have a controller, say a PersonController for example. And there you have the "get" action that returns just enough data to render the view. Well times are different than what they used to be 3-4 years before and HTML is not the one and only output format we expect these days. There's JSON, plain text, ATOM, RSS - you name it! Back to the original thought...

Knowing that the JSON format for example looks different than the HTML one (no surprise there) it's kind of obvious the way it's being rendered will need to be different. So for example an HTML view will have everything embedded into an <html> element, then there will be a <body> item containing whatever needs to be rendered whereas the JSON version will most probably contain only the key-value map in JavaScript format.

So what's so ground breaking here? We all know there's this "render person as JSON" thingy, right? Do we really need anything else?

As a matter of fact we do. There are lots of examples where JSON generated this way will not cut it. For example you need the actual data wrapped into some outer object, maybe some additional "count"-like field for list is something you need... You name it!

To get around this here's the revelation: you create not one but as many views as you need but add the extension to their names, for example for the "get" action of "person" controller you'd have get.gsp for the HTML view of the thing and a "get.js.gsp" view for the JSON representation!

Of course one always needs to remember to set the content type properly:

<%@ page contentType="text/javascript"%>

I have no idea if this works with any other version of Grails other than 1.3.5 (this is what I've tested) but this feature is so nice it will allow for effortless rendering of different types of results with no pollution in controller code.

Here is an example project that does what I've described. Once you've got it up and running navigate to http://localhost:8080/example/home/index and http://localhost:8080/example/home/index.js to see the results.

Have fun!

Sunday, October 24, 2010

Git adventures

Hi there folks!

I've been trying really hard (with success!) to get Git (the revision control system from Linus) to work the way I like it.

So the first thing I tried was to clone a remote repository from git hub. That was pretty easy. git clone URL and the repo was cloned. Piece of cake.

Next thing (since I like to mess around) was to create a repo from scratch. No surprise here - git init folder_name and I was done. Working with the new repo did show some surprises... First, the git add required me to specify something to work with. With Mercurial or Bazaar this was not the case so I was surprised to see an error message but I figured out it pretty quickly.

Next thing - commit.
Well, if you worked with Subversion, Mercurial and Bazaar you'd be pretty used to the "ci" abbreviation. Unfortunately it's not working in Git and you have to specify the whole command name... Same thing goes for "status".

Using TortoiseGit under Windows didn't bring much surprise - it was as I'd be using Subversion which means plain and simple.

Last but not least came the problem of sharing my work and creating a "central" (the most important) repository. Had I known this would be so f..ing difficult I'd not start with it at all...

First, there's a "git-daemon" thingy that should take care of the "server" part. Well, it does and exporting (making publicly available) a repository was not a nightmare. One needs to remember that a repo is not automatically available via this daemon but first after creating a tag file in .git subdirectory called "git-daemon-export-ok". That was not intuitive but I can live with it. Google did help.
My anger started when I wanted to push something to the newly cloned and modified repo. It turns out it's not that simple because the "git-daemon" thingy is supposed to be read-only!
After hours of fighting with stupid error messages that the connection was suddenly dropped... Very counterintuitive! But I thought it's not the end of the world and looked further.
I've finally stumbled upon a post describing that git is actually allows interoperability using SSH protocol. So I've cloned the repo using different url (username@host:/path), done the same changes again, checked them in and tried to push. Well... It didn't work either. The repo had to be marked as "bare" - whatever that means. If you've come across this term anywhere else please drop me a note - I have no fricken idea what it means.
So I've "marked" the repo as "bare" in the config file. And again I was not able to push any changes because the repo was empty (surprise! an empty repo cannot be served!!!). After doing some foobar changes to it and committing them on the server I was finally able to push my local changes.

It all sounds like a piece of cake once you know what to do, but attacking the problem head on for the first time is simply a pain in the ass to figure it out.

To summarize:
- you cannot server r/w repo using git protocol. You need to use SSH or other protocol that supports authentication.
- you have to have at least one checkin in the server version of the repository before you're able to push chages from remote clients.
- you need to create "git-daemon-export-ok" for the repo to be picked up by "git-daemon" or else!
- you need to set the "bare" config option to "true" or else!

I hope this will help someone. Have fun!

Tuesday, October 12, 2010

Grails, GORM, Teradata and no primary key

Hi,

I've stumbled upon a problem which is most probably a very common one though I couldn't find any clear answer right away... Mapping to so called natural keys with GORM.

Imagine you have a badly designed table without surrogate key acting as unique primary key. To map such a table in GORM you need to compose the ID of a mapped class using a composed key, that's obvious:
static mapping = {
id composite: [ 'reportId', 'managerId' ]
}

Since there's no restriction telling the database that the fields have to have values then if at least one of the fields contains null what you'll get in return is a null in a list where you'd expect your domain objects!!!

I have no idea if this is a bug but I surely believe that this is a design error in the database.

The fix for that (an ugly like hell one) is to add as much fields that always have values and remove those columns that can have nulls in them.

But I strongly recommend that you do add the surrogate, required (or better yet auto-populated) primary index.


Have fun!

Friday, October 8, 2010

Grails controllers and command objects

Hi there folks!

This is one of the days that come from time to time when one feels as if a lightning struck went down in extreme proximity :)

Well, I've been asked to implement a functionality, a very simple one. Take 2 parameters from the URL, verify if all of them are given, check if one is a valid identifier of an existing entry in the database and if so set a given property of that domain object to the value of the other parameter. Let's see how this might be done:
class CarController {
def index = { ... }

def setCarAvailability = {
def car = Car.get(params.id)
if (car && params.available) {
car.avaiable = params.available
car.save(flush: true)
redirect action: 'index'
} else {
flash.message = "Error: either no valid car id, available not given or saving failed"
redirect action: 'index'
}
}
}

Pretty easy, right?

Now somebody please tell me what's wrong with this picture?

At first, if this is a simple application with one or two controllers having one or two actions this seems completely acceptable, right? But what if there are 5 or 10 actions in 20 different controllers? The answer is simple: UNMAINTAINABLE RAVIOLI CODE!!!

To counteract this I've came across an idea of making command objects not just dumb value placeholders with validation capabilities but to actually implement the command as it should be (given its proud name).

So at the end of the day this is how I'd really code this:
class CarController {
def index = { ... }

def setCarAvailability = {
SetCarAvailabilityCommand command ->

if (command.validate()) {
command.execute()
redirect action: 'index'
} else {
flash.message =
command.errors.allErrors.collect { error ->
error -> error.field
}.join(", ")
redirect action: 'index'
}
}
}

class SetCarAvailabilityCommand {
Car car
Boolean available

static constraints = {
car nullable: false, validator: { it?.attached }
available blank: false, required: false
}

def execute() {
car.available = available
car.save(flush: true)
}
}
How about that, ha? Nice separation of concerns (actual entity that does the job separated from controller that should only care about controlling what should go next), automatic parameter validation, clean naming and if you put those two into the same file then even automatic reloading works!

The key here is that the parameter must be named "car.id" for this to work. This way the automatic binding will find the actual Car instance and put it into our command object automagically.
  <g:form action="setCarAvailability">
<g:textField name="car.id"/>
<g:checkBox name="available"/>
<br/><br/>
<g:submitButton name="action" />
</g:form>

You might have noticed the funny-looking validator for car field. This just checks that the Car instance came from the database. If one would be to specify an id that does not exists it'll fail.

Another neat thing is that all of the commands have similar interface so generally you can create a helper method that will get some parameters (where to redirect after failure for example) and have every single action be actually a one-liner! And remember: since this is a dynamic language with duck typing it does not have to be a java interface strictly speaking! Commands just have to talk and walk like commands :)

Oh, and if you'd like to delegate some code to service I rush to say that dependency injection works as expected with command objects so no worries :)

I would not be myself if a ready-to-use example would not be here :)

I wish you all some nice and well separated code!

Wednesday, October 6, 2010

Grails EasyB and Selenium

Hi there,

having EasyB in your grails project is handy. There's no question about it. However combining it with Selenium RC adds a whole new flavor to the mixture!

Let's examine a step-by-step scenario on how to include both grails-easyb and selenium-rc in a brand new application, then let's create a simple home controller with one action and let's test it using the potent mix of behaviors and remote test execution :)

Step 1: Create a new application

This one is extremely easy:
grails create-app example
Step 2: Install the grails-easyb plugin.

This one is extremely easy to:
grails install-plugin easyb
Step 3: Install selenium rc.

Well, there's 4 things to it.
a) download the Selenium RC package
b) extract the driver (selenium-java-client-driver.jar) into the lib folder of our example application
c) extract the Selenium RC server (the whole folder selenium-server-1.0.3)
d) run Selenium RC server
java -jar selenium-server.jar
Step 4: Create the home controller.

As you might have already guessed:
grails create-controller home
Step 5: Add some meat to the index action.

Let's change the default empty implementation of our index action into
[ message: "Hello, world!" ]
Step 6: Create a functional (yes! functional test at last!) in test/functional (this folder does not exist at first so you have to create it yourself). I'll call it MyFirstFunctional.story
import com.thoughtworks.selenium.*

before "start selenium", {
given "selenium is up and running", {
selenium = new DefaultSelenium(
"localhost", 4444, "*iexplore",
"http://localhost:8080/example/"
)
selenium.start()
}
}

scenario "Will show 'hello, world!' message", {
when "home/index opens", {
selenium.open("home/index")
}

then "the text 'Hello, world! appears on the page", {
selenium.isTextPresent("Hello, world!")
}
}

after "stop selenium", {
then "selenium should be shutdown", {
selenium.stop()
}
}
WARNING: you might naturally want to move the "after" section right below the "before" section. DON'T EVER DO THAT! EasyB test segments are executed in the order they have been declared so if you do that selenium will get stopped before any scenario can be executed!

Step 7: Run the test and see it fail (we have no view just yet)
grails test-app functional:easyb
Step 8: Create the view (/views/home/index.gsp).
Message: ${message}
Step 9: Execute the test and see it pass:
grails test-app functional:easyb

I hope this will cut down the time you spent implementing easyb- and selenium-enabled functional tests clearing any misunderstandings you might have after reading online docs (they suck big time!).

Do I hear "That's a lot of work, man!"??? Well if you're really that lazy grab the ready-to-run package here and enjoy the rest of the evening :)

Have fun!

Tuesday, October 5, 2010

Grails 1.3.5 Released!

Hi there all you Grails geeks!

Yesterday Grails 1.3.5 was released :) With one small addition from me:

class HomeController {

def index = { }

def save = { LoginCommand login ->
println "login.username: ${login.username}"
println "login.password: ${login.password}"
println "comment.text: ${comment.text}"

redirect action: "index"
}
}

class LoginCommand {
String username
String password
}

This is pretty basic stuff, right? We're creating a command object, giving it as the closure parameter and values from the form (named "username" and "password" get deserialized into this object.
What was missing though is the fact that not all of the form parameters need to be bound to the same command object. In fact there are times when more than one object allows for better re-use and/or separation of concerns.
The elements that need to be deserialized into multiple command objects should be prefixed with command type (by convention).

So "LoginCommand" becomes "login.", "CommentCommand" becomes "comment." and for example "VeryLongAndComplexCommand" becomes "very-long-and-complex.".
  <g:form action="save">
<label for="login.username">Username: <g:textField name="login.username"/><br/>
<label for="login.password">Password: </label>
<g:textField name="login.password"/><br/>
<label for="comment.text">Comment</label>
<g:textField name="comment.text"/><br/>
<br/>
<input type="submit"/>
</g:form>
class HomeController {

def index = { }

def save = { LoginCommand login, CommentCommand comment ->
println "login.username: ${login.username}"
println "login.password: ${login.password}"
println "comment.text: ${comment.text}"

redirect action: "index"
}
}

class LoginCommand {
String username
String password
}

class CommentCommand {
String text
}

I know this example is lame, useless and all that but hey - it's just an example :D

The actual prefix for commands is taken from the class name - not the parameter name! Bear that in mind!

I hope you'll like it!

Monday, October 4, 2010

Grails console and LDAP via JNDI

Hi folks!

I've spent over 6 hours today fiddling with LDAP from Grails console and let me tell you it's been a huuuuge disappointment! Let me explain...

I'm using LDAP (it's Active Directory but this is not really relevant) to store users with their attributes. To perform authentication other than usually (having a user that has right to read the password attribute and then query LDAP once a user logs in, verify the password, etc.) I need to login in using credentials provided by user on login page.

With that the use of grails-springsecurity-ldap is pretty much toasted and a new implementation is needed. I don't want to get into any details of spring security plugin, because it makes no sense in this context. What makes a huge difference is the way we interact with LDAP in Java.


import javax.naming.*
import javax.naming.ldap.*

try {
LdapContext context = new InitialLdapContext((Hashtable) [
(Context.INITIAL_CONTEXT_FACTORY): "com.sun.jndi.ldap.LdapCtxFactory",
(Context.PROVIDER_URL) : "ldap://ldap.localdomain.com",
(Context.SECURITY_AUTHENTICATION): "simple",
(Context.SECURITY_PRINCIPAL) : "DOMAIN\\invalid",
(Context.SECURITY_CREDENTIALS) : "invalid",
(Context.REFERRAL) : "follow",
(Context.BATCHSIZE) : "30"
], (Control[]) []);
println "Logged in!"
} catch (AuthenticationException e) {
println "NOT lOGGED IN"
}


The assumption here is of course that "DOMAIN\invalid" either does not exist or has a password other than "invalid" :)

What one would expect from this piece of code is that it tries to create the initial context and since the credentials are wrong an AuthenticationException is being thrown thus the message "NOT LOGGED IN" should appear.

Well, in Groovy console (you know, the one that you get when you install Groovy on your PC) works exactly this way but Grails console works differently. It creates the initial context without problems and presents one with "Logged in!" message.

Why is this happening? Well the CLI support stuff overrides all protocol handlers (and I mean EVERY SINGLE ONE) with Spring's org.springframework.mock.jndi.SimpleNamingContext! Grouse!

What I ended up doing was to use the LdapClient directly (even though it's an implementation detail it gave me all the methods I needed) and life is (sort of) good again...

Check the bug report here.

Wednesday, September 1, 2010

Same name - different projects...

Hi there!

Today I've faced a serious problem: branchy development in Grails. Sounds easy, right? Well... Let's examine this a little bit.

Grails store files in 4 different locations:

  1. The folder where you've unzipped the distro (GRAILS_HOME)

  2. The project's folder

  3. The project's "target" folder

  4. User's home/.grails/{version} folder

The problem is in the last one. What's bad about it while doing branchy development is that there's more than one application with the same name but different version. That causes all kind of issues ranging from random build errors, no auto-reload of artefacts to unexpected application behavior.

As usually with Grails there's an ultra-easy way of fixing this problem :) Here's the content of my grails.bat that does the trick:


@echo off

set GRAILS_HOME=C:/grails-1.3.4
set JAVA_OPTS=%JAVA_OPTS% -Divy.cache.dir=%CD%/target/libraries
set JAVA_OPTS=%JAVA_OPTS% -Dgrails.project.work.dir=target/work

%GRAILS_HOME%\bin\grails.bat %*


As you can see here everything is made project-specific. In "target/libraries" is the ivy cache (instead of home/.ivy2 which causes problems from time to time when working with other technologies such as JSF) and in "target/work" are the project's artifacts.

And live is gooooooooood again :)

Thursday, August 12, 2010

Grails,Teradata and TIME/TIMESTAMP fields

Hi there,

For a long, long time I've been searching for a solution to the incompatibility issue between Teradata server and Teradata JDBC driver in regard to TIME/TIMESTAMP fields. I've finally figured out what's the deal :)

Long story short the database has columns defined as TIME(0) and TIMESTAMP(0) which during updates from Grails (especially the lastUpdated field filled in automagically) causes a number of different errors to come back from the server (5404 for example).

The problem is that java.lang.Date instances are translated using a default precision (which is grater than zero) and the database server is dumb enough to throw an error and not truncate the incoming data.

Solution: update to the latest version of JDBC driver (tested with TeraJDBC 13.10.00.01) and add TSNANO=0,TNANO=0 to connection string and live is good again!

I hope you'll find this solution handy :)

And by all means: have fun!

Tuesday, August 10, 2010

Grails 1.3.4 Released!

Hi there all you Grails geeks!

Yesterday Grails 1.3.4 was released :) Finally some bugs (described in my previous post) were fixed along with one small addition from me.

If you had a domain class that had a generator of type "assigned" and wanted to mockDomain that class then all calls to "save" method were treated as updates. The reason for that was that the distinction was made on the value of "id" field which had to be assigned in case of the "assigned" generator.

So I've proposed a fix for that that'll make the mocked version of save be sensitive to the actual generator type and if it's the "assigned" generator then to act smart instead :)

I hope you'll like it!

Thursday, July 15, 2010

Grails 1.3.3 - testing domain classes FIX

Hi there,

if you're following the TDD principles while using Grails you might be very surprised when upgrading to Grails 1.3.3 because all your unit tests that mocked domain classes and utilized the "save()" instance method all of the sudden fail with some crazy message:

java.lang.NullPointerException
at grails.test.MockUtils.mockDomain(MockUtils.groovy:443)
at grails.test.MockUtils$mockDomain.call(Unknown Source)
at grails.test.GrailsUnitTestCase.mockDomain(GrailsUnitTestCase.groovy:131)
at grails.test.GrailsUnitTestCase.mockDomain(GrailsUnitTestCase.groovy:129)

It's obviously a bug, but don't fear - help is coming!

The bug description in Jira GRAILS-6482 has the answer!

I've allowed myself to go one step further and I've created a base class for those cases where it's needed (DRY - remember?)

package grails.test

import org.codehaus.groovy.grails.plugins.GrailsPluginManager
import org.codehaus.groovy.grails.plugins.PluginManagerHolder

class FixedGrailsUnitTestCase extends GrailsUnitTestCase {

protected void setUp() {
super.setUp();
PluginManagerHolder.pluginManager = [
hasGrailsPlugin: { String name -> true }
] as GrailsPluginManager
}

protected void tearDown() {
super.tearDown();
PluginManagerHolder.pluginManager = null
}
}

Now all my test classes that were touched by this issue inherit from FixedGrailsUnitTestCase and life is good again :)

I hope this will spare you a few minutes :)

Sunday, July 11, 2010

Grails and content negotiation

Hi all,

I've been going through the user's manual for Grails and was shocked that this little piece has slipped my study before. Content negotiation is done in Grails in the most simple and user-friendly way and above all it's almost identical to Ruby on Rails!

I've recently blogged on how to achieve a similar result using ASP.NET MVC (which does require certain amount of manual work)

In Grails everything you need is already built-in. The engine recognizes extensions passed on in the URL automatically as well as request headers (if properly specified by client) and the "withFormat" construct resembles 100% its counterpart in RoR.

The longer I use and study Grails the more I see the power behind it. Even though it might be unstable from version to version (especially the major ones) it's still one of the most comprehensive, well designed and user-friendly web application platforms ever created. I love it!

Have fun!

Monday, May 10, 2010

ICEfaces 1.8 - Next Generation Enterprise Web Development

Hi,

because of the integration of ICEfaces and Grails I started looking at books describing ICEfaces as a framework. Unfortunately I found only one, the "ICEfaces 1.8 - Next Generation Enterprise Web Development".

I was pretty excited at first when I saw the integration itself. Many things are done by convention (so more/less the Grails way), views use Facelts for templating... And in many places ICEfaces is mentioned as the best JSF-based framework out there.

So back to me reading the book...

Well,... hm,... what can I say...

60 pages of blah blah blah about how difficult it was to create web applications in the past with pure servlets and JSP, then the magical discovery that was made that web apps could actually mimic the experience of desktop apps... All nice and dandy but... BOOOORING!!!

I finally came to the page where code started to shine through the misery we've been at for the past decade or so. The thing that killed me at first was the statement that layouts should be done using tables!

I mean come on, guys! Where's the distinction between content and presentation? Where's the semantic web stuff??? Should we abandon CSS completely because IE is so damn cruel in this regard?

They even say that they took this road because of "pragmatism":

You may wonder why we use a <table> for the layout, and even the align attribute, when there is a <div> tag and CSS. The answer is pragmatism.

Whatta heck is that?

Honestly, around page 64 I have decided to stop reading the 290+ pages miserable poem and figure out the way to deal with ICEfaces myself using examples from their website.

The conclusion is that some books could just be better. Nonetheless it's fascinating how things get boring when you step back into the "official enterprise" sort of things having your brain already set on the nature of the web (the request/response kind of thing) by all those MVC-based frameworks like Grails, RoR and ASP.NET MVC...

Have fun!

C# with dynamic: Xml processing

Hi there!

I've been watching Anders Hejlsberg and his presentation about dynamic features introduced in C# 4.0. It got me into thinking that the CTPs and RCs of the language must have been long enough out there for people to do some crazy stuff with it.

I was sooo not mistaken!

Take a look at those couple of things here:
  1. DynamicXmlParser
  2. XmlBuilder

Those are like straight out of Groovy just named a bit differently (the dynamic xml parser is called XmlSlurper) but do mostly the same thing!

C# is getting more and more appealing to my liking of programming languages :)

Have fun!

Thursday, May 6, 2010

Delphi 2010

Hi there!

I'm currently looking at the newest version of old Borland tools namely the "Delphi 2010" environment. I thought that I'll share my thoughts with the rest of you...

There are a few things I'd like to make one thing completely clear: I'm a seasoned Delphi programmer with more that 10 years of experience of using Borland's and then Inprise'es and after that CodeGear's tools to do the job. That being said it is my honor to write a brief review of the latest and the greatest that came out of Embarcadero...

So.. Leaving the "nice words" behind let's see what's in the package!

Let's start with Ruby.
The so called "3rd rail" is not much of a helper since all they have added is the project support, debugging and some code-insight (that's Borland's name for the code hints). After 15 minutes I've reverted back to the only free IDE supporting RoR and I was happy to stop dragging the 3rd leg behind me...

(I just needed to spit it out - sorry :D)

Delphi... Completely different story!
I was using Delphi from version 2.0 when it came out in 1996 I was still using Turbo Pascal and I believed that to be the ultimate choice for a developer. Delphi teached me that doing GUI manually might not be the best idea and also showed me that stuff like code insight are actually working.
Years after that (4 to be exact) I started working for a company in Poland that used Delphi 5 to do some CAE-like application. It was really amazing what one might have accomplished with this tool at hand!
Later we've switched to Delphi 7 which I believe to be the absolutely, completely, unquestionably best IDE in the world EVER! The personal edition had everything a proficient Pascal developer would ever need and was so damn fast that today's Express editions of Visual Studio can only dream about being in such a great shape.

Then came along Delphi 8... For Microsoft .NET 1.0 (as far as I can remember)... It came and went...

I really hoped Delphi 8 was a misunderstanding and that later version of my beloved IDE will follow the usual path. You can imagine how crushed I was when the next version came out and it was based on the same completely lame engine as 8!!! That was the day I thought to myself "OK buddy, it's time to learn something else". With that in mind I was still looking at the evolution of my old IDE just to make sure I made the right choice :)

Today it's the year 2010, Borland is pretty much dead, Inprise is a name no one has ever heard of, CodeGear has a nice ring to it but the phrase "whatta heck is it" surfaces every time I ask someone about it... And today's name for the company is..... Embarcadero!

They still follow that same devil's route Inprise embarked on in 2003 which is a long-starting, incredibly embedded, ugly looking and slow performing IDE.
Sure they have added some cool features to the language. No questions about it... But was that enough to justify a programming language evolution to bring the old, lovely platform down???

Today I'd never ever choose Delphi for my development - at least nothing above version 7 which is in my opinion the best IDE for Pascal-like languages ever created (and I admit I'm a bit tainted but hey.. who's not!).

I'd like to know why Borland and then Inprise, CodeGear and finally Embarcadero didn't see the beauty of the IDE, the language and the huge user base they have had back in the days and shifted to this ugly-looking thing they are feeding us today?


Rust in Peace Delphi! You'll always have a special place in my heart!

Sunday, May 2, 2010

ASP.NET 4 WinForms inside an MVC project

Hi,

I was stunned today watching a presentation by Scott Hanselmann about the new features of .NET 4 especially the fact that you can actually compose in a WebForms page into an MVC application using routing and it all just works!

Imagine you have like a regular MVC 2.0 app and for this one thing that you need to implement having a form instead of a controller and view would be soooo much easier. Now with this simple line of code
routes.MapPageRoute("Form", "Example", "~/Forms/Example.aspx");

you can actually do just that!

In this example I've created a folder called Forms inside of my MVC project and inside that project I've created a WebForms page named Example.aspx. To be able to access that page all I needed to do was to tell the routing thingy that I want the Example.aspx page to be available under /Example and that was it!

Now the question if we should go with WebForms or MVC is gone! You just use whatever suits your needs in the particular case you have to solve and you're done.


Have fun!

Saturday, May 1, 2010

The Great Trio

Hi there,

I wanted to do a comparison of different MVC-based frameworks/application stacks flying around. I was looking lately at Ruby on Rails, Grails and ASP.NET MVC so this comparison is going to tackle those 3 guys.

I've deliberately left out pure Spring MVC, Monorail, all the statefull frameworks and other guys because I personally think they are so much not how like I'd like a framework to look like.

Let's start with Ruby on Rails.

1. Extremely nice, terse and concise language (+)
2. Very large user's group (+)
3. Easy to write CRUD-based applications (+)
4. Very testable (+)
5. Depends on the existence of a database (-, but it can be changed)
6. Tooling support OK (+)
7. Free IDE support is not so great (-)
8. Platform agnostic (when you take into account that you can deploy it virtually everywhere, for example on .NET, Java and pure Ruby interpreter it's mind bothering how far you can go with this guy) (+)

Let's quickly follow up with Grails.

1. The language is for sure better than Java but it still has this Java-feel I personally despise.
2. User's group not so large as in the case of RoR but still large enough (+)
3. Easier than with RoR when it comes to writing CRUD-based applications due to the dynamic scaffolding mechanism (++)
4. Very testable (+)
5. Does not depend on the existence of a database to execute but can use one if you'd like it to (+)
6. Tooling support OK (+)
7. Free IDE support is not so great (-)
8. Easy to deploy on any Java EE container so it runs everywhere (+)

And last but not least - ASP.NET MVC.

1. I love the language (+, yes, it's my personal preference). With the latest addition of "dynamic" keyword (and therefore ease of integration with dynamic languages) it's the most powerful language I've come across so far.
2. User's group is very limited by comparison to the other two. (-)
3. CRUD-based applications are definitely the strongest point of this framework but it's mainly due to the fact that it pushes you in no direction when it comes to database layer. You can choose whatever you want (for me it's a +)
4. Very testable (+)
5. Free IDE support (with tooling) is fantastic! (++)
6. Learning materials are through the roof! (+)
7. Deployable on .NET and Mono but not as broad as with the other two guys (-)

I guess when it comes to my personal preference I'd choose ASP.NET MVC before any of the other tools. However the plugin support in Grails and RoR is really amazing and one can accomplish a lot without writing even one single line of code which is an extreme productivity boost.

Have fun cuz that's all that matters!

ASP.NET MVC and different output formats

Hi there,

I wanted to mimic the nice behavior of Ruby on Rails that allows you to render different content based on the extension passed on in the URL. Here are a couple of examples:

http://localhost/people/list.json <- list of people in JSON
http://localhost/people/show/1.json <- person with id=1 in JSON
http://localhost/people/list.xml <- list of people in XML
http://localhost/people/show/1.xml <- person with id=1 in XML

The part I was not able to figure out right away was the routing configuration. Here's how I finally did it:
routes.MapRoute(
"ActionWithFormat",
"{controller}/{action}.{format}"
);

routes.MapRoute(
"ActionWithFormatAndId",
"{controller}/{action}/{id}.{format}"
);

routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
format = "html"
}
);

As you can see here I've added 2 additional routes (ActionWithFormat and ActionWithFormatAndId) that contain the additional parameter distinguished by "." (dot) instead of "/" (forward slash). I've also took the liberty to modify the Default route so that when no format is passed the default "html" format is what you'd get passed to the action.

Now suppose you'd like to make use of it in the PersonController's Show action:
public ActionResult Show(String id, String format)
{
var person = new { FirstName = "John", LastName = "Doe" };
switch (format)
{
case "json":
return Json(person, JsonRequestBehavior.AllowGet);
default:
return View(person);
}
}

Sure that the RoR's version is shorted, nicer, purer and all that but this little fellow here does the trick as good as the RoR's :)

The key here is that the format is just a string so if you'd like to come up with (let's say) a PdfActionResult then using it in an action is just dead simple!

I hope you'll find it useful!

Friday, April 30, 2010

Reloading lib/ classes in development

Hi,

I've finally found a solution for reloading classes found in rails' lib folder.


In Environment.rb: Add the path for the lib subdirectory where my module was stored, e.g.

config.load_paths += %W( #{RAILS_ROOT}/lib/item_setup )

In Development.rb: Add the name of my Module to the explicitly_unloadable_constants list, e.g.,

ActiveSupport::Dependencies.explicitly_unloadable_constants = 'NameOfMyModule'

If you have other modules you want to automatically reload, use the << explicitly_unloadable_constants array, e.g.,


ActiveSupport::Dependencies.explicitly_unloadable_constants << 'NameOfAnotherModule'

That's more less it.

Monday, April 19, 2010

JavaScript editor in VWD 2010 rocks!!!

Hi there,

I've always been a huge fan on VisualStudio. That fact alone means that my opinion might be biased. However what the VS team made this time with the capabilities of JavaScript editor is simply magic!

Here's what I started with: I've created an ASP.NET MVC project using default settings. That has produced the basic skeleton with Scripts folder in it. Then I've created a new WebSite, copied the jQuery stuff over from that MVC project, created a new JScript file, included jQuery in it and bang! IntelliSense worked just like that!

And it's not only because the $ object is defined! Far from it! Take a look at the following screenshot:


As you can see the IntelliSense worked not only with the stuff that comes directly from $ object but also worked just fine with my plugin as well!

Here's another example that I've tested - ExtJS:


As you can see the editor was capable of parsing all the sources from ExtJS and provide me with the proper IntelliSense for a an object instantiated from Ext.Window prototype!

To add to all that the editor works like a speeding car - fast like I've never seen it before anywhere else!

I'm sure other IDEs (especially those from Java world) provide good developer experience but VWD 2010 is simply the best!

Thanks Microsoft for making this tool available to everyone!


Have fun!

Thursday, April 15, 2010

4Developers conference in Poznan


Hi all,

last month I've visited one of the biggest conferences for developers in Poland. 4 tracks, a lot of very passioned people, lots of great material, good beverages and great service - all in one place.

To the right there's Jarek Palka with me just moments before his presentation on JavaScript on the server side :) Very interesting stuff indeed!

If you'd like to check out the agenda and presenters look at http://2010.4developers.org.pl/

One thing that I must say was a big disappointment was the presentation given by Jacek Laskowski. I was really expecting more from a person like him. Instead we were given a lot of CV stuff and unprofessional jokes.

A very interesting thing I saw there was a presentation by Maarten Balliauw showing not only that programming against the cloud is possible but also that using Microsoft's IDE and tools it's extremly easy! Good job Maarten!

See you again in a year!

Sunday, April 4, 2010

JTK - the killer emerges

Hi all,

recently I've been shocked by how many people write their unit tests without actually putting any assertions in them. Can you imagine that?

Long story short a good friend of mine proposed that we write an application/maven plugin called JTK (which stands for Java Test Killer) that will check the test cases and will provide a clear overview of how many of the tests that the project has make no sense based on the fact that they don't call any assertions.

You can check out the sources on bitbucket.org (it's obviously managed under Mercurial so you'll have to have the client installed which you can get from here)

There's also a couple of tools guarding the process of creation: Hudson and Sonar.
The maven repository (in case you'd like to give it a spin) is here (snapshots only as of this moment but we're planning on releasing it eventually).

We're at a very early stage but if you're interested in helping out let me know!


Tuesday, March 9, 2010

Code coverage 100% - is it feasable?

Recently I've been working on a small project for caching some stuff. I've tried to achieve a good coverage score so I went the TDD way to do so. The results are amazing!

First of all the TDD-way is just gorgeously simple! You write a test first and as soon as the code does not compile (the IDE is a great help here) you start writing production code - but just enough to satisfy the compiler. This way you iterate between test and production code every 30 or so seconds. Then you run the test and see it fail (that's an absolute requirement!). Then you write just enough code for the test to pass and see the test go green.
Stuff always happen. Some times I was just tempted enough to write some production code I knew had no coverage in the test I just wrote (for example damn forced exception handling required in Java - who invented that shit???). So for those parts I've writen separate tests to have all corner-cases covered. That got me to 100% code coverage!

Sure there are some pitiful places like getters and setters that will hold you down but testing them is soooooo easy - you just write a helper method that goes through the properties, sets and gets their value and checks if the property works as expected. It's just like 3 lines of code so one can really afford that to gain the magic 100%

Right now the project is pretty far and let me tell you one thing: changing it is a BREEZE!!! I've probably never worked in a project that I or some else wrote that would be so easy to modify or extend.

The conclusion: Is 100% code coverage hard to achieve? SURE! But we (the professional developers) should still try to achieve it - the peace one gets from it is unbelievable!

Happy covering!

Thursday, January 28, 2010

VMware ESXi 4 and physical disks

Hi there,

if you were ever wondering if it is possible to map a physical disk to a virtual machine in ESXi (even though it's not available using vSphere client) check this article out! It describes step by step how to achieve it! I've checked is using the latest ESXi and it works!


Have fun!

Wednesday, January 20, 2010

jQuery 1.4 Released!

Hi there,

in case you have missed that a new version jQuery (my favorite JavaScript library) has been released. It's the 1.4!

Go check the latest stuff on jQuery at jquery14.com


Saturday, January 16, 2010

JavaEE 6 - first impression

Hi

I've had some delay checking out the latest stuff on JavaEE 6 but finally I've done some looking around and I must honestly say that it is really impressed!

Using maven I've created 4 projects: parent, EJB, WAR and an EAR to house the others. It was relatively easy so I'd say in a scale from 1 to 10 I'd give it an 6 (the same thing using NetBeans scores a complete 10). I've implemented a EJB bean (just a class with one annotation - @Stateless - so the score is 9 because Java is just too damn verbose) and a servlet that uses that bean (that has scored a 6 because of the web.xml part, but maybe there's something new I didn't read about yet to raise the score).

Overall it was very pleasing to see the EJB part without XML configuration whatsoever :)

If you want you can check it out here.


Have fun!

Wednesday, January 13, 2010

Apache ServiceMix - Close encounter

Hi there,

I've been pushed by the project I'm working on to use a very specific platform for integrating services, namely Apache ServiceMix. After spending around 8 hours trying to put this piece of code to some use (and failing miserably) I've decided to blog about it.

It's going to be very negative! You've been warned!

Let me start from the absolute beginning which is installation. Apache ServiceMix comes in 2 different distributions: one directly from Apache and another one maintained by IONA company called Fuse ESB. Both were easy to install (especially easy in the case of Apache distro where it came in the usual zipped form ready to go after unzipping). Iona was a bit more annoying with its GUI-based installer (you guys thing we're morons not able to use zipped folders? I hope not!).

After a brief lecture of the tutorial I've started to do some coding. Well, it's an integration platform after all so I thought some "integration exercise" will be ok to start with. All I wanted to do was to generate some messages in constant intervals using quartz and send them to a message queue provided by ActiveMQ (btw. if you have not tried ActiveMQ I strongly recommend you do check it out! It's an amazing piece of free software!).

My problems started at the very beginning where I've had to browse through tons of poorly structured documentation (on both Iona and Apache web sites) to get the hang of how do I actually proceed with such a use case. At this point one might think it is ok because it is a complicated piece of technology so doing some reading is kind of expected... "Some" being the key word here: 8 hours spent on googling for information without much success is in my humble opinion a total disaster! Have you guys heard about user friendliness and learning curves? Not all of us are ESB gurus but many of us are thrown into the pit where using SMX is needed. You really might have done better here!

Speaking of which, there is actually support you can get - but it's PAID!!! You have to pay some jerks to give you information about stuff they have "packaged" and "maintained", whatever the latter part means. This is theft, to say the least...

Going back to the available materials. There's a "tutorial". A piece of "documentation" written in a very easy to understand way. Had this sh*t been right top to bottom my complains would not have been so hard. I mean can you imagine trying to find out how to deal with grails and be left with a hello-world-style application that does not even compile? Or if it actually compiles then running it is a no-go? Can you beat that?!

Moving on I've finally found the answer on the net (provided by some poor soul trying to do the same thing I did today, meaning get started with SMX) and he already found the errors so I was able to do the changes and see (exactly) one file being moved from one folder to another! Ain't that cool?!

Amazed by the extreme complexity of the solution I made I thought that doing some scripting would be kind of cool and maybe would provide me with some more confidence that not everything is actually lost. So I did some googling and bang! There it is! The actual "component" I need was called servicemix-scripting, there's a Maven archetype that creates an example service unit from scratch so I was hoping to feel a loooot more positive. Again, nothing could have been further from the truth...

servicemix-scripting is not available from Iona repositories but it comes bundled with Apache distribution. It is said that "components are written to be JBI-compliant" so I thought moving one component from one distro to the other should not present any issues since both are JBI compliant. The disappointment was huge when I found out that my service unit not only does not start (the one generated by default using Maven archetype) but the error message says completly nothing. I was like "assembly failed to do something because of administrative error of some damn kind"... ehhhhhhh...

I will not bother you with the "F" words I wanted to say about JMS integration. Suffice to say its description and tutorials are where the sun does not shine.

Well, had this not been part of my daily work I would have thrown it away after like 1 hour (yes, I am extremely pervasive! :) ). Will see if I can squeeze some positive outcome in the coming days out of this product. If I do (or if I don't) I'll blog about it soon.