Show/hide various sections of a page using JQuery and CSS

In this post I’ll go over how you can utilize JQuery and CSS classes to show/hide various parts across the different sections of a page without creating a mess!

The Challenge
You’ve got a wizard-like page with multiple steps and you want to be able to show/hide various elements based upon the current step. Below is a dumbed-down example:

The colored boxes represent the parts that are being shared across the various sections of the page. For instance, the green box is being shared by the ‘Image Selection’ and ‘Order Confirmation’ sections. While the red box is being shared by all three sections.

So the challenge is: How do we show/hide these various parts across the sections of the page without making a mess? And by mess, I refer to duplicate code and/or little <% if..then %> snippets scattered throughout the page.

The Solution
By using some CSS/JQuery trickery, of course! What we’ll do is introduce some CSS classes that we will then apply to the various parts for which we need to handle visibility. Here are the classes that we will need:

  • section – Represents a section
  • requestor – Represents the requestor section
  • image-selection – Represents the image selection section
  • confirmation – Represents the order confirmation section

The CSS classes will then be applied to the various parts based upon the section inside which the part is to be shown:

<div>
  <input type='hidden' id='section-to-show' />
  <table>
    <tr>
      <td>Request Type:</td>
      <td class='section requestor'>
        <select>...</select>
      </td>
      <td class='section image-selection confirmation'>
        <%= selectedRequestType %>
      </td>
    </tr>
    ...
    <tr>
      <td>First Name:</td>
      <td><%= firstName %></td>
    </tr> 
    <tr>
      <td>Last Name:</td>
      <td><%= lastName %></td>
    </tr> 
    <tr class='section requestor confirmation'>
      <td>Email</td>
      <td><%= email %></td> 
    </tr>
    ...
    ...
    <tr class='section image-selection confirmation'>
      <td>Image</td>
      <td class='section image-selection'>
        Browse...
      </td>
      <td class='section confirmation'>
        <img src='..' />
      </td>
    </tr>
    ...
  </table>
</div>

A few things to highlight:

– The hidden input field ‘section-to-show’ indicates the section to display. It’s value is set by the server-side code.
– There are two table columns inside the first table row. Only one will be visible based up the section that is being displayed.
– The first name and last name table rows don’t have any classes applied to them. This is because they are always visible.
– The last table row shown above gives an example of how you can make the visibility conditional for both the table row and the table column.
– I skipped various rows in the HTML form above to save some typing and to avoid being repetitive.

And now for the JQuery:

  $(document).ready(function(){
 
    // hide all sections to begin with
    $('.section').hide();
 
    current_section = $('#section-to-show').val();
    $("." + current_section).show();
  });

And there you have it – a cleaner alternative to showing and hiding various parts across the sections of a page!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Writing integration tests for ASP .NET with Selenium 2.0 – Part 1

This is the first in a series of posts on writing integration tests for ASP .NET using the Selenium 2.0 web application testing system.

UPDATE: This post was updated on April 15, 2012 to explain how to setup and configure Selenium 2.0.

In this post, I explain what Selenium is, why use it and how to setup and configure it. In the next subsequent posts, I’ll do a code walk-thru and also share some advanced scenarios.

What is Selenium?
The best description of Selenium is probably the one mentioned on their website:

“Selenium automates browsers. That’s it. What you do with that power is entirely up to you. Primarily it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.”

Why use Selenium?
There are other integration testing web frameworks out there such as WaitN or the Lightweight Test Automation Framework for testing ASP .NET web apps. So, why use Selenium? Here are the main reasons why picked it:

  1. Selenium allows you to record test scenarios manually (by browsing to specific pages and clicking buttons, etc.) as well as programmatically (by coding up a test case). Thus the tool can be used by both developers and QA’s. You can even use a combination of recorded test scenarios and C# test cases to integration test your application.
  2. One feature that I really liked is that you can export a recorded test scenario as a C# test-case! This technique can be used to drastically speed up the Selenium learning curve since it spits out code that you can use inside C# test-case. For instance, when you’re unsure how to code up a specific scenario you can manually record it and then export it to see what the code needs to look like.
  3. The recorded scripts can be used as a tool to speed up manual testing. For example, I never manually login into the web application that I am currently implementing anymore. Instead I run a test scenario that I had previously recorded, conveniently named Login, that logs me in. No more manually typing in username/password! You can use this technique to directly land on specific pages and/or fill-in and submit forms as well. This adds up to save you boat loads of time during your manual testing.
  4. Finally, the test recorder is a small Firefox plugin and integrates real nice with Firefox.

