End Loose Ends

Dead Simple Ajax Progress Spinner Mar 26

Here is a drive-by post for anyone that wants a simple way to show spinners during an AJAX requests. jQuery allows you to define AJAX pre-filters which enable you to do funky things before and after AJAX requests. The following snippet enables you to pass a jQuery selector as a "spinner" option to jQuery.ajax. It will automatically show the element after 500 ms and will hide it when the request is complete. If the request takes less than 500 ms, it won't show the spinner at all.
jQuery.ajaxPrefilter(function (options, originalOptions, jqXHR) {
  if (options.spinner) {
    var spinner = jQuery(options.spinner);
    if (spinner && spinner.length > 0) {
      var timeoutId = setTimeout(function () { spinner.show(); }, 500);
      jqXHR.always(function () {
        clearTimeout(timeoutId);
        spinner.hide();
      });
    } else {
      console.log('Found spinner parameter, but couldn\'t find the specified element.');
    }
  }
});
Using this pre-filter is a snap. Just pass it as an option to jQuery ajax as follows:
  jQuery.ajax({
    url: '/items/1',
    success: display,
    spinner: '#loadSpinner'
  });
The nice thing about this approach is that it lets you handle this uniformly across your application. Despite this, it gives you the flexibility of having multiple spinners in different locations.

Git Bash Visual Studio Command Prompt Jan 04

I enjoy using the bash command prompt that comes with msysgit. Every once in a while I find myself having to launch the Visual Studio 2008 Command Prompt – usually to initiate a build without having to open a solution up in Visual Studio.  This is annoying when I already have a bash window open in the desired folder.  In the spirit of automating things I do often, I’ve written a batch file that calls out to Visual Studio’s command-line environment setup script before launching git bash.  This ensures the correct PATH is set along with other required environment variables.  Here’s how I’ve set things up:

  1. Create the wrapper batch file

    Save the following script as git_bash_vs.batRemember to modify the Visual Studio and msysgit paths in the script.
  2. @set myVsDir="e:\development\vs2008\VC\"
    @pushd %myVsDir%
    @call %myVsDir%\vcvarsall.bat x86
    @popd
    @"E:\development\git\bin\sh.exe" --login -i
  3. Modify the Git Bash start menu shortcut

    Edit the Git Bash shortcut by right clicking on it and selecting Properties.  Now, update the Target to point at your git_bash_vs.bat script, and set the Start In directory to be wherever you wish. (I usually set this to my project directory where all of my source code is stored.)

    git_bash_shortcut

If you also happen to have External Tool entries in Visual Studio that launch git bash, don’t forget to update them too!

Formatting Dates and Times in SQL Server Dec 02

We are in the midst of a report writing blitz. While writing Reporting Services reports, we’ve found the need for formatting dates and times in Microsoft SQL Server. Ordinarily, our UI tier handles formatting based on the customer specific rules.  We aren’t there yet on the report side, so we need SQL Server to do some of the lifting. For future reference, I’m going to list a few useful functions for turning those pesky datetime values into strings.

Built-in Formatting

When out-of-the-box formatting will do, use the CONVERT function and pass in a format code. Checkout this example:

Executing: print CONVERT(varchar(20), getdate(), 0);

Yields: Dec  2 2010  9:37AM

To see all of the built-in formats in action, execute the following script:

declare @i int, @now datetime
select @i = 0, @now = '2010-12-02 8:05:55'

while @i < 200
begin
    begin try
        print ltrim(str(@i)) + ': '
            + convert(nvarchar(200), @now, @i)
    end try
    begin catch
    end catch
    set @i += 1
end

Custom Formatting

For custom formatting, there is no official way to pass a format string like you would in .NET (think “yy/mm/dd”). In SQL Server you’ll want to resort to using some of the following functions:

Localization

Another thing you might want to look into is changing the language used for formatting dates.

hazardous

Your mileage may vary here and I’m not sure of the repercussions, so if your machine explodes and kills your dog, remember you were warned!

declare @oldLanguage nvarchar(100)
set @oldLanguage = @@language

set language 'french'

print convert(varchar(20), getdate(), 7)

set language @oldLanguage

Executing the above would result in the current language being set to french, the month name being printed in french and reverting back to your original language.

Hope that helps ease the pain – even if just a little.

Debugging JavaScript Unit Tests Apr 02

I am experimenting with jsUnit, a javascript unit testing framework.  I am really enjoying the ability to easily unit test my javascript code.  I particularly like the UI:

 

image

jsUnit uses a technique they refer to as cache-busting to ensure the System Under Test is reloaded between test runs.  Unfortunately, this makes it difficult for developers that want to debug a unit test (GASP! Yes, once in a while, the debugger is useful when unit testing).

The key is a simple javascript trick for setting a breakpoint in the actual code.  Wherever you want the code to break, just add a debugger statement and Voila! You will be able to debug why that pesky unit test is failing.  Keep in mind, you will need to have a javascript debugger running.  In this case, I opened FireBug, enabled the script debugger for the site and let the debugger statement do the rest.

