Merry Christmas

Firstly, for anyone following along, Merry Christmas all!

I’m only a handful of posts deep but I can honestly say that I’ve loved doing this. So much so that I, most likely, will plug a bit of money into this in the New Year and try to sort a custom domain/do a few customisations to the blog.

Currently, I’ve got a post in the pipeline looking at the WPF MediaElement control which I’ll try and have out sometime around the New Year; beer and parties permitting. After that, I want to throw in a little Objective C, Python and perhaps do a little more focused work surrounding Unity 3D (and do more game development in the New Year). As I’m eyeing up a few books in relation to create custom shaders in Unity and handling AI I think this should provide some interesting material to flesh out in the form of blog posts. In addition, I’ve got my hands on an Arduino experimentation kit and have had a Leap Motion controller for a while now (and I’d love to start getting into the API’s surrounding that).

I’ll grind out as much as I can manage before my brain explodes (and try to turn up to my wedding in the process).

In the meantime go eat and be merry, you’ve earned it!

Happy New Year to all.

Mucking around with the SpeechSynthesizer class

If you fancy a quick, fun, muck-around style project in C# then having a play with the System.Speech.SpeechSynthesizer class is definitely a good bet. Below is pretty much the most basic example of using this class which involves simply passing a string to the SpeechSythesizer Speak or SpeakAsync methods. More complicated variations are possible by using a PromptBuilder object instead which allows fine-tuned control over the content being spoken (i.e. pronunciation of parts of the content and getting a firm grip on the start of sentences and paragraphs within the content as a whole).

Start by adding a reference to the System.Speech assembly within your project:

Adding the System.Speech assembly to the project.

Adding the System.Speech assembly to the project.

