Database, SQL

Sort Data with NULLs at the Bottom in Microsoft SQL Server

One of my clients has a reporting system that orders the data by a column that is a date. They wanted the sort to be ascending, but this places columns with a NULL value at the top followed by the data ascending. They wanted the NULL dates to appear at the bottom. To achieve this, you have to use a syntax that I’ve never used before. Here is the original query:

SELECT * from Jobs as j ORDER BY Date ASC

Here is the modified query that makes use of the CASE statement:

SELECT * from Jobs as j ORDER BY CASE WHEN Date IS NULL THEN 1 ELSE 0 END, Date ASC

The revised query does the initial sort based on the result of the CASE statement and then based on the value in the Date field. The CASE statement itself returns a value of 1 if the Date field is NULL and 0 otherwise. The result of this is that all of the rows with data in Date are first, ordered by Date followed by the remaining rows. It works great and produces the exact result that the client was after.

For additional information on the CASE statement, you can check out this Database Journal article.

Javascript, PHP

jQuery Superfish Menu and Jeditable in IE7

Since I’m carrying on a love affair with jQuery right now, I’m moving most of my customers to jQuery based plugins to simplify the JS code that I am currently using on their sites. One customer happens to make extensive use of the jQuery Jeditable plugin for dynamic/ajax based content updates. One issue I ran into with IE7 was that with the previous menu system, FSMenu, the Jeditable objects would overlap the menu making it unusable. I tried everything under the sun to make it work and finally just dropped FSMenu in favor up the awesome Superfish plugin.

Unfortunately, Superfish had the same problem with the Jeditable objects overlapping the menu system. I tried tweaking the z-index on both of these items with no luck. Firefox displays these properly so I needed to find a workaround for IE since most of the users are still using IE.

The solution turned out to be super simple. All of the fields I was using Jedtiable with had the class “editableNote” assigned to them so it was going to be easy to target just these items. I figured I would just hide them from view when the Superfish menu was activated and show them again when it was hidden. I didn’t want this to be the case in Firefox, just IE.

To make this change, open up your superfish.js file and look at the top where the superfish function is defined. Here is the full snippit of code that we are working with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var sf = $.fn.superfish,
	c = sf.c,
	$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
	over = function(){
		var $$ = $(this), menu = getMenu($$);
		clearTimeout(menu.sfTimer);
		$$.showSuperfishUl().siblings().hideSuperfishUl();
	},
	out = function(){
		var $$ = $(this), menu = getMenu($$), o = sf.op;
		clearTimeout(menu.sfTimer);
		menu.sfTimer=setTimeout(function(){
			o.retainPath=($.inArray($$[0],o.$path)>-1);
			$$.hideSuperfishUl();
			if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length&lt;1){over.call(o.$path);}
		},o.delay);	
	},
	getMenu = function($menu){
		var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
		sf.op = sf.o[menu.serial];
		return menu;
	},
	addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };

What you will want to look for is the over (line 4) and out (line 9) sections of the above code snippit. Since we only want to target IE, we are going to include the following 2 commands to show and hide the Jeditable objects on the over and out events for the Superfish menu.

To hide it:

if ($.browser.msie) $(".editableNote").hide();

To show it:

if ($.browser.msie) $(".editableNote").show();

Remember to change “editableNote” to whatever common class you are also targeting for your Jeditable objects.

Here is the updated snippit with the show and hide functions in place.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var sf = $.fn.superfish,
	c = sf.c,
	$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
	over = function(){
		var $$ = $(this), menu = getMenu($$);
		clearTimeout(menu.sfTimer);
		if ($.browser.msie) $(".editableNote").hide();
		$$.showSuperfishUl().siblings().hideSuperfishUl();
	},
	out = function(){
		var $$ = $(this), menu = getMenu($$), o = sf.op;
		clearTimeout(menu.sfTimer);
		menu.sfTimer=setTimeout(function(){
			o.retainPath=($.inArray($$[0],o.$path)>-1);
			$$.hideSuperfishUl();
			if ($.browser.msie) $(".editableNote").show();
			if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length&lt;1){over.call(o.$path);}
		},o.delay);	
	},
	getMenu = function($menu){
		var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
		sf.op = sf.o[menu.serial];
		return menu;
	},
	addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };

