Monday, 30 January 2012

JavaScript - getting to know the beast...

So it's 2010 and I've started using jQuery. jQuery is a JavaScript library. This means that I'm writing JavaScript... Gulp!

I should say that at this point in time I *hated* JavaScript (I have mentioned this previously). But what I know now is that I barely understood the language at all. All the JavaScript I knew was the result of copying and pasting after I'd hit "view source". I don't feel too bad about this - not because my ignorance was laudable but because I certainly wasn't alone in this. It seems that up until recently hardly anyone knew anything about JavaScript. It puzzles me now that I thought this was okay. I suppose like many people I didn't think JavaScript was capable of much and hence felt time spent researching it would be wasted.

Just to illustrate where I was then, here is 2009 John's idea of some pretty "advanced" JavaScript:

function GiveMeASum(iNum1, iNum2) 
  var dteDate = new Date();
  var iTotal = iNum1 + iNum2;
  return "This is your total: " + iTotal + ", at this time: " + dteDate.toString();

<input type="text" id="Number1" value="4" />
<input type="text" id="Number2" value="6" />
<input type="button" 
  value="Click Me To Add" 
  onclick="alert(GiveMeASum(parseInt(document.getElementById(Number1).value, 10), parseInt(document.getElementById(Number2).value, 10)))" />

I know - I'm not to proud of it... Certainly if it was a horse you'd shoot it.

Basically, at that point I knew the following:
  • JavaScript had functions (but I knew only one way to use them - see above)
  • It had some concept of numbers (but I had no idea of the type of numbers I was dealing with; integer / float / decimal / who knows?)
  • It had some concept of strings
  • It had a date object

This was about the limit of my knowledge. If I was right, and that's all there was to JavaScript then my evaluation of it as utter rubbish would have been accurate. I was wrong. SOOOOOOOOOOOO WRONG!

I first realised how wrong I was when I opened up the jQuery source to have a read. Put simply I had *no* idea what I was looking at. For a while I wondered if I was actually looking at JavaScript; the code was so different to what I was expecting that for a goodly period I considered jQuery to be some kind of strange black magic; written in a language I did not understand.