Here’s a very basic code implementation (using a C# Console Application):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Speech.Synthesis;          //To gain access to the SpeechSynthesizer Class (add a reference to System.Speech)
using System.Diagnostics;               //For the debugging

namespace SpeechSynthTestApp
{
    /// <summary>
    /// Program Class Definition.
    /// </summary>
    class Program
    {
        #region Private Static Data Fields

        //Static SpeechSynthesizer object (initialised fully within the PrepareSpeechSynthObject method)
        private static SpeechSynthesizer speechSynth;

        #endregion Private Static Data Fields

        #region Constructor

        /// <summary>
        /// SpeechSynthTestApp Program Class Constructor.
        /// </summary>
        /// <param name="args">Incoming arguments for this Console Application from external sources (if supplied).</param>
        static void Main(string[] args)
        {
            //Prepare the static SpeechSynthesizer object ready to receive input from the user (for speech) and then start the main application loop
            PrepareSpeechSynthObject();
            RunApplication();
        }

        #endregion Constructor

        #region Private Static Methods

        /// <summary>
        /// Private static method that prepares the private SpeechSynthesizer object
        /// ready for the user to start interacting with.
        /// </summary>
        private static void PrepareSpeechSynthObject()
        {
            //Initialise the speechSynth object
            speechSynth = new SpeechSynthesizer();

            //For testing purposes tie up some of the SpeechSynthesizer classes event handlers (in this instance to retrieve debug information)
            speechSynth.SpeakStarted += ((sender, e) => 
            {
                SpeechSynthesizer synth = sender as SpeechSynthesizer;

                if (synth != null)
                {
                    Debug.WriteLine("Speech Synth object has started talking with the voice '{0}' at volume '{1}'.",
                        synth.Voice.Description, synth.Volume);
                }               
            });
            speechSynth.SpeakProgress += ((sender, e) =>
            {
                SpeechSynthesizer synth = sender as SpeechSynthesizer;

                if (synth != null)
                {
                    Debug.WriteLine("Speech Progressing. Saying '{0}'; Char Count '{1}'; Audio Pos '{2}'; Voice '{3}'; Volume '{4}'.",
                        e.Text, e.CharacterCount, e.AudioPosition, synth.Voice.Description, synth.Volume);
                }  
            });
            speechSynth.SpeakCompleted += ((sender, e) =>
            {
                SpeechSynthesizer synth = sender as SpeechSynthesizer;

                if (synth != null)
                {
                    Debug.WriteLine("Speech completed. Voice '{0}'; Volume '{1}'.", synth.Voice.Description, synth.Volume);
                }
            });
        }

        /// <summary>
        /// Private static method that represents the main application loop (which
        /// consists of gathering user input and calling a method to make a
        /// SpeechSynthesizer object do it's thing!).
        /// </summary>
        private static void RunApplication()
        {
            //Just keep a' loopin'
            while (true)
            {
                //Gather user input
                Console.Write("Type something for the SpeechSynthesizer to say then press enter ('E' to exit): ");
                string userInput = Console.ReadLine();
                
                //If a user types 'E' (case insensitive) then exit the loop and the application
                if (userInput.Equals("E", StringComparison.InvariantCultureIgnoreCase))
                {
                    //As we are calling SpeakAsync we have to cancel any code still being executed/to be executed asynchronously to prevent exceptions
                    speechSynth.SpeakAsyncCancelAll();
                    break; //Exit
                }

                //SPEAK!
                Speak(userInput);
            }
        }

        /// <summary>
        /// Take in the users input and talk talk talk!!!
        /// </summary>
        /// <param name="userInput">The users input from the Console.</param>
        private static void Speak(string userInput)
        {
            /*
                Speak based on the users input (handle null, empty or whitespace input). We could create a more complicated PromptBuilder object here but 
                passing a string serves as a suitable, basic example
            */
            speechSynth.SpeakAsync(string.IsNullOrWhiteSpace(userInput) ? "You need to type something next time." : userInput);
        }

        #endregion Private Static Methods
    }
}

In addition to the content being spoken you’ll also be able to access additional details via the event hookups (as specified in the code snippet above). A wee example looks like this:

Debug output based on SpeechSynthesizer events.

Debug output based on SpeechSynthesizer events.

I guarantee that, within about 30 seconds, you’ll be typing all sorts of swear words just to see how funny they sound. Enjoy!

SQL Debugging Tips – Part Two

A common task within SQL is to search an objects definition for a particular reference. This might be a table, column, procedure, function or view name. Below are a few techniques for achieving this. I’ve also highlighted some tables that are related to SQL Server Maintenance Plans and how to start searching interrogating the data tied to these.

/* 

Searching Object Definitions in SQL.

sys.sql_modules is a fairly complete way to achieve this but there's a myriad of options below, including a way 
to look into SQL Maintainence plans (add a where clause on the command column to filter this down)

*/

DECLARE
@SEARCH_TERM		NVARCHAR(MAX) = '%tblSYS_SCHEMA_COLUMN%';

--Full raw objects that reference tempID (or the SEARCH_TERM) in Views (for reference, select only), Triggers, SP's and Functions
SELECT
so.name
, sm.[definition]
, so.type_desc
FROM sys.sql_modules sm
	INNER JOIN sys.objects so ON sm.object_id = so.object_id
WHERE sm.[definition] LIKE @SEARCH_TERM
ORDER BY so.type_desc, so.name;

--Raw results from sys.procedures (SP's only) - Use for verification with the above sys.sql_modules results
SELECT *
FROM sys.procedures sp
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE @SEARCH_TERM
ORDER BY sp.name;

--Results from the INFORMATION_SCHEMA.ROUTINES system view (encapsulating SP's and Functions) - Use for verification with the above sys.sql_modules results
SELECT
ir.SPECIFIC_NAME
, ir.ROUTINE_TYPE
, ir.*
FROM INFORMATION_SCHEMA.ROUTINES ir
WHERE ir.ROUTINE_DEFINITION LIKE @SEARCH_TERM
ORDER BY ir.ROUTINE_TYPE DESC, ir.SPECIFIC_NAME;

--Check SQL Jobs (Maintenance Plans) for the search term being imbedded in the 
SELECT
sj.name
, sj.[enabled]
, sjs.step_name
, sjs.subsystem
, sjs.command		--Filter the command (by adding a WHERE clause) column by the search term (TSQL subsystems)
FROM msdb.dbo.sysjobs sj
	INNER JOIN msdb.dbo.sysjobsteps sjs ON sj.job_id = sjs.job_id
WHERE sjs.command LIKE @SEARCH_TERM
ORDER BY sj.name;

/*
SQL JOB TABLES FOR REFERENCE

SELECT * FROM msdb.dbo.SysJobs
SELECT * FROM msdb.dbo.SysJobSteps
SELECT * FROM msdb.dbo.SysJobSchedules
SELECT * FROM msdb.dbo.SysJobServers
SELECT * FROM msdb.dbo.SysJobHistory
*/

SQL Debugging Tips – A Simple Example

Depending on the infrastructure of the application you are working on you may find yourself in need of really being able to interpret what’s going on in the guts of SQL Stored Procedures in a fast and efficient manner.

For a small Stored Procedure you’re probably going to find that, locally at least, the debugging tools with SQL Server Management Tools are going to suit just fine most of the time (i.e. inspecting variables using the locals window, etc). Thinking further along the line however, when your database architecture finds itself going out into the wider world (for example, being hosted on various sites outside of your direct control), or when being debugged for issues by non-developers with permissions not suited to debugging, you’ll need to consider other approaches.

To the end, here’s something I’ve found as a handy pattern to implement when working with Stored Procedures. Provided it’s not over-baked then it normally proves pretty darn useful. So, without further ado, let’s take a look at the simplest possible example of the ‘@DEBUG’ parameter at work.

To set us up we need a very simple set of tables and test data to provide an example case. Below, you’ll see I’ve implemented two tables; tblITEM and tblPARAM. The tblITEM table contains a basic set of items which we will make available via a Stored Procedure. In this implementation, tblPARAM is used to store all of our ‘parameters’ that will ultimately decide how our Stored Procedure behaves. I’ll explain as we go anyway:

TEST_DB Structure

TEST_DB Structure

--1) Setup the tblPARAM table

--If no records exist yet then perform the initial data load. Otherwise, do nothing
IF NOT EXISTS
(
	SELECT *
	FROM dbo.tblPARAM p
)
BEGIN

	INSERT INTO dbo.tblPARAM
	(
		PARAM_DESC
		, PARAM_ACTIVE
	)
	VALUES
	(
		'Active Records Only'
		, 1
	)
	,
	(
		'Big Head Mode'
		, 0
	);

END;

--2) Setup the tblITEM table

--If no records exist yet then perform the initial data load. Otherwise, do nothing
IF NOT EXISTS
(
	SELECT *
	FROM dbo.tblITEM i
) 
BEGIN

	INSERT INTO dbo.tblITEM 
	(
		ITEM_DESC
		, ITEM_ACTIVE
		, ITEM_ADD_INFO
	)
	VALUES
	(
		'Skateboard'
		, 0
		, 'A skateboard with retractable wheels that turns into a hoverboard.'
	)
	,
	(
		'Super Mario Plumbing Kit'
		, 1
		, 'A red all-purpose plumbing kit.'
	)
	,
	(
		'Luigi Plumbing Kit'
		, 1
		, 'Just like Mario''s kit, but in green.'
	)
	, 
	(
		'Guitar Strings'
		, 0
		, 'Bog standard strings.'
	)
	,
	(
		'Simple Item'
		, 1
		, NULL
	);

END;

--Get all Items
SELECT
i.ITEM_ID
, i.ITEM_DESC
, i.ITEM_ACTIVE
, i.ITEM_ADD_INFO
FROM dbo.tblITEM i;

--Get all Parameters
SELECT
p.PARAM_ID
, p.PARAM_DESC
, p.PARAM_ACTIVE
FROM dbo.tblPARAM p;

Now we have our test tables/data in place we now need to author something in order to provide access to this information which, in this case, is a SQL Stored Procedure. The aim here is to provide a basic results set that displays records from tblITEM, with an additional filter on an items active state (based on the relevant tblPARAM setting). The first (buggy as hell!) implementation is as follows; I’m expecting seasoned eyes to pick up on the problem immediately:

SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID ('[dbo].[SPROC_GET_ITEMS]','P') IS NOT NULL
BEGIN

	DROP PROCEDURE [dbo].[SPROC_GET_ITEMS] 

END;

GO

CREATE PROCEDURE [dbo].[SPROC_GET_ITEMS]
AS
BEGIN

	--Get a param value, by description, denoting if how we should filter items (just as for illustration purposes)
	DECLARE
	@ACTIVE_RECORDS_ONLY		BIT =
	(
		SELECT
		p.PARAM_ACTIVE
 		FROM dbo.tblPARAM p
		WHERE p.PARAM_DESC = 'Active Record Only'
	);

	--Get the relevant items
	SELECT 
	i.ITEM_ID
	, i.ITEM_DESC
	, COALESCE(i.ITEM_ADD_INFO, 'No Additional Information')
	FROM dbo.tblITEM i
	WHERE i.ITEM_ACTIVE = @ACTIVE_RECORDS_ONLY; --Retrieve active or inactive items, depending on the parameter value	

END;

SPROC_GET_ITEMS is geared to pull a value from tblPARAM and then use this to filter a select statement based on tblITEM looking for either active or inactive items. A very simple setup, but even in this case, it’s flawed.

Executing the stored procedure in its current form provides the following results:

SP call with no results.

SP call with no results.

Checking the tblPARAM table I can see the parameter that I’m interested in, present and correct with a value of true (1), based on the initial data load I performed. The tblITEM table contains records so what gives…?

As previously mentioned, something of this complexity is probably not going to require you to really think along the following lines, but planning like this early on in a Stored Procedures life-cycle can save future headaches if and when the amount of code begins to stack up.

I tend to like to do the following, and add an @DEBUG input parameter to the Stored Procedure:

SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID ('[dbo].[SPROC_GET_ITEMS]','P') IS NOT NULL
BEGIN

	DROP PROCEDURE [dbo].[SPROC_GET_ITEMS] 

END;

GO

CREATE PROCEDURE [dbo].[SPROC_GET_ITEMS]
(
	@DEBUG			BIT = 0		--Add a debug parameter (defaulted to false). This can be added when executing the SP for additional information
)
AS
BEGIN

	IF (@DEBUG = 1)
	BEGIN

		PRINT
		(
			'Running SPROC_GET_ITEMS' 
			+ CHAR(13)
			+ '===============================' 
		);

	END;

	DECLARE
	@ACTIVE_RECORDS_ONLY		BIT =
	(
		SELECT
		p.PARAM_ACTIVE
		FROM dbo.tblPARAM p
		WHERE p.PARAM_DESC = 'Active Record Only'
	);

	--Additional debug information
	IF (@DEBUG = 1)
	BEGIN

		--Inspect the parameter value drawn from tblPARAM before utilising in the SELECT statement (to help troubleshoot)
		PRINT('Active Records Only parameter value: ' + COALESCE(CONVERT(NVARCHAR(1), @ACTIVE_RECORDS_ONLY), 'NULL (Unset)'));		

	END;

	SELECT 
	i.ITEM_ID
	, i.ITEM_DESC
	, COALESCE(i.ITEM_ADD_INFO, 'No Additional Information') AS [ITEM_ADD_INFO]
	FROM dbo.tblITEM i
	WHERE i.ITEM_ACTIVE = @ACTIVE_RECORDS_ONLY; --Retrieve active or inactive items, depending on the parameter value

END;

This then enables the stored procedure to be called as follows to surface additional, debug information. I prefer to explicitly type the input parameter name as well as specify the value in all cases for clarity, and to satisfy my OCD urges:

--Calling the procedure, expecting just active items....but something is up, now we have debugging we'll hopefully be able to spot the issue
EXEC dbo.SPROC_GET_ITEMS
1;

--Or, If you like extra keystrokes and less ambiguity
EXEC dbo.SPROC_GET_ITEMS
@DEBUG = 1;

When called in this way, the code surrounded by the IF checks (seeing if @DEBUG = 1) will be called. We are looking here to grab hold of, via a PRINT statement, the values of any variables being utilised in the procedure. We are not receiving any errors in this scenario so it’s a good bet that something else is afoot and variables are a good place to start. Structuring your debugging like this, from the offset, gives others the opportunity to run your Stored Procedures in a manner that transparently gives access to functional details that will make troubleshooting easier. From a support perspective this can be invaluable. You’ll notice that I also like to include a summary header, only printed if @DEBUG = 1, that normally states something along the lines of ‘Running Stored Procedure SP_NAME’. You can also choose to print out the values of any other Stored Procedure input parameters here just for clarity. If debugging multiple procedures at once this can help in separating the output into sectioned chunks, making it clear which procedure was responsible for what output.

Using a simple COALESCE/CONVERT combination on the @ACTIVE_RECORDS_ONLY variable we should be able to quickly spot if this value is being set as expected.

SP call with no results but debugging activated.

SP call with no results but debugging activated.

We have an immediate hit now that illustrates that something isn’t quite right with how we are setting our @ACTIVE_RECORDS_ONLY variable. A scan by eye shows that I’ve gone and royally screwed up! The parameter description is incorrect:

DECLARE
@ACTIVE_RECORDS_ONLY		BIT =
(
	SELECT
	p.PARAM_ACTIVE
	FROM dbo.tblPARAM p
	WHERE p.PARAM_DESC = 'Active Record Only'
);

Setting p.PARAM_DESC = ‘Active Records Only’ should fix our issue. Let’s look at a fixed, enhanced implementation and evidence supporting that our wonderful little fix is working:

SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID ('[dbo].[SPROC_GET_ITEMS]','P') IS NOT NULL
BEGIN

	DROP PROCEDURE [dbo].[SPROC_GET_ITEMS] 

END;

GO

CREATE PROCEDURE [dbo].[SPROC_GET_ITEMS]
(
	@DEBUG			BIT = 0		--Add a debug parameter (defaulted to false). This can be added when executing the SP for additional information
)
AS
BEGIN

	IF (@DEBUG = 1)
	BEGIN

		PRINT
		(
			'Running SPROC_GET_ITEMS' 
			+ CHAR(13)
			+ '===============================' 
		);

	END;

	DECLARE
	@ACTIVE_RECORDS_ONLY		BIT =
	(
		SELECT
		p.PARAM_ACTIVE
		FROM dbo.tblPARAM p
		WHERE p.PARAM_DESC = 'Active Records Only'
	);

	--Additional debug information
	IF (@DEBUG = 1)
	BEGIN

		--Inspect the parameter value drawn from tblPARAM before utilising in the SELECT statement (to help troubleshoot)
		PRINT('Active Records Only parameter value: ' + COALESCE(CONVERT(NVARCHAR(1), @ACTIVE_RECORDS_ONLY), 'NULL (Unset)'));		

	END;

	SELECT 
	i.ITEM_ID
	, i.ITEM_DESC
	, COALESCE(i.ITEM_ADD_INFO, 'No Additional Information') AS [ITEM_ADD_INFO]
	FROM dbo.tblITEM i
	WHERE 
	(
		i.ITEM_ACTIVE = @ACTIVE_RECORDS_ONLY		--Active records only
		OR COALESCE(@ACTIVE_RECORDS_ONLY, 0) = 0	--Or all items (Active and Inactive), if the flag is set to 0 (false). Null handled
	);	 

END;
SP results after fix.

SP results after fix.

SP messages after fix.

SP messages after fix.

--Only active items at the moment, based on the parameter
EXEC dbo.SPROC_GET_ITEMS;

GO

--Update the parameter to false
UPDATE p
SET p.PARAM_ACTIVE = 0
FROM dbo.tblPARAM p
WHERE p.PARAM_DESC = 'Active Records Only';

GO

--Should give us all items based on how this is currently configured
EXEC dbo.SPROC_GET_ITEMS;
A full test.

A full test.

When you’re done debugging you can just omit the @DEBUG = 1 part of the statement from the Stored Procedure call to trim out any debug output (as the @DEBUG parameter is defaulted to false within the procedure definition).

I’ve made a small adjustment to the where clause on the select statement within the procedure to return all results if the parameter value is 0. Good debug information can sometimes make you rethink a set of statements general structure; something I view as a good thing. The same as doing test-driven development within C# can alter the way you construct your code base, objects and implementation details, writing debug handling into Stored Procedures can help you write more elegantly constructed and robust SQL.

I’ve also decided to treat NULL’s as false from this point forward; this will of course just be down to what is acceptable functionally. It’ll no doubt depend on the business requirements.

Again, this represents the simplest possible way to tie this concept into Stored Procedures. I’ve personally found this approach incredibly handy when dealing with procedures that handle a large number of variables and those that produce very complex dynamic SQL. With the latter this pattern really comes into it’s own, enabling you to print out dynamic SQL to the console to illustrate what is going to be executed, which equates generally to a nice little time saver if problems do occur. Just be careful to not overdo it and use common sense on what to include in any debug output :-).