A working before and after demo is forthcoming.

Javascript, PHP, Programming

Validating reCaptcha with jQuery and AJAX

This example is well out of date. Please don’t use it as is until I have a chance to update it.

I recently did some work for one of my clients that involved securing some simple web forms. These forms were to request literature or request a call back, simple stuff. Incidentally they were getting hammered with spam. The clients didn’t seem to care for this so they asked me to stop it.

My first move was to setup some sort of Captcha. I settled on reCaptcha and got to work on implementing it. I’d be on a bit of a jQuery kick lately so I wanted to see if I could validate the Captcha fields dynamically and only submit the form if they matched. It turned out that this was much easier than I’d thought.

To make this work, we’ll be using the following files:

  • recaptcha.php – The page that holds our form
  • ajax.recaptcha.php – The file that handles the ajax requests and outputs the result

Prerequisites

  1. The first thing we’ll do is setup our form. I’m going to assume you already have your form in place and that you are merely trying to secure it.
  2. Next, you’ll want to download the newest version of jQuery. You can put this file wherever you normally store your js files and include this in your page.
  3. Now it’s time to get yourself a reCaptcha keyset. A keyset is nothing more than a public and private key that allows you to use the reCaptcha service. It’s free. Head on over to http://recaptcha.net and click “Get reCaptcha” and fill out the necessary fields. Under domain, either fill out your site’s domain or set this up as a global key if you plan on using reCaptcha on multiple domains. Make a note of your public and private keys.

Now it’s time to put this all together. First we have to get our form to display our reCaptcha challenge field so the user can actually submit the form. My site uses PHP so I’ve downloaded the reCaptcha PHP Library and stored it on my server. At the top of my page, I have included this PHP file and setup my public and private keys. On this page, you really only need the public key, but I went ahead and included both so I don’t lose one of them. Here is what the top of my recaptcha.php looks like (with my keys blanked out):

recaptcha.php

require_once('/inc/recaptchalib.php');
$publickey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // you got this from the signup page
$privatekey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";

Next, you will include this in your page where you want the reCaptcha box to appear in the form:

recaptcha.php

echo recaptcha_get_html($publickey);

Next, we need to write our function that handles the dynamic/AJAX reCaptcha validation for us. I’ve done that already and you can see it below:

recaptcha.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function validateCaptcha()
{
    challengeField = $("input#recaptcha_challenge_field").val();
    responseField = $("input#recaptcha_response_field").val();
    //alert(challengeField);
    //alert(responseField);
    //return false;
    var html = $.ajax({
    type: "POST",
    url: "ajax.recaptcha.php",
    data: "recaptcha_challenge_field=" + challengeField + "&amp;recaptcha_response_field=" + responseField,
    async: false
    }).responseText;
 
    if(html == "success")
    {
        $("#captchaStatus").html(" ");
        // Uncomment the following line in your application
        return true;
    }
    else
    {
        $("#captchaStatus").html("Your captcha is incorrect. Please try again");
        Recaptcha.reload();
        return false;
    }
}

The above function grabs the reCaptcha data, submits it via a POST request to a file called ajax.recaptcha.php on our server, and waits for the repsonse. When it gets the response it either updates the status telling your user that the captcha didn’t match and then it reloads a new captcha for them, or it submits the form. The running demo code is slightly different to prevent the form from actually being submitted.

The last step to this part is to make sure your form runs this function when the user clicks that submit button. To do this, update the form’s opening tag and add an onsubmit event like this:

recaptcha.php

form name="loginform" id="loginform" action="#" method="post" onSubmit="return validateCaptcha()"

You’ll notice that we return true or false from the validateCaptcha() function. This controls if the form is submitted or not and is important for making this work.

Our final step in this process is to build the ajax.recaptcha.php file that we mentioned earlier to handle the requests. I’ve done this already and here is the final product (again with my keys blanked out):

ajax.recaptcha.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require_once('/inc/recaptchalib.php');
$publickey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // you got this from the signup page
$privatekey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 
$resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);
 