Convinced? Awesome! Let’s move on to setting up Selenium…

Initial Setup
There are two parts to setting up Selenium:

  1. Installing the Selenium IDE: A Firefox plugin that allows you to manually record test scenarios. Find and download the Selenium IDE plugin from the Selenium Downloads section. After it downloads, fire up the Firefox browser -> Go to Add Ons from the Main Menu -> Click the Settings icon -> Select the Install Add-On From File option -> Click Install Add-On.
  2. Installing the Selenium 2.0 WebDriver for .NET: Accepts commands from your C# test cases and automates the browser. Using the NuGet Package Manager Console, run the below commands to install the Selenium packages. Make sure you select your test project as the “Default project” inside the Package Manager Console before running the commands. This way the DLLs will get added to the correct project.

    Install-Package Selenium.WebDriver
    Install-Package Selenium.Support

    Okay, at this point, we should be all set with Selenium. Verify the following:

    - You are able to record a test scenario: Fire up Firefox. On the Main Menu, under Web Developer, you should now see a Selenium IDE option. Or you can use the Ctrl+Alt+S shortcut key to bring it up. Click the record button on the top right, browse to goggle.com, and search for something. Click the record button again to stop the recording. Now try running the script by clicking the play button and see what happens. Make sure you are already on the google.com page when you click the Play button. Hopefully, it worked. If not, call me. I’ll help you out and I only charge a $150/hr. Just kidding. If it doesn’t work then try re-installing the plugin, I guess. :)

    - You are able to write and run C# integration test-cases using Selenium – This is what I go over in my next post on Selenium.

    Twitter Email Linkedin Digg Stumbleupon Subscribe

Dynamically creating input fields on tab via CoffeeScript and JQuery

Below is my very own, very first, super-clean, super-sexy CoffeeScript snippet that dynamically appends input fields as the user tabs through the current input field. The source-code is on the left. On the right you can actually play with it and see it in action!

inputId = 1;
 
jQuery -> 
  $("#fields :input").live 'keydown', (e) ->
    if isModifierKeyPressed e
      return 
 
    if e.keyCode in [9, 13]
      e.preventDefault
 
      if isLastActivity($(this).attr 'id')
	addAnotherTextInput();
 
      $(this).next().focus();
      return false
 
isModifierKeyPressed = (e) ->
  e.ctrlKey or e.altKey or e.shiftKey
 
isLastActivity = (inputFieldId) ->
  inputNumber = 
    (Number) inputFieldId.split('activity')[1]
  inputNumber == inputId
 
addAnotherTextInput = ->
  inputId++
  $("#fields").append getInputField inputId
 
getInputField = (inputId) ->
  return "<input type='text' id='activity#{inputId}' 
                 class='input-super-large' 
                 placeholder='Type something and then press tab' />"
Twitter Email Linkedin Digg Stumbleupon Subscribe

To TDD or Not To TDD?