Next up

I’ve been having a little think about what to cover next, keeping in mind that I want to at least attempt to shorten the posts and not drive everyone nuts with insanely lengthy content, etc.

I was chatting to one of my colleagues today and we arrived on the topic of debugging SQL Stored Procedures. To that end, I’m going to cover a quick debugging technique that I’ve found useful, and has become somewhat of a mainstay among the people I work with.

This will hopefully be up in the next couple of days.

jQuery is just a little bit sexy!

Cramming the word ‘sexy’ into the title was a sure-fire way of drumming up some attention. I’m happy to resort to dirty tactics as I’m still rocking my noob colours :-). It’s time to take a trip down the yellow brick, urm, jQuery road? Yes, I’ve said it now, so I’m sticking with it. I’ll start this in the way I mean to continue; with all of you wondering whether I’m mentally stable…..moving on!

I’ve been having a tonne of fun with this awesome JavaScript library. So much so, I think I’ve probably been driving all of my work colleagues a little bit nuts talking about it. I’m really not winning many friends here I’m sure but jQuery is, urm, just a little bit sexy dare I say it (sorry Claire, I’m sure I’ll pay for this later!).

I’m positive that I won’t need to tell too many people what this funky little API is all about, most developer buddies I have spoken to know of it, or are well versed (much more me than) in the wonders of what this has to offer.