if ($resp-&gt;is_valid) {
    ?&gt;success&lt; ?
}
else
{
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
       "(reCAPTCHA said: " . $resp-&gt;error . ")");
}

This file outputs only the word “success” if the captcha matches and a message and the response from reCaptchta if it fails. This is important because we are looking for the word success in our validateCaptcha() function.

You can see the functioning demo for this or download a zip file of the files used in the demo including full PHP source code.

Site News

New Blog

Most of my posts over the past few months have been of a technical nature and it’s time for this blog to officially find it’s place. From this point forward I will be focusing my writing efforts on PHP, jQuery, or whatever else I am working with at the time. My new personal writing will be located at http://chris.rascotopia.com

Stay tuned.

Life in General

Taking a Break

No, I promise that I didn’t die or forget about this site. The reality is that in the past few weeks I’ve been swamped with freelance work, taking a much needed vacation, and working on some of my personal sites to improve them. I’ve got a few things lined for this site and I’ll try and finish them up in the next week or so. Until then, stay tuned.

Internet

What is your preferecens?

I don’t know what mine is either, but apparently Yahoo was unable to save them:

Movies

The Dark Knight

Last week the wife and I went to dinner and went to see The Dark Knight. I don’t know that I would really call myself a huge fan of the Batman movies. I mean, sure, I enjoy them, but I’m not up to speed on the whole Batman saga.

That said, I have always liked Heath Ledger and I really wanted to see his final performance and boy did he deliver. I don’t want to take anything away from the original Joker, Jack, because The Dark Knight had a totally different tone than the first movie with Michael Keaton. Let it be said though, Ledger owned that part. He was by far the most unpredictable villian I’ve seen on the big screen in a long time and I honestly hope the man wins an Oscar for his part.

i think that he did such a good job only serves to make his death even more tragic. That his life was cut short is sad, but that we are all deprived of the best that he had to offer is even worse.

If you haven’t seen the movie, you need to.

Kids, Life in General

Family Vacation Round 1

I’ve really been slacking off on the whole blogging thing. You see, we went on vacation a few weeks back and I think I am still trying to catch up and recover from it.

When my oldest was a baby, we tried to fly out to San Diego to stay with my relatives that had rented a condo out there. Long story short, we got stranded in Denver with no baby food, diapers, and no car seat. Thanks United! From that point forward we were committed to driving ourselves to our vacation destinations of choice. This is relatively easy if you are travelling to the coast or somewhere near by. We weren’t and we haven’t. Since then we have driven to the East Coast once and the West Coast 2 or 3 times. I forget.

After last year’s trip I decided I was done with the driving thing. I just couldn’t stand 2 days of traveling each way. So this year we decided to head out West again for our first of 2 trips to the great state of California.

This trip was kind of impromptu and then blossomed into a full blown vacation. Whatever, it was a lot of fun.

One important distinction about this trip was that it was Ethan’s first real plane trip. He was far too young to recall the first one. He kind of freaked out about the whole thing all the way up until we got to the airport. My mom somehow managed to convince the gate attendant to let him go sit in the cockpit and meet the pilot. That went a long way towards making the trip start off easily.

We were staying in a condo on the boardwalk down in Mission Beach for the week. We had rented it with my mom and brother. My aunts, cousins, and grandparents also occupied 3 other condos right in that area. You could say that it was a big family reunion and that would be pretty accurate.

With the kids being 4 and 1, I was pretty excited to see how they were going to react to the activities we had planned for the week. The first few days were beach days and it was hilarious to see them run around on the beach. They truly had a blast. It helped that all of my cousins love them to death. I’m the oldest of like 12 or 13 cousins with the youngest of the bunch being 16.

Last year while we were out there we headed to the San Diego Zoo and it was a blast so we made sure to go again this year. I really wish the San Antonio Zoo was 1/2 as big and half as entertaining as that. I mean, I like our Zoo and all that, but it’s really in a world of it’s own.

One of the new things that we made time for this year was Legoland. I went about 10 years ago right after I got out of high school and I loved it. They’ve made a few additions in the last 10 years.