I was half right. jQuery wasn't black magic. But it was written in a language I didn't understand; namely JavaScript. :-( Here beginneth the lessons...

I started casting around looking for information about JavaScript. Before very long I discovered one Elijah Manor who had helpfully done a number of talks and blog posts directed at C# developers (which I was) about JavaScript. My man!

For me this was all massively helpful. In my development life so far I had only ever dealt with strongly typed, compiled "classical" languages. I had little to no experience of functional, dynamic and loosely typed languages (essentially what JavaScript is). Elijahs work opened up my eyes to some of the massive differences that exist.

He also pointed me in the direction of the (never boring) Doug Crockford, author of the best programming book I have ever purchased: JavaScript: The Good Parts. Who could not like a book about JavaScript which starts each chapter with a quote from Shakespeare and still comes in at only a 100 pages? It's also worth watching the man in person as he's a thoroughly engaging presence. There's loads of videos of him out there but this one is pretty good: Douglas Crockford: The JavaScript Programming Language.

I don't want to waste your time by attempting to rehash what these guys have done already. I think it's always best to go to the source so I'd advise you to check them out for yourselves. That said it's probably worth summarising some of the main points I took away from them (you can find better explanations of all of these through looking at their posts):
  1. JavaScript has objects but has no classes. Instead it has (what I still consider to be) the weirdest type of inheritance going: prototypical inheritance.

  2. JavaScript has the simplest and loveliest way of creating a new object out there; the "JavaScript Object Literal". Using this we can simply
    var myCar = { wheels: 4, colour: "blue" }
    and ladies and gents we have ourselves a car! (object)

  3. In JavaScript functions are first class objects. This means functions can be assigned to variables (as easily as you'd assign a string to a variable) and crucially you can pass them as parameters to a function and pass them back as a return type. Herein lies power!

  4. JavaScript has 6 possible values (false, null, undefined, empty strings, 0 and NaN) which it evaluates as false. These are known as the "false-y" values. It's a bit weird but on the plus side this can lead to some nicely terse code.

  5. To perform comparisons in JavaScript you should avoid == and != and instead use === and !==. Before I discovered this I had been using == and != and then regularly puzzling over some truly odd behaviour. Small though it may sound, this may be the most important discovery of the lot as it was this that lead to me actually *trusting* the language. Prior to this I vaguely thought I was picking up on some kind of bug in the JavaScript language which I plain didn't understand. (After all, in any sane universe should this really evaluate to true?: 0 == "")

  6. Finally JavaScript has function scope rather than block scope. Interestingly it "hoists" variable declaration to the top of each function which can lead to some very surprising behaviour if you don't realise what is happening.

I now realise that JavaScript is a fantastic language because of it's flexibility. It is also a deeply flawed language; in part due to it's unreasonably forgiving nature (you haven't finished your line with a semi-colon; that's okay - I can see you meant to so I'll stick one in / you haven't declared your variable; not a problem I won't tell you but I'll create a new variable stick it in global scope and off we go etc). It is without question the easiest language with which to create a proper dogs breakfast.

To get the best out of JavaScript we need to understand the quirks of the language and we need good patterns. If you're interested in getting to grips with it I really advise you to check out the Elijah and Dougs work - it really helped me.

Tuesday, 24 January 2012

What on earth is jQuery? And why should I care?

What on earth is jQuery? What's a jQuery plugin?

These were the questions I was asking myself shortly after discovering that jqGrid was a "jQuery plugin". I'd been vaguely aware of the phrase "jQuery" being increasingly mentioned on various techical websites since about 2009. But for some reason I'd felt no urge to find out what it was. I seem to remember that I read the name "jQuery" and jumped to the perfectly logical (in my head) conclusion that this must be a Java SQL engine of some sort. (After all "j" as a prefix to anything so far had generally been Java and "Query" just rang of databases to me.) Clearly I was wrong - life's full of surprises.

I soon discovered that, contrary to expectations, jQuery had nothing to do with Java *and* nothing to do with databases either. It was in fact a JavaScript library written by the amazing John Resig. At the time I had no love for JavaScript. I now realise I knew nearly nothing about it but my feeling was that JavaScript was awful - evil even. However, given JavaScripts ubiquity in the world of web it seemed to be a necessary evil.

I took a look at the jQuery website and after reading round a bit I noticed that it could be used for Ajax operations. This lead to me reaching the (incorrect) conclusion that jQuery was basically an alternative to the Microsoft Ajax library which we were already using to call various Web Services. But I remained frankly suspicious of jQuery. What was the point of this library? Why did it exist?

I read the the blog by Scott Gu announcing Microsoft was going to start shipping jQuery with Visual Studio. The Great Gu trusted it. Therefore, I figured, it must be okay... Right?

The thing was, I was quite happy with the Microsoft Ajax library. I was familiar with it. It worked. Why switch? I saw the various operations Scott Gu was doing to divs on the screen using jQuery. I didn't want to do anything like that at all. As I said; I had no love for JavaScript - I viewed it as C#'s simple-minded idiot cousin. My unofficial motto when doing web stuff was "wherever possible, do it on the server".

I think I would have ignored jQuery entirely but for the fact of jqGrid. If I wanted to use jqGrid I had to use jQuery as well. In the end I decided I'd allow it house room just for the sake of jqGrid and I'd just ignore it apart from that. And that's how it was for a while.

Then I had an epiphany. Okay - that's overplaying it. What actually happened was I realised that something we were doing elsewhere could be done faster and easier with jQuery. It's something so ridiculously feeble that I feel vaguely embarrassed sharing it. Anyway.

So, you know the css hover behaviour is only implemented for anchor tags in IE6? No? Well read this Stack Overflow entry - it'll clarify. Well, the app that I was working on was an internal web application only used by people with the corporate installation of IE 6 on their desktops. And it was "terribly important" that buttons had hover behaviour. For reasons that now escape me we were doing this by manually adding inline onmouseover / onmouseout event handlers to each input button on the screen in turn in every page in the Page_Load event server side. I think we were aware it wasn't fantastic to have to wire up each button in turn. But it worked and as with so many development situations we had other pressures, other requirements to fulfil and other fish to fry - so we left it at that.

And then it occurred to me... What about using the jQuery class selector in conjunction with the jQuery hover event? I could have one method that I called on a page which would wire up all of my hover behaviours in one fell swoop. I wouldn't need to do input-by-input wireups anymore! Hallelujah! This is what I did:

The buttons I would like to style:

<input type="button" value="I am a button" class="itIsAButton" />
<input type="button" value="So am I" class="itIsAButton" />
<input type="button" value="Me too" class="itIsAButton" />

My CSS (filter, by the way, is just linear gradients in IE 6-9):

  filter:progid:DXImageTransform.Microsoft.Gradient (GradientType=0,StartColorStr='#ededed',EndColorStr='#cdcdcd');   

.itIsAButton:hover, .itIsAButton_hover /* "_hover" is for IE6 */
  filter:progid:DXImageTransform.Microsoft.Gradient (GradientType=0,StartColorStr='#f6f6f6',EndColorStr='#efefef');   

My jQuery:

$(document).ready(function () {

  //Add hover behaviour on picker buttons for IE6
  if (($.browser.msie) && 
      (parseInt($.browser.version, 10) < 7)) {

    var fnButtonHover = function (handlerInOut) {

      var $btn = $(this);
      var sOriginalClass = $btn.prop("class");

      if (handlerInOut.type === "mouseenter") {

        //If not already hovering class then apply it
        if (sOriginalClass.indexOf("_hover") === -1) {

          $btn.prop("class", sOriginalClass + "_hover");
      else if (handlerInOut.type === "mouseleave") {

        //If not already non-hovering class then apply it
        if (sOriginalClass.indexOf("_hover") !== -1) {

          $btn.prop("class", sOriginalClass.split("_")[0]);


And it worked. I didn't really understand this much about this jQuery "thing" at that point but I could now see that it clearly had at least one use. I've come to appreciate that jQuery is one of the best pieces of software I've ever encountered. Over time I may go further into some of the good stuff of jQuery. It is, quite simply, brilliant.

Saturday, 14 January 2012

jqGrid - it's just a far better grid

The year was 2010 (not really that long ago I know) and the project that I was working on was sorely in need of a new grid component. It was an ASP.NET WebForms project and for some time we'd been using what was essentially a glorified datagrid which had a few extra features implemented to allow us to change column order / columns displayed / copy contents to clipboard etc.

Our grid worked perfectly fine - it gave us the functionality we needed. However, it looked pretty terrible, and had some "quirky" approaches in place for supporting IE and Firefox side by side. Also, at the time we were attempting to make our app seem new and exciting again for the users. The surprising truth is that users seem to be more impressed with a visual revamp than with new or amended functionality. So I was looking for something which would make them sit up and say "oooh - isn't it pretty!".

Unfortunately the nature of the organisation I was working for was not one that lended itself to paying for components. They were occasionally willing to do that but the hoops that would have to be jumped through first, the forms that would need to be signed in triplicate by people that had nearly nothing to do with the project made that an unattractive prospect. So I began my search initially looking at the various open source offerings that were around.

As a minimum I was looking for something that would do what our home-grown component did already (change column order / columns displayed / copy contents to clipboard etc) but hopefully in a "nicer" way. Also, I had long been unhappy with the fact that to get our current grid to render results we did a *full postback* to the server and re-rendered the whole page. Pointless! Why should you need to do all this each time when you only wanted to refresh the data?

Instead I was thinking about using an Ajax approach; a grid that could just get the data that it needed and render it to the client. This seemed to me a vastly "cleaner" solution - why update a whole screen when you only want to update a small part of it? Why not save yourself the trouble of having to ensure that all other screen controls are persisted just as you'd like them after the postback? I also thought it was probably something that would scale better as it would massively reduce the amount of data moving backwards and forwards between client and server. No need for a full page life cycle on the server each time the grid refreshes. Just simple data travelling down the pipes of web.

With the above criteria in mind I set out on my Google quest for a grid. Quite soon I found that there was a component out there which seemed to do all that I wanted and far more besides. It was called jqGrid:

Oooh look at the goodness! It had both column re-ordering and column choosing built in!: This was a *very promising sign*!

Now it's time for me to demonstrate my ignorance. According to the website this grid component was a "jQuery plugin". At the time I read this I had no idea what jQuery was at all - let alone what a plugin for it was. Anyway, I don't want to get diverted so let's just say that reading this lead to me getting an urgent education about some of the client side aspects of the modern web that I had been previously unaware of.

I digress. This component did exactly what I wanted in terms of just sending data down the pipe. jqGrid worked with a whole number of possible data sources; XML, Array but the most exciting for me was obviously JSON. Take a look a the grid rendered below and the JSON that powered it (all from a simple GET request):

As you can see from the above screenshot, the grid has populated itself using the results of a web request. The only information that has gone to the server are the relevant criteria to drive the search results. The only information that has come back from the server is the data needed to drive the grid. Simple. Beautiful. I loved it and I wanted to use it. So I did!

I had to take a few steps that most people thinking about using a grid component probably wont need to. First of all I had to write an ASP.Net WebForms wrapper for jqGrid which could be implemented in a similar way to our current custom datagrid. This was because, until the users were convinced that the new grid was better than the old both had to co-exist in the project and the user would have the option to switch between the two. This WebForms wrapper plugged into our old school XML column definition files and translated them into JSON for the grid. It also took datasets (which drove our old grid) and translated them into jqGrid-friendly JSON. I wanted to power the jqGrid using WebMethods on ASPX's. After a little digging I found Dave Ward of Encosia's post which made it very simple (and in line with this I switched over from GET requests to POSTs). Finally I wrote some custom javascript which added a button to jqGrid which, if clicked, would copy the contents of the jqGrid to the clipboard (this was the only bit of functionality that didn't appear to be implemented out of the box with jqGrid).

I think I'm going to leave it there for now but I just wanted to say that I think jqGrid is a fantastic component and it's certainly made my life better! It's:
I think Tony Tomov (the man behind jqGrid) has come up with something truly brilliant. It's worth saying that the equally brilliant jQueryUI team are in the process of writing an official jQuery UI grid component which uses jqGrid as one of its inspirations. However, this is still a long way from even a "zero feature" release. In the meantime jqGrid is continuing to go from strength to strength and as such I heartily recommend it.

Finally, you can take a look at jqGrid's source on GitHub.

Saturday, 7 January 2012

Standing on the Shoulders of Giants...

It started with Scott Hanselman. I had no particular plans to start a blog at all. However, I was reading Scott Hanselman's turn of the year post and I was struck with an idea.

First, let me give a little background about myself. I'm a software developer. I've been in the industry for coming up to 15 years. I started out professionally writing call centre software. I moved on to code in a variety of different industries from straight IT to marketing and, for the last 7 years, finance.

Though I initially started out writing in Delphi I fast found myself moving toward the Microsoft "stack of love". I should say that this move was not because I instinctively liked Microsofts stuff (in fact in the beginning I actively disliked it - moving from Delphi 3.0 to Visual Studio 5 left me finding Microsoft's offering very much wanting). Rather it was pragmatic. I needed a job and at the time VB was a far more transferable skill than Delphi. What with the all encompassing dot-com bubble of the late 90's I soon found myself working in the webtastic world of classic ASP (weep) and VB server components (remember them?).

Though things can improve - and in my opinion they really did when Microsoft coughed up the first furball of ASP.NET Beta in (I think) 2001. I grabbed on with both hands. Since that point I've been earning my bread pretty much, though not exclusively, in the ASP.NET universe.

The one thing that might not be clear from the above curriculum vitae is this: I AM A COMPLETE AMATEUR. I mean this in both senses of the word:

  1. I have no formal training to speak of - I didn't do a computer sciences degree. In fact my first real coding experience was writing a program in Locomotive Basic for my father on our humble Amstrad CPC.
  2. That said, I love it. I find writing code an intellectually, emotionally, creatively satisfying act. And whilst I undoubtedly have less of the theoretical knowledge which most professional developers seem to have, I probably counter-balance that with a hunger to keep learning and keep trying new things. And since software never sits still that's probably just as well. Keep watching the horizon - there will be something coming over it!

    And it's worth saying, I have an instinct for developing which serves me pretty well. I'm good at coming up with elegant and pragmatic solutions. Put simply: I'm good at making code work.

So back to the point. In my daily work life, like any other developer, I am repeatedly called on to turn someones requirement into a reality. Very rarely do I achieve this on my own. Like most of us I'm a dwarf standing on the shoulders of giants. There's a lot of people out there who come up with useful tools / components / plug-ins that make it possible for me to deliver much more than I would given my own abilities.

So that's what I want to do: I want to talk about the tools, components and techniques that I have found useful in the everyday working life of a developer. It's likely to be quite a "webby" blog as I probably find that the most interesting area of development at the moment.

I don't know how often I will write but my plan is that when I do, each time I'll talk about something I've found useful - why I found it useful, what problems it solved, what issues it still presented me with and so on. This is probably not going to be a "techie techie" blog. Rather a blog that deals with the situations that can confront a developer and how I've responded to them. I hope you find it interesting. And if you don't; please keep it to yourself :-)