Abstract Deviance

Just a slight refactoring of my previous sample that I've been meaning to post, since I was doing some stuff that I didn't need to. First of all, you don't need to fetch the input value from the form parameter list, MonoRail will make sure its passed to your controller method. Second, you don't need to create a view for the completion list (the completionlist.vm file), since you can just render the HTML straight from the controller. So your CompletionList() method will now look something like this:

   1:          public void CompletionList(string test)
   2:          {
   3:              List<string> results =
   4:                  new List<string>(new string[] {"Mazda", "BMW", "Mercedes Benz", "Toyota", "Ford", "Volkswagen"});
   5:              if (!string.IsNullOrEmpty(test))
   6:                  results = results.FindAll(delegate(string s) { return s.StartsWith(test, StringComparison.OrdinalIgnoreCase); });
   7:   
   8:              string html = "<ul>";
   9:              foreach (string s in results)
  10:                  html += string.Format("<li>{0}</li>", s);
  11:              html += "</ul>";
  12:   
  13:              RenderText(html);
  14:          }

Being, as previously stated, an Ajax n00b, I found myself today needing to implement text field auto-completion. Since MonoRail has all the nifty AjaxHelper stuff built in, I decided to use the help that was offered, assuming that I'd be able to make it work without actually knowing how it works.

I was, as you've no doubt guessed, mistaken. I shall attempt to document my morning's suffering as a simple example so that others might be spared the pain.

For those of you who are desirous of shiny Ajax goodness, MonoRail "ships" with the prototypejs and script.aculo.us JavaScript libraries which give you all sorts of useful and pretty effects, and makes it pretty easy to reference them in your layout as well. Assuming you have the Castle project templates installed, create a new MonoRail project. To get the project templates you'll need to install Castle using the MSI available for RC2, but don't forget to update the libraries with one of the later builds - I'm using build 442 at the moment. We'll edit the default layout template for our sample to add the JavaScript libraries which will leave it looking like this:

   1:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   2:  <html>
   3:  <head>
   4:      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
   5:      <title>MonoRailAjaxAutoComplete</title>
   6:      <link rel="stylesheet" type="text/css" href="$siteroot/content/css/base.css" />
   7:      $AjaxHelper.GetJavaScriptFunctions()
   8:      $ScriptaculousHelper.GetJavascriptFunctions()
   9:  </head>
  10:  <body>
  11:      $childContent
  12:  </body>
  13:  </html>

That's all you need to get started. Now in our index view for our home "area" we simply use our trusty AjaxHelper to create a text input field that is already all set up for auto-completion, something like this:

   1:  <p>Autocompletion with MonoRail</p>
   2:  <p>$AjaxHelper.InputTextWithAutoCompletion("test", "/home/completionlist.rails", "%{}", "%{}")</p>

Okay, so that will generate a text input field with an id of "test", and we still don't need any code in the corresponding Index() method of our HomeController, since its not doing any real work. But we can see that according to the URL we've provided to our auto-completer, we'll need to add a CompletionList() method, as well as the corresponding view in the "views/home" folder, so that our asynchronous Ajax method has something to call to get a list of options. Now this method will need to return a list of items to display in the auto-completion drop-down list, but it will also need to do some basic filtering of the list based on the current user input. So we'll construct something simple:

   1:          public void CompletionList()
   2:          {
   3:              string query = this.Context.Request.Form["test"];
   4:              List<string> results =
   5:                  new List<string>(new string[] {"Mazda", "BMW", "Mercedes Benz", "Toyota", "Ford", "Volkswagen"});
   6:              if (!string.IsNullOrEmpty(query))
   7:                  results = results.FindAll(delegate(string s) { return s.StartsWith(query, StringComparison.OrdinalIgnoreCase); });
   8:   
   9:              PropertyBag["results"] = results;
  10:          }

There, we have a list of car manufacturers that will be filtered by the input provided by the user, which as you can see is available in our form parameters collection since it is sent by HTTP post with the id of "test" we provided for out text input field. So now we need to fill out our completionlist.vm view so that it returns those results in a manner that will be meaningful to the Ajax script. The script is expected nothing other than an unordered HTML list, so our view is very simple:

   1:  <ul>
   2:  #foreach ($result in $results)
   3:  <li>$result</li>
   4:  #end
   5:  </ul>

And that is pretty much all there is to it.. we have an auto-completing text box. With a few CSS classes added swiped from a script.aculo.us sample to make the result a little prettier, it looks like this:

And, without further ado, here's the sample code.

I’ve had the good fortune to have the opportunity to use Castle MonoRail on a project I’m currently working on which required certain aspects of the system to have a web interface. I’ve been using other bits of the Castle framework, like ActiveRecord, Windsor and Aspect# for quite a while now, but since I’m not often involved in developing web applications (read: actively avoid it) I’d had little incentive to play with MonoRail at all. In fact, it was a brief dalliance with Ruby On Rails and a sudden need to delve once again into the realm of web development that lead me back to it, intrigued by the development model and philosophy that the two frameworks are based on. I won't launch into a song and dance about the virtues of RoR, and by extension, MonoRail; unless you've been living under a rock somewhere you've no doubt seen a hundred pundits heaping praise on it.

What has been particularly interesting to me is the way the various aspects of the Castle Project come together so neatly in MonoRail, almost to the point where one could be forgiven for thinking that it may have been Hammet & Co’s grand design all along. (Indeed, it may well have been, I have no idea.)
I must report that my interest in and subsequent use of MonoRail has had the particular benefit of making me not utterly hate web development for the time being, although how long this burst of enthusiasm will last is anyone’s guess. I’ve never felt particularly comfortable with WebForms development for no reason I can adequately define, and so the RoR/ActionPack approach has been a breath of fresh air, with MonoRail allowing me to implement the concepts in C#, which was a prerequisite for this project.

I thought that since the buzz around Castle and MonoRail is growing it might be worthwhile to post a few tidbits of my ongoing MonoRail adventure, and perhaps help some other poor soul along a road which can be confusing and treacherous at times. I'm not going to go into too much background detail around MonoRail and its functionality as I go, since this is not intended to be a beginner's primer - if you're looking for something along those lines there are a lot of good articles and quite an abundance of sample code, although some of it takes some searching to find. I'll simply concentrate on posting whatever interesting oddities I happen upon, as well as any useful links I find.

Gotcha #1: Identifying your remote forms

MonoRail employs the very nifty concept of Helpers, which allow to manipulate your templates in any number of useful ways. Despite offering you the option to build your own custom helpers, it comes with a bunch of built-in goodies too, one of which is the AjaxHelper, which makes it really easy (eventually) to add some cool Ajax capability to your pages. For a total web/Ajax n00b like me, its been a godsend.

I did run into one problem with it though. I was attempting to do some input validation using another helper, the FormHelper, which aside from outputting all the necessary form and input html tag stuff you need, provides you with a bunch of validation scripts and plugs in the JavaScript for you. Kinda like this:

   1:  $Form.FormTag("page2.rails", "%{}")
   2:   
   3:  <!-- some form stuff -->
   4:   
   5:  $Form.EndFormTag()

 

Only one problem though.. its only when you call EndFormTag() that the helper puts in the JavaScript to trigger the validation. And when you try this:

   1:  $AjaxHelper.BuildFormRemoteTag("page2.rails", "%{}")
   2:   
   3:  <!-- some form stuff -->
   4:   
   5:  $Form.EndFormTag()

...the helper doesn't include the JavaScript you need, I'm guessing because you didn't start the form with the same helper (yes, I know the source code is available and I don't need to guess, I have it checked out of Subversion but I didn't feel like digging into it at the time). Anyway, the fix seemed easy enough - get the JavaScript that it outputs and slap it in myself, closing the form tag without the use of a helper. Only problem was, while the FormHelper assumed a form id of "form1" if you didn't provide one when building the HTML tag, the AjaxHelper was less forgiving. The answer seemed obvious enough since, the method takes a hash table of tag options:

   1:  $AjaxHelper.BuildFormRemoteTag("page2.rails", "%{id='form1'}")

 

Rather frustratingly this did nothing to alleviate my pain, and so I was finally forced to delve into the source. Turns out that, mysteriously, and flying in the face of the way the framework works everywhere else, you need to use the specific string "formId", which the helper will then infer as the tag attribute "id".

   1:  $AjaxHelper.BuildFormRemoteTag("page2.rails", "%{formId='form1'}")

 

Perhaps not the most interesting first post on MonoRail, but hopefully it will save someone else some pain somewhere along the way.

In grand old blogging tradition I decided to use this platform to loudly proclaim my current opinions on the state of things. Actually its nothing quite that ambitious, just another one of those ubiquitous Hot/Not lists. In what will no doubt prove to be a dangerously controversial move I have however decided to break from the accepted norms of blogging, at great personal risk, and will not add a single link to this post. That's right, no links. I know its scary, but I'm sure you all know how to google. In fact, if you're using Firefox you can simply highlight a word or phrase, right-click, and select "Search Google for". If you're still using IE go ahead and add yourself to the second list.