I was really worried that Ethan wouldn’t enjoy himself or appreciate the scope of what it takes to build a 15′ tall skyscraper out of real LEGO blocks. He did and he is still asking to go back. I think when we head back to SoCal this fall that we are going to make the trip down to Carlsbad for a day.

The trip back to San Antonio was pretty easy and I am seriously glad we did the air travel thing instead of driving.

I usually get pretty stressed out on vacation for some reason. I am not a strict timetable type of person, but I just tend to get up tight. This trip I really got to enjoy and didn’t feel up tight about anything. Maybe I wasn’t as worried about the kids since they are a little bit older.

Kids, Life in General, Reviews

Review: Bugaboo Bee

Bugaboo Bee

Name: Bee
Manufacturer: Bugaboo
MSRP: $529

Now that I’ve gotten over the initial giddy feeling of this purchase, I am at a point where I can legitimately tell you about it. The Bee is the newest member of the Bugaboo family of products. It’s aimed at parents that live in the city and have reason to fold it up and toss it into a taxi or take it on the subway. For that reason, it’s designed to be stylish, but also very lightweight and compact.

The Bee features very solid but lightweight construction with it’s aluminum frame. The Bee also comes equipped with 4 wheel independent suspension. What that means is that each wheel is independently spring loaded to provide a very smooth ride for your child. The wheels are also very sturdy and foam filled. They seem to allow the stroller to just glide smoothly across any surface. Even a quick stroller around the block is a smooth as can be.

The Bee also features an adjustable handle bar so it can comfortably be used by parents of all size. This was one of the major drawbacks to most strollers with fixed handles.

Another great feature is the ability to have your child face the world or face you. With a few simple steps you can flip the lightweight seat around. One drawback was that with the seat facing you, the stroller didn’t seem to fold up as well. It is recommended to return the seat to forward facing before folding.

Folding up the stroller is as easy as pulling 2 slide locks on the frame. No tricky locks are necessary to keep the stroller folded up. It simply holds it’s position. To unfold, simply place your foot on the brake pedal and push and it pops right up.

The brake is in the center of the back of the stroller and is very easy to engage and unlock with the flip of your foot.

The Bee also packs ample storage space beneath the seat, especially in rear facing position.

In all, the Bee is a fabulous stroller that isn’t packed full of complicated features. It has a simple design that works well and is simple to use. It’s light and sturdy and the seat cover is machine washable for easy cleaning. The price tag is hard to swallow for many people, but if you are planning on having multiple kids then the cost of purchasing a new stroller for subsequent kids it isn’t all that bad. The Bee also has an adapter for holding Graco car seats for $50.

I highly recommend anyone considering a new stroller take a look at the Bee. It is available at Neiman Marcus and at many online retailers.

Sports

My Thoughts on the 2008 NBA Draft

Last night’s draft was both expected and totally unexpected at the same time. On one hand, the first 3 picks being Rose, Beasley, and Mayo was what just about everyone expected. The rest of the draft field, however, kind of shook things up.

Joe Alexander, one of my favorite prospects, went 8th to the Bucks. I wasn’t expecting him to go anywhere higher than a 12 or 14. Looks like the Bucks realized what a good prospect he was. Another pick that moved up at the last minute was UT’s D.J. Augustin. I think he was a projected 20th pick and he went 9th!

More surprised were revealed when the Spurs went all American and drafted no Euro players. With the 26th pick, the Spurs selected George hill from IUPUI. A surprising move considering there were a slew of players from both Memphis and Kansas left on the board including Joey Dorsey, Mario Chalmers, and Chris Douglas-Roberts (who ended up going 40th in the 2nd round to the Nets).

I’ve got a lot of faith in R.C. and Pop and most of these guys will end up being busts. I just hope our picks are the ones that shine.

There is A LOT of player movement going down as we speak including a deal where Mayo and Love swap teams. Chalmers is going to Miami. Dorsey to Houston. It’s only going to get worse over the next week or so.

One thing is for sure and that is that the West is going to be much more difficult in about 1 or 2 years. I’m preparing myself now for a short streak of getting dominated by teams like the Hornets, Sonics, and Blazers.

To check out the full Draft Board go here. For all the information on the current player movement go here.

« Newer Entries - Older Entries »