Recently, I was involved in a discussion with a colleague of mine that was focused around TDD - Test-Driven Development. During the discussion he mentioned that he personally finds the process of coding up the method first and test later to be easier, natural and more efficient. Writing the test-first just seems more difficult to do and less efficient. He then went on to state his reasons: He said, and I agree with him here, it's probably easier and feels natural because that's the way he has always programmed. Create functionality and then test that functionality. TDD flips that around and as result you have to "re-learn" development. Something he wouldn't mind doing, expect that... In his opinion, TDD is a slower way to code. Here is his reasoning: A great majority of the time, you're going to change the code that you wrote to begin with - you will rename the class or method, move things around, change the number of parameters or throw away the first attempt and start again. If you were to write the tests first then those tests would have to change as well! As a result, you're increasing the amount of effort involved. It's much faster to just write the test after the code has been finalized. Until a year ago, those were my thoughts exactly. Then one day (well, probably more like over a period of several months, several books and several articles) I finally found the missing piece to the puzzle. The piece that made TDD possible for me without causing me spend countless hours making significant changes to my test cases because I would keep making significant changes to my code-base. I realized what TDD actually states. Which is: Do NOT write a single piece of production-code before first writing a test for it. And there it is, the missing piece to the puzzle - production-code! Ah ha, I said! I finally get it! In other words, if you're unsure how about the solution is going to look like or work - write non-production code first to work out ideas, fill-in the gaps in requirements, get your questions answered, and get a feel for what the overall solution will look like. Then and only then are you ready to write production-code! Here is the process I now follow during the development: 1. Write a spike or POC code to "brainstorm" what the solution might look like. Sometimes I spend quite a bit of time here. Since in the brainstorming process you'll find out gaps in requirments or will have to go research the third-party product that you're planning use. 2. Once you've got a good grip on what the overall solution might look like and how it's going to work, I throw away the spike (or at least put it out of sight). 3. I then write a failing test case. 4. Write code to make it pass. 5. Back to Step 1 if I am unclear on what the next piece of functionality entails; otherwise, Back to Step 3. So I mentioned that to him and he sort of agreed but not really. He was sort of on the fence. After further discussion we hit upon another point on why to follow TDD that really hit home for him. Here is the example I gave him: Consider the following: You've got X number of test cases in place for a piece of existing functionality. All of the tests pass and everything is working just fine. Then you get a change request. You make the change and then run all the tests. They all pass. Are you done? It's a little difficult to say, isn't it? Somewhat open to interpretation. I've come across developers who think that they are done at this point because they didn't break any existing tests. But they forgot to ask - have I added a test for the new change that I made? On the other hand, if we were to first write a failing test for the change request then there would be no debate on whether or not a test is needed. This where TDD really shines and ensures that we've got tests for all of the functionality. When pressure creeps in, and this is especially true for change requests, then the discipline to add tests after the fact even when all of the existing tests are passing becomes very hard to follow-through on. Sorry for the long-winded ranting. Hopefully you got something out of it. :)
Twitter Email Linkedin Digg Stumbleupon Subscribe

Unobtrusive JavaScript with HTML 5

HTML 5 supports a new feature known as Custom Data Attributes. These attributes give us the ability to define custom attributes for ANY HTML tags. The only restriction is that the tag must start with "data-". For instance, we can add a custom attribute to a link as follows:
  <a href="#" data-search-by-type="<value>">My link with custom attribute</a>
This feature comes with a neat benefit that we no longer need ANY inline javascript inside our HTML content. For instance, say, we've got a commonly-used javascript function that performs a search by searchType:
function search(var searchType)
{
   ...
   ...
}
Prior to HTML 5, we would invoke the function using inline javascript inside our HTML tags:
<a href="javascript:search('byName')" class='search-link'>Search By Name</a>  
<a href="javascript:search('byType')" class='search-link'>Search By Type</a>
With the introduction of Custom Data Attributes, we can now completely do away with the in-line javascript and write the links as follows:
<a href="#" data-search-by='byName' class='search-link'>Search By Name</a>
<a href="#" data-search-by='byType' class='search-link'>Search By Type</a>
We would then add the following to our common.js file that contains the search() function:
$(document).ready(function() {
  $(".search-link").click(function () { search(this.getAttribute("data-search-by")); })
})
The Custom Data Attributes in HTML 5 gives us a benefit that is similar in nature to the benefits provided by the CSS model - namely, separations of concerns. CSS enables us to separate content from the presentation of that content, thus enabling our HTML pages to follow a well-defined structure. Similarly, with Custom Data Attributes we can now separate logic or functionality from HTML content. This provides with the following benefits:
  1. We no longer need to pollute our HTML with in-line Javascript.
  2. Keeping all our Javascript functionality centralized makes it much easier to manage.
  3. The use of Custom Data Attributes increases code re-usability since they can effectively serve as parameters to our javascript functions.