jQuery allows you to perform HTML manipulation and traversing of the DOM (using CSS class selectors) as well as orchestrating some neat animation tricks.

I’ll aim to cover this API in further detail but I wanted to do a little ‘bear’ bones post to get this started (sorry, I couldn’t help it, bad joke I know!).

You’ve got a couple of choices on how to bring jQuery into scope; you can use a CDN (Content Distribution Network) or simply reference it from a known directory path. This can be done by dropping one of the following into the head element of the web page:

<!--Using the jQuery CDN (and using a designated version)-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!--Using the Google CDN (and using a designated version)-->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<!--Using a downloaded version of the file (stored within the _js directory of the website in this case)-->
<script type="text/javascript" src="_js/jquery-1.11.1.min.js"></script>

I’ll dodge the downloaded file vs CDN debate for now and just concentrate on jQuery’s usage, mainly due to the fact that I get the impression this incites violence among normally civilised folk.

For the purposes of a quick showcase I’ll utilise the jQuery ready function (as we’re going to be manipulating loaded HTML I want to make sure that this process is fully completed before the tinkering begins – Placing code in this function removes the possibility of us attempting to reference unloaded parts of the page).

Immediately beneath the script tag created to bring jQuery into scope bang in the following code:

<!--Add the long-hand ready function declaration to perform actions once the page HTML is loaded-->
<script type="text/javascript">
	//Long hand ready function declaration
	$(document).ready(function () {
		//Code goes here, for instance...
		console.log("Hello world! In the ready function!");
	});