Things displaying a high or increasing level of AWESOMENESS

1. Firefox
lol OSS fanboi kkthxbai

Addendum 1a. Adblock Plus (Firefox extension)
I hate internet advertising.

2. Castle Windsor
I've been using this puppy for ages now, or rather under-using it. Lately I've been learning a lot more about it and understanding how to use it more effectively. It owns.

3. Switchblade Symphony
I'd forgotten how much I like this band. I just wish I had some more .. perfectly legal .. digital tracks of their music to listen to.

4. Andromeda
I never watched beyond the first few episodes of this sci-fi series, for a reason that escapes me now. I'm now trawling through the first four seasons and digging it.

5. Lexa Doig
...is an actress who plays the physical manifestation of the starship's AI in the aforementioned sci-fi show. Oh. My. God.

6. ReSharper
After all these years, life is not worth living without it. I remember the Dark Age when there was no stable version for VS2005.. still gives me chills.

7. NHibernate
Of course, like ReSharper, its a total NHibernate love-fest out there in the wilds of the interweb. What terrifies me is how many lousy ADO implementations are going to give way to god-awful NHibernate implementations. Sadly, good tools don't make up for bad designers. Just look at my source code..

8. Ubuntu Linux + Beryl
Running this at home as my primary OS. Well, when I'm not playing games. Or writing code. Sometimes I use it to watch movies and browse the net. Well, its pretty, ok?

Things manifesting a high or increasing level of SUCK

1. Castle Windsor documentation
Almost non-existent, where there is actually documentation its often misleading at best. Code documentation is also apparently not a priority. I know its a free open-source framework, but I recently had a brief look Spring.NET, and they do a far better job of it.

2. Being sick
I seem to be having a resurgence of the flu. I thought I'd won that battle for this winter.

3. Unit tests that fail for no good reason whatsoever, requiring you to spend hours trying to fix them, only to have them spontaneously start passing again.
Erm, no real elucidation needed on that point.

4. Alphageeks
This term is still cropping up all over the place, and pisses me off no less now than it did when I first read it. We all hate you, Alphageeks.

5. Fitnesse
There really must be an easier way. If I wasn't so apathetic I might try and figure one out.

6. Vista
Oh you hadn't heard? Yeah, it blows.

Of course, fickle as I am, all these opinions are subject to change at any given time, with no warning whatsoever. I also reserve the right not to have to justify any of these opinions for any reason whatsoever.

As modern software developers we exist in an ethereal domain that lies between the world of money and the pursuit thereof, and the world of technology that enables that pursuit. On one side of us are the Business People who construct processes, rules and guidelines that enable them to operate in the real world of people, needs, money and meetings. On the other side are the Technologists, who build magical technological platforms that offer worlds of possibility, but stop short of realising it. Although they might seem so very different, both dwell in the realm of ideas. On the one hand the Business People delve into this realm to imagine innovative ways to provide for, and profit from, the needs of others, sometimes inventing, sometimes finding new ways to implement old ideas. No more or less visionary, the Technologists see a world of possibility in the infinite arrangement of ones and zeros; they imagine new ways to send them, store them, and share them. But, sadly for them and luckily for us, their worlds are just far enough removed that they never quite seem to meet in the middle.

Fuck, there goes my train of thought. Oh well.

In the face of all this AlphaGeek bullshit that’s floating around the crapoblogosphere, it seemed to me that since proposing developer labels is so cool right now the time had come to coin a new phrase, something to safeguard the self-esteem of those of us who know with a dreadful certainty that we don’t fit the profile of the much-vaunted AlphaGeek. Since I needed some way to relieve my chronic boredom anyway I took it upon myself to come up with something, and drawing on my unparalleled lack of imagination, I hereby usher into existence the concept of the OmegaGeek.