image

TouchCursor is now open source! Mar 08

I am a self professed keyboard ninja.  One of the software tools I love most is TouchCursor.  By holding down the space key, it allows me to use keys in and around the home row to act as the arrow keys, home/end keys, pgup/pgdown keys, backspace/delete keys and almost any other key.  I cannot explain to you the pleasure I get from using TouchCursor!  I hardly ever feel the need to move my hands from the home row.  Using TouchCursor is a basic instinct.

TouchCursor is especially useful on laptops with non-standard keyboard configurations.  I simply NEVER use those awkwardly placed keys.  I have been using TouchCursor for years - even when it was a commercial product.  I am glad Martin Stone decided to open source this product because the more people that install it, the happier I will be to use their computers!  That said, TouchCursor is portable software that can run off a USB stick - never leave home without it.

Become a keyboard ninja. Use TouchCursor!

Disable Beep Sound for Git Diff Feb 16

This is really just an addendum to my post on disabling annoying beep sounds when using git for windows.  You will likely want to disable the aggravating beeps that happen when scrolling to the end of a diff. This can be done by tweaking your user level git configuration settings(~/.gitconfig).  Just modify the pager command line to include a –q for quite:

[core]
  pager = less -q

How to Push a New Local Branch to a Remote Git Repository Jan 11

You might find yourself in a situation where you have a branch that you created locally and want to push to a remote git repository. Suppose you created a local plugin branch that you want to expose to others through your GitHub repository but you are not yet confident enough to put it into the master branch. Here is the command you would execute to push all of the changes from your plugin branch to a plugin branch on the GitHub repository:
git push origin plugin
This tells git to push changes from your plugin branch to the plugin branch on the origin repository. If origin does not have a plugin branch, it is created on the fly. Now, say your friend Bob wants to access the hot new feature you just pushed to the new branch on the GitHub repository. All Bob needs to do is update his local repository with all of the changes on the GitHub repository and create a local branch where he can play with the new code.
git fetch origin
git checkout --track origin/plugin
The first command updates Bob's repository with the changes from the remote repository. The second command creates a local branch named plugin that matches the origin/plugin branch and tells git that Bob wants to be able to easily push and pull from the branch on GitHub. Bob can now play with the code, commit his own changes and git push them back up to the GitHub repository.

Configure Git to Display Colours May 12

It is no secret I have switched to using Git version control system for personal projects.  One feature that is not enabled by default but I find very helpful is the use of colour when displaying output to the terminal.  This is particularly useful when viewing file status and performing diffs.  The use of colour can easily be enabled by adding the following “color” section to your personal .gitconfig file:

[color]
    ui = auto

User wide configuration settings like this one can be saved in your home directory (~/.gitconfig). 

Disable Annoying Beep Sound for Git on Windows Apr 20

One of the first things I do immediately after installing msysgit (and/or using bash under cygwin) is to disable the annoying bell noise heard when using command line completion.  To disable the bell, append the following line to the .inputrc file in your home directory (~/.inputrc):

# Don't ring bell on completion
set bell-style none

How To Avoid Accessing Repositories from Domain Objects Apr 20

I was reading the comments on Udi Dahan’s blog post about Domain Driven Design when I ran into a frequently asked question regarding domain classes and repository access.  Usually, the questions are similar to the following:

  • While invoking behaviour on one aggregate root, how do I load another aggregate from a repository?
  • How do I inject a repository instance into a domain object? 

 

I generally prefer to tackle this problem using an approach that keeps the domain model free of storage concerns.

The Obligatory Customer/Order Example

Let me put forth a simple scenario to demonstrate what you might do when a domain class seems to require access to information that would typically be in the repository:

A Customer class has a CreateOrder method that enforces the invariant "a customer can only create orders if they have no more than two unpaid orders."

In this scenario, the CreateOrder method needs to access the presumably short list of unpaid orders belonging to the customer.  Rather than polluting the Customer class with calls to a repository, the method should simply access an UnpaidOrders field of the Customer class.  This brings up the big question: how do the unpaid orders get into the Customer instance?

Repositories Return Ready to Use Aggregates

As suspected, the unpaid orders are loaded from a repository - the big difference is which repository and how.  In this example, the Customer repository would handle the loading of UnpaidOrders collection.  Whether this collection is fetched immediately when the Customer is loaded (eager loading) or loaded when you access the UnpaidOrders member (lazy loading) is a separate concern.  In both cases, the Customer class is oblivious of this and simply accesses the UnpaidOrders collection as if it were pre-populated.

Fancy object relation mapping (ORM) tools, like NHibernate, make it easy to build domain models in this way because they provide separation of concerns.  How the UnpaidOrders collection is loaded is part of the ORM configuration.  If you are concerned with database performance issues, Udi has a great post on using intention revealing interfaces to solve the conflict between eager and lazy loading.

Closing

In short, the ideal solution is to make domain classes oblivious of repositories by letting the repository for the aggregate root handle the fetching of related entities and aggregates.