</script>

I’ve decided though, with barely a second thought for the poor long-handed approach, to adopt the short-hand declaration myself:

<script type="text/javascript">
	//Short hand ready function declaration
	$(function () {
		//Code goes here, for instance...
		console.log("Hello world! In the ready function!");
 	});
</script>

You’ve got some choices in regards to how you want to target your code on the various elements found on a given web page. In general, at least for me so far in a very basic sense, I’ve been targeting elements by id, class and the actual tag type (element type) as follows:

<script type="text/javascript">
	//Short hand ready function declaration
	$(function ()
	{
		console.log("Start of ready...");

		//Get access to a DOM element (pure JavaScript) using traditional means. You'll only have access to normal JavaScript members
		var headerContainer = document.getElementById("HeaderContainer");
		console.log(headerContainer.innerHTML);         //Getting container html

		//Retrieve a 'jQuery Object' based on 'id'. You'll get access to jQuery specific members this way (equals awesome). Notice the use of hash in this scenario
		var $headerDiv = $("#HeaderContainer");
		console.log($headerDiv.html());                 //Getting container html

		//Retrieve a 'jQuery Object' based on CSS Class (representing all objects using that class). Notice the use of a period before the class name
		var $specialParagraph = $(".SpecialParagraph");
		console.log($specialParagraph.text());          //Getting element content

		//Retrieve a 'jQuery Object' by tag type (again, representing all objects using that element type). Just specify the element type using a string, no special prefix required
		var $h1Elements = $("h1");
		console.log($h1Elements.text());                //Getting element content

		console.log("End of ready...");
	});