As OmegaGeeks we are the antithesis of our alpha brethren: we don’t run at the head of the pack, we dawdle along behind and smell the roses. Sometimes we yell disparaging remarks from the back of the class, but for the most part our intentions are good. We love software development, but it’s not our religion; we got into this because it’s fun, and consider ourselves lucky to have gotten away with doing it for this long. Our sense of self-worth isn’t based on our Code Project articles. We’ve been into the whole ALT.NET thing for a while, but not because it’s cool to be different, just because it pisses us off when people tell us how we should be doing things; when ALT.NET becomes “mainstream” we’ll start advocating the use of datasets and post about it on our blogs, just to annoy software architects. We use new languages and frameworks because it makes our daily grind more amusing, and because we want to make life miserable for the maintenance coders who come along after we’ve moved on. We go to community events, drink all the beer and hit on the geek girls. Our spare time isn’t all spent “reading books, going to conferences, and tinkering” – sometimes we spend it playing WoW, downloading porn or watching old sci-fi TV series. Sometimes we even get away from our computers altogether and concentrate on getting laid.

"On any given day, over 50% of Sun's workforce is remote. MPK20 is a virtual 3D environment in which employees can accomplish their real work, share documents, and meet with colleagues using natural voice communication. Just like on Sun's physical Menlo Park campus, known as "MPK," inhabitants of the virtual MPK20 office building can work together in planned meetings, or can talk informally in unplanned encounters. Unlike the physical campus, however, in MPK20, the community can be built and maintained without the constraints of physical location."

Link

I'm not sure how I feel about this..

Link

Microsoft has released everything you need to build your own copy of MechCommander 2reportedly for the purposes of demonstrating the feature of XNA.

Here's an Adrenaline Vault review of the original game.
"..the rumor is that Microsoft plans on announcing Wednesday a developers kit that would make it possible for anyone to build games for the console, or for PCs, and that the kit will cost only about $100."

Link
This is a nice short concise article on some of the common mistakes developers make when working with databases. My favourite quote:

Too often database code isn't subject to the same standards of design, test, and code review that we demand for the rest of our applications. When you're tempted to put code in the database, take a moment to ask yourself whether it really belongs there.

Ten of the Biggest Mistakes Developers Make With Databases
Redbeard sent me a link to Halo Zero the other day, which I just downloaded and played for the first time, and I must say it's pretty damn cool! It's a 2D fan-made game based on the Halo universe and tells story of Master Chief before the events of the original game. The gameplay seems quite cool, and the 2D graphics are awesome!


It seems that perhaps the constant battle raging in America between science and religion might be rearing its ugly head here at home. I was driving past Sandton Bible Church in Douglasdale yesterday and the notice board outside announced that tonight, 10th March, a debate would be held at Fourways Highschool titled "Creation vs Evolution". I briefly considered attending, since I do like to hear both sides of a good argument no matter what my personal beliefs are, but upon reflection decided that in light of the event having been organised by a church, it was less likely to be a debate, and will more likely be a diatribe against Darwinism. I hope I'm wrong, especially since the event is being held at a school, which I believe should ideally be a secular institution that encourages open-mindedness, reasoned argument and critical thought. I'd be interested to hear from anyone that does attend.

Anyway, for those who are interested in a good blog about evolutionary biology, The Loom is an excellent resource.
 

Windsor kicks ass. Db4o kicks ass. Aspect# kicks ass.

All of them together kick more ass than you can shake a stick at. God help any maintenance coders who arrive after you’re gone though. It's all so elegant, but to the uninitiated (which included me not so long ago) it looks more than a little like Black Magic.

I took a strange trip to arrive at this combination for a (forever ongoing) pet project of mine. I had converted it from my own ORM framework to use NHibernate, but was having some issues (I should have used ActiveRecord). Having played with Db4o briefly in the past, and not necessarily wanting to be tied to a relational database anyway, I had another look at it, and a brief glance at Bamboo (which I really must play with sometime). Db4o was an easy choice – the ability to use 2.0’s anonymous methods as a query language was just too cool.

But let’s take a step back. My not-so-recent interest in Nhibernate led me predictably to Hibernate, which reawakened a short-lived interest in Java. I downloaded Eclipse and IntelliJ, but settled on Netbeans 5.0, which has a GUI designer worthy of Visual Studio (better, if you factor in my frustration at having VS crash whenever the Designer has to render one of my custom controls). Anyway, the Java flirtation didn’t last long, but it led me back to some Inversion of Control/Dependency Injection frameworks I’d promised to look in on from time to time, like Spring.

Somewhere in between I decided to revisit aspect-oriented programming, which I’d been meaning to try out for ages (since I first heard about it back in the mists of time). A quick search led me back to the Castle Project, from whence comes the DynamicProxy, which is at the core of the magic of Nhibernate, and which had become the new home for Aspect#. And there it was: Windsor. It’s all very incestuous.

And so that brings me here, to where I am. Enthused.

More Posts Next page »