Wednesday, February 24, 2010

Falling in line to the (micro)templating frenzy

A few weeks ago I would've laughed in your face if you told me I was gonna fall in line to the templating frenzy that seems to be spreading like a virus between coders. Now - one way or the other - I seem to be infected.

I recently tackled the challenge of generating a DTO layer (including mapping logic) from WCF service client using T4 (with no editor whatsoever - don't get me started). I honestly thought I was gonna blog about that sooner or later but then I immediately got shuffled around like a puppet to some front-end work (I am talking web here) and faced the lame-ass ordinary challenge of dynamically injecting repetitive structures into a given page in response to a given event (click-click-click-click ... click).

Coming from that T4 work, templating obviously came to mind as a way not to get bored: wouldn't it be great if there was something like T4 for js? It sounded crazy at first, but I started looking into it and immediately found the John Resig Micro-Templating engine.

There was no way I was gonna pass on that and, to be honest, the only alternatives were pretty lame:
  • implement your own templating engine 
  • shamelessly hard-code the markup to inject in your .js functions (as I always did before)
So I started playing with it and managed to stumble upon the Rick Strahl variation to it, which actually uses T4 syntax (it sure doesn't look like a coincidence) and also has a nice addition for error handling.

Anyway, this is getting too long: here's an example where I am adding divs with a bunch of input fields to a container, ids are generated at runtime depending on how many divs we have in there. It's ugly as fuck it gets, but it drags the message across (I think).

Let's start: 
you need to shove the templating engine function in a file. I called it templating.js and you can just copy paste whatever Rick Strahl has on his article. Once you've done that, add templating.js and jQuery.js as external script files to your html.

Once you have that in place, it's time to populate you jQuery init function and add your micro-template (the micro-template is added in a script element defined as text). This should be pretty straightforward if you read the comments:
<!-- all this goes into the head section --> <script type="text/javascript"> $(document).ready(function() { //IDs for the first div var idsArray = { divId: "div_0", input1Id: "input1_0", input2Id: "input2_0" }; // logic to add the first div function onLoad() { var templ = $("#myRepeaterTemplate").html(); var parsed = parseTemplate(templ, idsArray); $("#myTarget").html(parsed); } // inject the first div onLoad(); // Add onclick handler to button w/id addBtn $("#addBtn").click(function() { //1. count how many divs var size = $("#myTarget > div").size(); //2. generate name value pairs var myArray = { divId: "div_" + size, input1Id: "input1_" + size, input2Id: "input2_" + size }; //3. invoke parseTemplate var templ = $("#myRepeaterTemplate").html(); var parsed = parseTemplate(templ, myArray); //4. append $("#myTarget").append(parsed); }); }); </script> <script id="myRepeaterTemplate" type="text/html"> <div id="<#= divId #>" > <input id="<#= input1Id #>" type="text" value="some input" /> <input id="<#= input2Id #>" type="text" value="some input" /> </div> </script>

And the following is what you need in the body of the page for this to work:

<div id="myTarget">
   <p>this stuff should be wiped on load</p>
</div>
<input id="addBtn" type="button" value="Add" />

This is just a very basic example that should be suitable when you just want to inject some markup given a template, but you can put actual js logic into the template. For a nice example of that have a look at this nice example here.

I am a lazy-ass late adopter, and if I am using this stuff  (talking about the templating frenzy in general) - it generally means it can't be ignored much longer. Do so at your own risk.

Wednesday, February 3, 2010

GetProperties(BindingFlags.DeclaredOnly) returns no properties

If you're trying to use reflection to retrieve a list of properties and you want only the properties declared in a given type but not the inherited ones, msdn says you need to call GetProperty passing down the DeclaredOnly binding flag.

What msdn doesn't say is that if you just pass down DeclaredOnly you'll get nothing back (and if you ended up on this post through a google search that's probably the reason why).

In order to get back the properties you're looking for you need to pass down also the Public and Instance binding flags - smt like this should work:
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
This is probably working "as designed" but could definitely make you waste a bit of time (as it did for me).

In the spirit of human hive intelligence - hope it helps some other average Joe out there.



Friday, January 22, 2010

Are MVP and AJAX a good match?

Can't seem to get through a conversation these days without talking about the MVP pattern - so here's a boring post about just that.

If you need extensive unit testing coverage, adopting the MVP pattern in your app is probably going to make your life easier. In the specific case of web apps though there are a number of considerations to take into account.

First of all, not everyone seems to be aware that MVP was retired a while ago, and it has been split by the author in two different patterns: Passive View and Supervising Controller. In my experience, when talking about MVP, most people implicitly refer to the Passive View model.

Passive View looks like a pretty good fit for the ASP.NET post-back model, where your presenter triggers updates on the view server-side and everyone can feel comfortable they're following the pattern. This is all good till you start sneaking loads of AJAX calls into your page, resulting in a view that has got now inherent behavior (in this discussion I am considering all the client-side scripting as inherent behavior of the view - which might be a wrong assumption, if so please slap me hard). Still nothing wrong, till the AJAX calls from the view go straight down to the model to fetch data which is used by the view to update itself. Bare in mind that here the problem is not so much the view that updates itself, but the fact that, going straight to the model, the view is no longer passive and the presenter doesn't trigger the update (as we obviously don't have a client-side equivalent).

The considerations above seem to rule out the passive view approach for AJAX intensive apps. In fact, in the Passive View pattern the view is only allowed to talk to the presenter (usually through some messaging mechanism). All this to say that if you're adopting MVP in a web project that requires AJAX calls from the client representation of the view to the service layer (the model), you better specify you're not adopting Passive View, because - at all effects - you're not!

But maybe not all is lost.

If Martin Fowler makes a clear distinction between passive view and selective controller there must be a reason (and a pretty good one for sure). In fact, in a scenario where the view selectively talks to the model and updates itself and "the controller/presenter defers as much as it is reasonable to the view", you're basically adopting the Supervising Controller variation of the MVP pattern (even if you don't know). This scenario is particularly well suited in case of databindings, and even if this is not strictly true in the case of loads of AJAX calls down to the model, I would probably see this AJAX scenario a good fit for this variation of the pattern (compared to passive view).

I find it might be easier for people to get it right if they feel they're closely following the pattern - this is definitely true for me!

So in answer to the title question: Are MVP and AJAX a good match?
I think they might - as long as you're not talking about Passive View!

Saturday, January 9, 2010

What a .NET guy likes about AppEngine

I recently completed work on an app built on AppEngine and Google Web Toolkit:



It's basically a logo design app with a twist - follow the link if you wanna find out more on the app itself.

To the point, the team on this project came mostly from a Java background and even though I am mainly a .NET nut I also have a bit of Java under the belt, so this project represented the perfect opportunity for me to get some sweet  AppEngine + GWT action.

So here we go, here's the good old list of things I really liked about the setup on this project (Java/AppEngine/GWT on Eclipse + Google plugins) compared to the setup I am more familiar with (C#/ASP.NET + SQLServer + Azure hosting, all on VS):
  • With AppEngine and the Google-Datastore you don't have to cope with SQL or SQLServer (and if you follow this blog you know how I feel about SQL)
  • You can literally deploy your app with one-click from the eclipse plug-in (all extremely easy to setup - and it works)
  • Hosting is free on google appspot (if you don't go over the free quotas, and quite cheap after that anyway)
  • GWT = virtually no messing around with javascript (I do like javascript but not if I am in a hurry)
  • .NET/VS to JAVA/Eclipse transition turned out to be OK (Eclipse is pretty cool) with people around to rely on
So far AppEngine has proven reliable - the app still runs a bit slow but we did not put any effort into improving performance (I've seen ASP.NET apps running much slower, and it rarely boils down to hosting anyway) - stay tuned for more.

Thursday, December 24, 2009

Nightmare before Christmas: How to use JFace + SWT standalone

I could've as easily called this Eclipse plugins from HELL, but being Christmas and all I thought I would go for the Christmas thing, which gives me the opportunity to wish Merry Xmas to all the geeks who happen to be reading this lame-ass blog over the holidays instead of watching Star Trek as per tradition.

Being mainly a .NET guy, I am not too familiar with the eclipse platform, but I desperately needed to put together a quick UI and decided to go with JFace and SWT after @tarelli suggested so (he's the JAVA guy). Unfortunately, at the time I didn't realize he was talking about an Eclipse plugin project and not about using JFace and SWT in a standalone Java app.

So I went on and got started with some nice tutorials specific to running JFace + SWT standalone, and some more gentle introductions.

Time to get my hands dirty, so I started a new Java project, and dropped in some of the code from the tutorials. In order to get it build I needed to import JFace and SWT plugins as external jars, which I could not find anywhere in my plugins folder (I am on Galileo C:\eclipse 3.5\plugins). I needed to somehow get the damn plugins, but could not quite figure out how to get only those I needed from Help --> Install Software Updates, so I ended up pulling down anything to do with Eclipse SDK. To my delight the SWT and JFace plugins were there (in the plugins folder) after the lengthy process of downloading tons of stuff I didn't need.

After a bit of mocking about (blindly trying to import anything with jface or swt in it) I managed to understand which jars I needed to import to get the damn thing to build (org.eclipse.jface_3.5.1.M20090826-0800.jar and org.eclipse.swt.win32.win32.x86_3.5.1.v3555a.jar) I started mocking about with the code and spent a good while playing around with ContentProviders, ListViewers and so forth. Everything was building nicely, but as soon as I tried to run it as java application got the cold shower:

Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/core/runtime/IProgressMonitor
    at demo.ui.test.EntryPoint.main(EntryPoint.java:18)
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.runtime.IProgressMonitor

Apparently some type was missing somewhere. I've seen a lot of sh*t working on Visual Studio and all, but errors don't get much more cryptic than this.

After a good while, after unfruitfully trying to offline troubleshoot the heck out of my project (offline troubleshooting is just madness but I was waiting the phone company to turn on my broadband in the new apt i moved to recently), I reverted to @tarelli, the eclipse guru who got me into this mess, and begged for help: he promptly told me that I was in a bit of a feckin' mess, and if I wanted to get out of it alive I would've had to create a Plugin Project "with a view" and take it from there. I tried, and he was right, but I did not want a plugin and all the overhead that comes with it, so I kept pulling my hair for several hours with no luck, then went to bed. I felt rightly and truely screwed, if you want.

Luckily the day after the phone company turned on my broadband and I could stop passively obsessing about the problem and started aggressively abusing google in search of a solution to the problem.

After a not too long research (God bless THE INTERNET), turns out that if you want to use JFace + SWT outside a plugin based project you need some other jars. Basically if you're using JFace and SWT in a plugin project runtime dependencies are managed for you through the manifest file (I seem to understand) but if you go for the rogue option of having SWT running standalone then you need to know you need that stuff.

In the specific case of the IProgressMonitor thingy, adding a reference to the org.eclipse.equinox.common jar did the trick. After that I got the same error on a different class, EventManager, and after a couple of blind trials I got it working by importing the org.eclipse.core.commands jar. Obviously, not a mention of this in the tutorials, as I seem to understand there was a bit of refactoring on those packages after those tutorials were drafted (looks like this problem is around since eclipse 3.2 --> read this bug report for further info).

What can I say? If you're coming from .NET sometimes Java == Pain.