</script>

Here, you can see that there are a couple of nuances when compared to selecting elements via pure JavaScript. The first is the use of the ‘$’ character, which is basically short-hand for specifying ‘jQuery(“selector”).function()’ – Essentially you’re using saying, “hey, I want to work with a jQuery Object please.”. Next up, you’re required to pop in a couple of parentheses and between these you provide a string specifying a ‘selector’, in turn denoting what kind of element/s you are trying to retrieve, and ultimately manipulate. Using an ‘id’ requires you to prefix the value with a ‘#’ and a CSS class requires a ‘.’ prefix. Grabbing elements by type doesn’t require a specific prefix at all so just place in the element you’re looking for and you are good to go.

In the examples above I have stored the DOM Objects and jQuery Objects in variables before operating on them. So far, I’ve been lead to believe that some developers prefix jQuery Object variables with a ‘$’ just to avoid any ambiguity in relation to any DOM Object variables sitting nearby, so I’ve followed this format. Anyone who stumbles along this with thoughts on whether this is correct please feel free to drop me a comment; I’d love to know how developers have decided to proceed in regards to variable naming conventions in production level code.

Just for simplicity, I’ve utilised the innerHTML property on the DOM Object and the .html() and .text() functions on the jQuery Objects (to get the selected elements HTML and text content respectively) and pushed these out to the console. The results of this can be seen below:

Various jQuery selectors in action.

Various jQuery selectors in action.

In order to have a little play around and provide a few simple illustrations of jQuery’s usage I’ve knocked up, what I’m sure you’ll agree, is some of the worlds greatest HTML markup (added to the pages body element) – Booyah:

<div id="HeaderContainer">
	<h1>jQuery Test Site</h1>
	<p>Welcome to the wonderful jQuery test website where we are going to do, urm, not a hell of a lot really.</p>
	<p class="SpecialParagraph">Only people who like craft beer see this paragraph.</p>
</div>
<div id="MainContainer">
	<h2>Here is a list box of my favourite things:</h2>
	<select id="GreatThingsListBox" multiple="multiple">
		<option>Chocolate Cake</option>
		<option>Chocolate Brownie</option>
		<option>Chocolate Something or Other</option>
		<option>Craft Beer</option>
		<option>Video Games</option>
	</select>
</div>
<div id="AnotherContainer">
	<button style="height: 35px; width: 75px" id="ClickMeButton">Click Me!</button>
</div>

So, I won’t be winning any awards for that! I’ve been staring at the colour palette of the test site whilst creating this post and I’m definitely starting to feel a tad nauseous; get the sick buckets at the ready :-).

Firstly, lets take a look at a quick example that shows the simplicity of jQuery at work. The first code snippet shows my attempt at using JavaScript to retrieve all ‘option’ elements on the page. After retrieval, I do a loop through the found elements and call setAttribute to add a title attribute based on the text value of the option:

<script type="text/javascript">
	//Short hand ready function declaration
	$(function () {
		//Possible approach, using pure JavaScript, for adding title attributes to 'option' elements
		var greatThingsListBox = document.getElementsByTagName("option");

		for (var i = 0; i < greatThingsListBox.length; i++) {
			greatThingsListBox[i].setAttribute("title", greatThingsListBox[i].text);
		}
	});
</script>

Here’s the same thing using jQuery (using the .each() function to iterate over the found ‘option’ elements).

<script type="text/javascript">
	//Short hand ready function declaration
	$(function () {
		//Set the title attribute on every option element (based on the options value) - using jQuery
		$("option").each(function () {
			$(this).attr("title", $(this).text());
		});
	});
</script>

The .each() function can be passed a normal JavaScript function name (which will run for each item selected), but in this case I’ve used an anonymous function call. Within this function, and this is something that I really love, it’s a real cinch to get hold of the jQuery Object currently in scope using the ‘$(this)’ syntax (this is the current ‘option’ element). Not specifying the $(this) enables you to act on each element as a traditional DOM element if you want/need to. From a keystrokes perspective, and I think readability, we’re onto a winner.

This is the end result of the above jQuery code (my cursor is placed over the List Box item):

Title attributes (resulting in tool tips) added to each list item.

Title attributes (resulting in tool tips) added to each list item.

Looking at the page, you’ll notice that we have a very special paragraph implemented in the ‘HeaderContainer’ div. If you’re not a craft beer drinker like myself then I would really like to hide this element from view (p.s. beer comments/recommendations welcome to!). jQuery provides a very tidy and convenient way to accomplish this task via the use of the .hide() function.

Note: from this point forward I’ll be omitting the ready function declaration to simply emphasise the jQuery code snippets themselves:

//Hide the paragraph with the '.SpecialParagraph' CSS class
$(".SpecialParagraph").hide();

This removes the paragraph from view as show below:

Paragraph hidden via jQuery.

Paragraph hidden via jQuery.