Twitter Email Linkedin Digg Stumbleupon Subscribe

On conducting technical interviews…

As a software consultant, I've both gone through and conducted a fair share of technical interviews. By conducting interviews, being interviewed and watching others interview I've learnt a few things myself. Below are some tips on what works and what doesn't when interviewing software developers... 1. Ask the candidate to write some code! IMHO, this should be one of the first filters. The coding question should be simple enough that it would take a decent coder less than 5 to 10 minutes to code. The purpose here is to filter out the "talkers" from the "doers". For instance, if the candidate is having trouble coding a method that reverses a string, then it doesn't really matter how many years for experience they have, what company they last worked at, or how big the project was! If they are having trouble remembering the a string is char[], then they are not someone you want on your team. This little test may sound too easy or "something that anyone should be able to pull off", but you'll be surprised at how many candidates are be unable to write a simple method when asked to do so. For interviews that are conducted remotely, you can have the candidate share their screen (I typically use Skype or Join.me), ask them to open up notepad and code the solution. 2. Separate the behavioral interviews from the technical interviews Be fair to the candidate - let them know ahead of time what sort of interview will be conducted and by whom. It's very confusing for a candidate when behavioral questions are mixed-in with technical ones. This is because behavioral interviews require answers that contain a different vocabulary and are geared towards a different audience. The candidate that is answering a behavioral question is usually careful to answer the question at a high-level without getting into the nitty-gritty technical details. The answer is more focused on their contribution, how well they worked with others, how issues were handled, etc. Whereas a technical answer would cover things like: what specific technology was used, how was the functionality broken out, what sort of development model was used, what approaches did they take to test their own code, etc. Letting the candidate know what sort of interview is being conducted and by whom will enable them to put forth clear and appropriate responses. Which brings to my third point... 3. Please have the candidate go through AT LEAST one technical interview! It's surprising how many managers, that haven't looked at code in ages, feel they have sufficient knowledge to hire a software developer. Software development is changing - rapidly! The skill-set required 5 years ago (or even a year ago in some cases) is quite different from what's required today. So you if haven't kept up, you will have no way of knowing whether a candidate is right or wrong when they tell you that an ORM is an Object-Role Model that allows you to map roles (yes, I did have a candidate tell me that). By all means, have the managers do the behavioral interviews - which, by the way, is a crucial part of the selection process - but PLEASE leave the technical interviews to your technical folks. If for some reason you're not in position where you can have your own developers do the technical interviews (and there are many valid reasons why this may be the case) then hire an outside consultant to conduct the technical interview. The last thing you want is someone who is adept at talking through the concepts and seems to knows all the technical buzz-words but is very poor when it comes to writing code. And, for some odd reason, there are many "senior-level developers and architects" that are just that! 5. Skip irrelevant questions - such as brain teasers Instead, ask questions that require some creativity and thought to answer. For instance, say you want to find out whether the candidate that is being interviewed for a web development position has the habit of looking at and thinking about the big picture. One question that may help gauge this is: What are some common performance or security related issues that surround web development and what are some strategies to circumvent them? It's okay if they can't fully the answer the question. What you are looking for is whether such thoughts and questions have crossed their minds and how much time they've spent thinking about such issues. Another example is to give them a user story from your actual project (after maybe simplifying it a little) and ask them to sketch an object model for the user story. What you are looking for is: What sort of class names they come up with, what sort of methods these classes contain, whether the relationships among the classes are represented correctly, does their overall object-model look "clean" and easy to understand? Another question that requires some brain-power and creativity is to give them a user story and ask them to come up with a list of test-cases for the user story. 6. Find out if they actually like (nay, love) software development! Ask them if they are currently learning or have recently learned a new technology outside of work. What was the last software development book they read? How long ago? What did they learn from it? Any mentors, role-models they follow? Have they read or follow the following persons: Uncle Bob, Martin Fowler, Scott Hanselman? (Big red flag if they haven't heard these names before). Where do they see themselves a year from now, five years from now? Lastly, please keep in mind that these are my opinions that I have reached through my own learning and experimentation. You may or may not agree with them and they may or may not work for you - and that's as it should be. Try them out if you'd like, modify them as you deem appropriate, and definitely invent your own. Conducting interviews, much like giving interviews, requires constant refinement. Filtering out and selecting the right candidate out of a pool of qualified candidates is never easy. Hopefully, the above tips will prove somewhat beneficial to you while searching for the right candidate.
Twitter Email Linkedin Digg Stumbleupon Subscribe

Embracing CRUD – to it’s full extent!

I watched a screen-cast recently on how Ruby on Rails takes CRUD (Create, Read, Update, Delete) to its very extreme in order to come out with a software design that is to create, understand and modify. Here is the link for it: Love the CRUD. After watching it, I couldn't help but think back to a past project of mine where we kept running into the issue where our controllers and service classes kept turning into gigantic monsters and we would struggle to break them. The fact that we were stuck with an existing design that greatly contributed to this problem didn't help either. Regardless, I think following the approach outlined in the screen cast would be a huge step in the right direction to help address this issue. The screen-cast is somewhat lengthy so hope you can hang in there. :) Cheers!
Twitter Email Linkedin Digg Stumbleupon Subscribe