A quick sniff around the DOM using your browser development tool of choice will indicate that jQuery has applied a style to the element in reaction to the .hide() function call (style=”display: none”). I think you’ll agree this is nice and simple, and with the power of using CSS selectors it’s quite easy to target a number of elements simultaneously. Also, for me, it’s just so darn readable; I’ve really found the syntax incredibly easy to pick up and play with. It’s clear to see that one of the core crowd pulling powers of jQuery is that it’s not all that intimidating and papers over some of the inherent complexities of JavaScript quite nicely. Put simply, it’s bonza!

Once you’ve brought a shiny jQuery Object into scope you are free to draw on a concept called ‘Function Chaining’ where multiple functions can be called on the object using a single statement. Syntactically and aesthetically, coming from a C# background with a serious love of LINQ and extension methods, this ticks all of the right boxes for me.

The code snippet below first hides our special paragraph (using the CSS class applied as the selector), then applies a small piece of custom CSS using a construct called an Object Literal (essentially, property/value pairs) and finally uses the .slideDown function to elegantly animate the paragraph into view, over the specified time frame:

//Retrieve a jQuery Object representing elements with the SpecialParagraph class and hide them on load (just the one is this case). But this time,
//use 'function chaining' and apply some custom css (or we could have called addClass to apply some kind of style) and animate the paragraph/s
//so they 'slide' down into view
$(".SpecialParagraph").hide().css(
	{
		"background-color": "black",
		"color": "red"
	}).slideDown(1500); //Slide down into view over 1.5 seconds
Paragraph sliding into view (with a bit of custom CSS applied).

Paragraph sliding into view (with a bit of custom CSS applied).

Hooking up to events is also a doddle. For example, to hook up a click event to a selected element/s you can call the .click() function and pass it an anonymous function or an existing raw JavaScript function that performs the required task, as below:

//Rig the ClickMeButton's (selected by id here) click event up (tied to an anonymous function in this case)
$("#ClickMeButton").click(function () {
	alert("Click me clicked. I could really do some complicated work now!");
});
//JavaScript function to handle the click
function respondToClick() {
	//complicated code goes here
	alert("Click me clicked. I could really do some complicated work now!");
}

//Short hand ready function declaration (included in this example to provide context)
$(function ()
{
	console.log("Start of ready...");

	$("#ClickMeButton").click(respondToClick); //Could just be a raw JavaScript function

	console.log("End of ready...");
});
Example of a click event firing using jQuery to tie the event up to the element.

Example of a click event firing using jQuery to tie the event up to the element.

Moving further down this lovely yellow brick road, and this is something I’ve really enjoyed playing around with, it’s possible to call the jQuery .on() function to bind multiple events at the same time. As before, you can hook in raw JavaScript functions or anonymous functions, the latter seems to be the order of the day from what I’ve learnt so far (and rightly so, they are ace!). In the next code snippet I’m concurrently binding a click, mouse enter and mouse leave event to a button (again, selected by ‘id’) to build a slightly more interactive element (i.e. chopping and changing styles depending on whether the mouse is over the element):

//Simultaneously hook up the ClickMeButtons click, mouseenter and mouseleave events to various anonymous functions. 'On' comes in handy for 'event delegation'
//which I'll cover in a future post
$("#ClickMeButton").on(
	{
		"click": function () {
			console.log("click.");
			alert("Click me clicked. I could really do some complicated work now!");    //Handle a 'click'
		},
		"mouseenter": function () {
			console.log("AltStyle added.");
			$(this).addClass("AltStyle");                                               //Add the AltStyle to this element on 'mouseenter'
		},
		"mouseleave": function () {
			console.log("AltStyle removed.");
			$(this).removeClass("AltStyle");                                            //Remove the AltStyle from this element on 'mouseleave'
		}
	});
jQuery 'on' function example in motion.

jQuery ‘on’ function example in motion.

The on(). function has a very unique part to play in relation to the concept of Event Delegation, which I’ll cover fully in a later post. To serve as a very brief example, you may have an existing unordered list (ul) element on a web page, simply with no list items yet (li elements). The list items are dynamically created at some point after the page has loaded, perhaps on a button click for instance. In this scenario, if you wanted to tie a click event to each list item, you would have to do it on creation of each element (plus each item would require a separate handler which might not be all that yummy once the list becomes larger). This couldn’t be achieved on page load as the elements wouldn’t exist yet. With Event Delegation it is possible to palm off the click event to the parent unordered list element on load for any list items added later on to respond to, reducing stress levels and hair loss for the developer.

Rounding off the ‘cool’ factor of jQuery I wanted to show you an example of the hover function with a simple animation routine plugged in. I’ve rigged the code formatting a little to make this a little more readable. As I am used to C# formatting I still find the default placement of braces a little annoying from time to time when formatting via Visual Studio. Here’s the weird and wonderful snippet anyway:

//Utilise the hover function on the ClickMeButton that allows you to specify two anonymous functions (or tie in two existing javascript functions). The first one
//handles mouseenter and the second one handles mouseleave. In this example we are using .animate() to manipulate a buttons height/width. The jQuery UI API allows
//you to animate colour transitions and allows you to utilise some interesting 'easing' functions if you bring this into scope also
$("#ClickMeButton").hover
	(
		//Mouseenter
		function ()
		{
			console.log("Entering element.");

			//Make the button larger over half a second. Calling .Stop prevents animations from 'queuing' up
			$(this).stop().animate
				(
					{
						"height": "70px",
						"width": "150px"
					},
					500
				);
		},
		//Mouseleave
		function ()
		{
			console.log("Exiting element.");

			//Make the button smaller (set back to the original size) over half a second. Calling .Stop prevents animations from 'queuing' up
			$(this).stop().animate
				 (
					 {
						 "height": "35px",
						 "width": "75px"
					 },
					 500
				 );
		}
	);
Button before the hover event fires.

Button before the hover event fires.

Button after the hover event fires.

Button after the hover event fires.

The hover function is a compound function that enables the developer to simultaneously handle the mouse enter and mouse leave events in a single statement. I class this as simple syntactic sugar, but I love it all the same (give me lambdas and anonymous methods any day thank you!). This probably boils down to the fact that I’m easily pleased by the smaller things in life.

As the snippet above shows, the hover function is taking two separate anonymous functions as arguments. I’ve coded these functions to manipulate the elements height and width properties, using the .animate() function, to alter the values over a specified time frame.

jQuery UI, another branch off from jQuery, enables more complex animation effects to be kicked off (such as animating an elements colour properties). It’s certainly something to check out if you’re finding any of this interesting.

If you want an easy way to add, remove, copy and move HTML content on the fly easily then you’re really in luck here. There are a good number of functions built-in that will enable you to get your head down and deal with the task of handling changing HTML content dynamically. This next example illustrates one of the more basic functions, .append(), which enables you to specify a string of HTML content to place at the end of the selected element/s:

        //When theClickMeButton is clicked append HTML to the List Box (select element)
        $("#ClickMeButton").click(function () {
            //Add a new hard-coded option to the List Box (this would obviously be a much more dynamic example)
            $("#GreatThingsListBox").append("<option>Coding</option>");

            //Grab the last 'option' element on the page and set it's title attribute based on the text value (giving us a nice little tool tip)
            //You could do this by using: $("option").last().attr("title", $("option").last().text()); but storing the jQuery Object in a variable saves on processing (i.e the re-selection of the element)
            var $lastOptionOnPage = $("option").last();
            $lastOptionOnPage.attr("title", $lastOptionOnPage.text());
        });

This last snippet introduces the Event Object, which can be specified as a function parameter (which the engine is implicitly passing for use) and used within an anonymous function. This stores handy nuggets of information about the event that has been fired. In this case, I’m just pushing screen co-ordinates to the console to illustrate where a click occurred:

//Using the event object (any parameter name can be picked, I'm using 'evt') and pulling out the current screen co-ordinates on click
$(document).click(function (evt) {
	console.log("X Co-ord: " + evt.pageX + ", Y Co-ord: " + evt.pageY);
});
The Event Object in action.

The Event Object in action.

The post is nowhere near as short as I would have liked but I have developed a bit of a soft spot for jQuery so I’ve gone over the top. Why the hell not I guess, it’s free, reliable and heavily used and distributed under an MIT licence, what’s not to like! Whilst I’m on a ‘love rant’ I may as well mention that an extensive amount of Plug-Ins are available, adding to the fun in my opinion. It’s also incredibly easy to draw out hidden and selected elements using jQuery (i.e. from a set of check boxes, for example), so read up if you’re interested. I hope you’ve enjoyed the first, real, coding post. Enjoy, like, comment, subscribe, talk to me about craft beer and code, etc. Whatever takes your fancy.

I haven’t decided on my next topic yet but I’d like to get something out of the door by the end of the week, so watch this space. Cheers to Pete for the jQuery book you’ve loaned me and to Claire for reading through this (it would have been much messier without your intervention!).

DISCLAIMER: All of the code snippets were ruined seconds before posting by the proof reading tool so I had to mend them on the fly, with any luck I’ve caught all of the screw ups!

Useful links:

jQuery Website
jQuery API Reference Guide
The Missing Manual Series JavaScript and jQuery

Cheers all!

So….No posts…What am I doing then?

So, I’m not afraid to admit that this is taking me a hell of a lot longer than I originally anticipated. I was chatting to my fiancée Claire today about all of my hopes and dreams for this blog. I stated that I wanted to:

  • Keep the posts simple to start with.
  • Keep the posts as short as possible to start with.

I’ve failed, on both counts. I’m working on a piece right now covering some of my early experiences with the super gorgeous jQuery, which I’m just having an immense time with. The post has ended up being far longer and a little more involved than I originally planned. I’ve got a few development buddies who have managed to peak my interest levels in jQuery to dangerous levels. To that end, I’m trying to genuinely write as good a piece (based on 15-20 odd hours with this library) as possible.

It’s about 60 percent of the way there. I’ll plan to get it tidied up and posted tomorrow evening.

I suppose this is a great time to actually state how often I intend on updating this blog 🙂 (terrible blogging etiquette I know!). The aim is to get 2 posts out a week if I can keep a handle on the detail/length of the posts.

Watch this space anyway, I’ll be coming back shortly with something that hopefully floats everyone’s jQuery boat!

Bye for now…