JQuery snippet to detect keystrokes on the numeric key-pad.

The below JQuery snippet returns the character corresponding to the key that was pressed on the QWERTY keyboard or the numeric key-pad. For instance, pressing the '1' key will return the text '1'. Similarly, pressing the '+' key will return back the text '+'.
$(document).keydown(function (event) {
      toCharacter(event.keyCode);
 });
 
function toCharacter(keyCode) {
 
    // delta to convert num-pad key codes to QWERTY codes.
    var numPadToKeyPadDelta = 48;
 
    // if a numeric key on the num pad was pressed.
    if (keyCode >= 96 && keyCode <= 105) {
        keyCode = keyCode - numPadToKeyPadDelta;
        return String.fromCharCode(keyCode);
    }
 
    if (keyCode == 106)
        return "*";
 
    if (keyCode == 107)
        return "+";
 
    if (keyCode == 109)
        return "-";
 
    if (keyCode == 110)
        return ".";
 
    if (keyCode == 111)
        return "/";
 
    // the 'Enter' key was pressed
    if (keyCode == 13)
        return "=";  //TODO: you should change this to interpret the 'Enter' key as needed by your app.
 
    return String.fromCharCode(keyCode);
}

A little explanation is probably in order...


Javascript provides the
String.fromCharCode()
method that converts an ASCII character code into it's equivalent text value. For instance,
String.fromCharCode(65)
returns the character 'A'. The method works great until to try to use it for keys that live on the numeric keypad. The ASCII code for the '1' key on the numeric key pad is 97. If you look this up on the ASCII Table, you will find that the ASCII code 97 corresponds to the character 'a' and not the character '1' denoted on the numeric key pad! The reason for this, as far I can tell, is that the numeric keys simply overload on the existing the ASCII codes. A little calculation will reveal that subtracting 48 from the ASCII code of the numeric keys will give us the "correct" ASCII code. For instance, subtracting 97 (which is the ASCII code for the '1' key on the numeric keypad) from 48 gives us 49. Look up the ASCII code 49 on the ASCII Table and you will find that it maps to the character '1'! For the keys that correspond to the various symbols such as '+', '-', etc., I am simply returning back the corresponding character. No mystery there. Hope this helps!
Twitter Email Linkedin Digg Stumbleupon Subscribe

Declaring MEF Parts to be Transient

I had very hard time locating the following information and, therefore, would like to share it with others thru my blog: MEF allows your to declare your exports as either singleton or transient. The default policy is to create all parts (aka exports) as a singleton. What this means is that the MEF container will search inside the specified catalogs and providers to find your export. Once it does, it will create an instance of it and reuse it forever. That's good if your exports aren't storing any state. But if they are, then you'll have to override the default policy by making your exports transient. You can do so by adding the below attribute to your class:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(MyType), "MyRuleset")]
public class MyExportClass 
{
}
Hope this saves you the time that it took me to find this little nugget! Happy Coding!
Twitter Email Linkedin Digg Stumbleupon Subscribe