Pages

Wednesday, October 24, 2012

jsonmé: A Simple HTML and JavaScript Resume Generator

It's been forever since I updated my resumé so I decided to turn my GitHub page into my living resumé.  Being a web developer I wanted to so something unique yet simple.  After playing around with a few concepts I decided to put all of my resume's data into a JSON file and create a small web app that would read it via AJAX and display its contents.  I was so happy with the result that I decided to extract out the code and put it up on GitHub and the result is jsonmé.

I wanted jsonmé to have a small footprint yet work in all browsers back to IE6.  I decided to use the Sizzle.js selector engine since it has such a proven track record in jQuery.  I also needed a small library for doing normalized AJAX requests.  I settled on snack.js, its a small and well written utility library with AJAX capabilities that also gives me a normalized document ready function.  

The resulting application is a simple and easy to implement application.  The easiest way to create your jsonmé is to fork the GitHub repository and rename it to .github.com.  For instance my personal resume is at http://bittersweetryan.github.com.  

The code is completely Open Source and licensed under the MIT license so feel free to grab it and do whatever you want with it.  If you do something awesome with it I'd love to hear about it or even get a pull request for it.

The source can be found at: https://github.com/bittersweetryan/jsonme

Thursday, October 4, 2012

Using the Partial Application Pattern in ColdFusion 10

The partial application pattern has been popular in JavaScript for some time now, Ben Alman has a great article on it: http://benalman.com/news/2012/09/partial-application-in-javascript/.   While refactoring some particularly redundant code I decided to try this pattern in ColdFusion using the power of closures and the function datatype.

The Partial Pattern


Lets start by taking one of Ben's examples and converting it to ColdFusion. Minuse a few syntactical changes we could almost copy and paste his code into ColdFusion. Lets start of by looking at a simple add function:

Now lets say we use that function to add one to a few numbers:

Instead of passing the parameter one to each function call wouldn't it be nice to have a function called addOne that just adds one to whatever argument is passed in? Simple. We can just create a new, more specialized, function that returns the invocation of our add function that always passes one as its first parameter:

Thats great. What if we want to add other numbers? We'd have to create a separate function for each number. What if those numbers aren't always known when we are writing our code, are we going to write a million different utility functions? Of course not. We can take the concept of creating a specialized function step further using the function datatype and closures to create a partial application that will help us construct new helper functions on the fly:

Looking at the code there are a few important concepts to note. First look at how this new function returns a function, this is a new datatype on ColdFusion 10 so this code will not work in any version less than 10. Second, and most importantly, look at how this new function is a closure. When we invoke the makeAdder function the inner function that is returned has access to makeAdder's argument even after makeAdder is invoked.

Since the makeAdder function returns a function we need to set a variable equal to the makeAdder's result to use it. Once we do that the new function can be invoked just like any other function:

Real World Example


In my application I had a function that took a long list of arguments which was called multiple times with only a few of the arguments changing between each call. This created some ugly code that was getting to be a pain to maintain. Instead of calling this function multiple times passing in all the arguments each time I decided to use the partial application pattern to clean up some of my code. This is what my new partial function looked like:
Instead of having one function that has 7 arguments that is called multiple times I have one function that takes 5 arguments that is called once. This function returns another function that gets called with only 3 arguments:

When ColdFusion first got closures I was unable to make the mental connection to how I was using closures in the JavaScript code I was writing. Slowly I am starting to write my ColdFusion more like I write JavaScript.




Wednesday, October 3, 2012

NCDevCon "The Art of JavaScript" Presentation Links

This is just a real quick post so I can share the link to my NCDevCon presentation slides and video.

The slides can be found at:

http://bittersweetryan.github.com/art-of-javascript/

The video can be found at (sorry, its in Silverlight format only):

http://textiles.online.ncsu.edu/online/SilverlightPlayer/Default.aspx?peid=02c7fe6174654f96b78a6194d3dbbe9d1d

One more thing, I was mentioned in the KeyNote!  You can watch that here, I'm mentioned in the second section about: "ColdFusion Today":

http://textiles.online.ncsu.edu/online/SilverlightPlayer/Default.aspx?peid=9c64b0db237e4240847875f95795138d1d

Please if you enjoyed let me know, or if you have any questions or suggestions how I can make this presentation better please let me know!

Thursday, September 6, 2012

ColdFusion Quickie : Using the Ternary Operator To Pass Conditional Argument Values

Its been awhile since I've done a ColdFusion quicke post and I found this trick to be quite useful  especially when dealing with ORM domain entities.

Lets say that we have a domain object called User that gets populated out when a user signs up for an account.  This object has some simple properties; fullName and email (lets not get into object purity here and say that those should be a member of a Contact object).  Lets also assume that when a user signs up all only an e-mail address is required, they can leave their name blank if they choose to.  The important thing to note here is that when a user object is loaded from the database the fullName property may hold a value of null.

When a user signs up for an account our application calls a function that will send a welcome message to a user that has a signature of: sendWelcomeMessage(required String name, required String email) (for arguments sake lets say that we don't have the ability to change.  If this function is invoked using implied getters from the User object we'll run into problems if getFullName() returns null. This is where the ternary operator can quite useful in sending a default value to a function:

sendWelcomeMessage( 
    (!isNull(person.getFullName()) ? user.getFullName() : "User" , 
    user.getEmail
);

The ternary operator takes a value or expression that can be evaluated to a Boolean and returns one of two things based on the result of that expression. The ternary operator's signature looks like this:

(expression) ? trueStatement : falseStatement

As you can see in our example, we check if person.getFullName()does not return null and pass that value if its true, otherwise pass in a default value of "User".

Tuesday, September 4, 2012

jQuery Function Of The Week: Deferred (deep dive)

This week we'll take a deeper look into jQuery's Deferred object.  According to the jQuery docs:
jQuery.Deferred(), introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
That is a bit of a mouthful.  I like to think of deferrds somewhat like a telephone call.  You'd like to contact someone so you dial a number.  Based on what happens when you call that number you will take action.  If the callee answers the call you can start a conversation, if you get their voice mail (I almost said answering machine but I'm afraid that some readers will have no idea what that is) you can take leave a message.  Also, when the phone is ringing you can even do something else, you only care about what happens once the number you are calling responds in some way.  This is an extremely simplified way of describing how Deferreds work because Deferrds can do so much more.

If you've used jQuery's AJAX functions you've already been taking advantage of Deferreds, the AJAX functions are actually using Deferrds behind the scenes with a lot of the details abstracted out for you.

When talking about Deferreds its important to note that there are two parts to each Deferred implementation: the callers and the callees.  The callers are the functions that either do something that other functions are waiting for or functions that take action based on the results of another function.  The callees are the functions that depend on the results of at least one of the callee functions.

The Callers

Like I mentoned before, the caller functions are divided into two parts: the functions that do something that other functions depend on, and the functions that take action based on the the results of other functions.  The when(deferrds)function is the first part of the callers and is a wrapper for all of the functions have results that other functions are waiting for.  jQuery will execute the functions passed into when immediately and asynchrouously.  This means if we have the following code:

func1(), func2(), and func()will all be called at approximately the same time.  

Functions passed into when are expected to return a promise object back to the when() function.  This promise will either be resolved or rejected (more on these in the callees section) by the function passed into when, and based on this result one of callback functions will be called.  

The second part of the callers are the functions that respond to the results of the functions passed into the when function.  The three functions are: then, done, and fail.  The then(doneCallbacks, failCallbacks) is a single method that encapsulates the functionality of the done() and fail() callbacks.  The first argument to the then function is a function, or array of functions, that will be called when all the functions passed into the when() function are resolved.  

The second argument passed into the then function is a function, or array of functions, that will be immediately invoked as soon as any of the functions passed into the when() function are rejected  The then and done functions will receive arguments from each function passed into the when function, in the order they were passed.   These arguments are passed into them via the resolve and reject methods (we will talk about when we discuss the callees).  If you'd like to be a bit more expressive in your code instead of using the then() you can specify the doneCallbacks and failCallbacks in the done() and fail() methods.  These methods are called the same was as the doneCallbacks, and failCallbacks of the then() function.

The Callees

When functions are passed into the when function jQuery expects these functions to return a promise to it.  A promise is just a message telling the when function that sometime in the future the function is either going to send it a  reject( args ) or resolve( args ) message.  Once the when function receives the promise object from a function it just sits and waits for a response.  The callee functions can also pass information back to the when function by passing arguments into the reject and resolve methods (I'll show you an example of this in the real world example).  Lets take a look at a typical callee function that implements the Deferred object and talk a bit more about what is going on:

Here we have a function that is going to implement the $.Deferred() function and immediately return a promise message to the when() function that called it.  The $.Deferred() constructor  function takes an optional function as an argument which is passed a reference to itself as an argument.    The above function could also have been rewritten as: 

Its important to note that if a function passed into when does not implement this Deferred pattern it will immediately be treated as resolved.

Real World Example

Now that we've looked at the parts of the Deferred lets take a look at a real world example.  In order to demonstrate the power of Deferred's lets take a look at some code that can benefit from them:
JS Bin

The intent of this code is to fade out any current content, get some tweets from twitters search API, and finally display the new tweets.  When any of the buttons are pressed you'll quickly see that something isn't right, and this is because the code being called relies on asynchronous operations like doing an AJAX call and jQuery animations.

One approach to fix this would be to put the getTweets function as a callback to the cleanDiv function's fadeOut callback, move the addTweets function to the ajax calls success callback, and finally move the the $tweetDiv.fadeIn('slow') code to the addTweets function. Doing so would tightly couple this code together making it tough to extend and maintain.  A better solution would to use the power of jQuery's Deferred object.

First lets look at our click handler function rewritten to take advantage of the Deferred object:



The first thing you probably notice is that there is more code in the new click handler.  The Deferred calls do add a bit of code, but I feel this code is quite expressive (meaning that the intent of the code is very clear) and each of the callback functions are decoupled from any function they are waiting on.  One other thing to note here is the use of the done() and fail() callbacks.  In the done() callback I use the when() and then() methods of the Deferred implementation.  Here I am only specifying a  single argument which will get called if/when the addTweets function passed into it has completed.  Since I'm not going to reject the promise anywhere in the addTweets function only passing in a done callback is sufficient.

Now lets take a look at one of the new callee functions.  Here is the code for the new getTweets function:



Since there is no access to the internal representation of the $.ajax method's Deferred function I have to wrap the entire function in a Deferred call.  Another thing to note is that Twitter's API will return a 200 status (which will invoke the ajax function's success callback) even if there is an error so  I will inspect the object returned from Twitter when determining weather to resolve or reject the Deferred object.  If a key of "error" is found in the data returned from Twitter I reject the Deferred which tells our click handler function to run the fail callback.  I'll also pass a message to the fail callback through the reject method call.


Putting it all together we get a nice and smooth implementation of our application.  As you can see I've also included an error button which will trigger an error in the twitter API.

JS Bin

Tuesday, August 14, 2012

jQuery Function of the Week: grep

This week's jQuery function of the week is grep.  According to the jQuery docs grep:
Finds the elements of an array which satisfy a filter function. The original array is not affected.
There is only a single signature for the grep function: $.grep(array, function(element, index) [,invert]). The function being passed in should return a truthy value or a falsy value based on the input argument.  If the invert parameter is left out, or is false then the grep function will return a new array with all the items that the satisfy the truth test function that was passed in.  If invert is set to true, grep will return a new array with all the items that do not satisfy the truth test function.

Lets take a look at looping through an array of text and removing the word "the":

JS Bin demo

Now lets take a look at the same code, but with the invert parameter set to true:

JS Bin demo

You'll see that only the word "the" is returned.

Check out the all of the jQuery function's of the week.

Thursday, August 9, 2012

jQuery Function Of The Week: nextAll

I'm super busy this week so this week's jQuery function of the week is going to be an easy one: nextAll.  According to the jQuery Documentation use nextAll to:
Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
Lets say we had a list of items, and we wanted to highlight every vegetable  Using nextAll would look like this:

JS Bin demo

Optionally a selector can be passed into nextAll to further filter the results.  Here we'll only select the even vegetables that are after our original selector:

JS Bin demo

Wednesday, August 1, 2012

jQuery Function Of The Week: proxy

In my JavaScript fundamentals presentations I have a section that talks about scope and how it can become confusing when using jQuery.  The reason for this is becuase jQuery normalizes the this scope in its function calls.  In other words when inside a jQuery method call this usually refers to the DOM elements in the jQuery set.

This can be clearly illustraed in a simple jQuery event callback (note use your browsers console, not jsbin's for the meantime):

JS Bin demo

This can become a problem when we try to write reusable code. Lets say we want to put our event handler into a object and then call it when a user clicks on a link:

JS Bin Demo

If you run the code you'll see that you get "Hello, undefined" instead of "Hello, Homer Simpson". The reason is simple, jQuery used the link as the context of this where no myName property exists. Enter jQuery.proxy.

According to the jQuery Documentation, the proxy function:
Takes a function and returns a new one that will always have a particular context.
This means that by using the $.proxy function we can make our callback run in the proper context, in this case itself:

JS Bin Demo

The change is subtle, but the result is exactly what we want.   Now, at this point you might be asking yourself, "isn't this the same thing as using the apply() or call() methods (mdn apply documentation)?   The answer is yes...and no.  Lets look at how to get the desired result using apply():

JS Bin Demo

If you look closely you'll notice a slight difference, the callback is now invoked in an anonymous function instead of passed directly to the on() method.  This is because the apply method invokes the function immediately whereas jQuery's proxy function only returns a reference function for later invocation.   This is a bit nicer because it makes for slightly more terse code.

In addition the proxy() function does a few more things:

  • it makes sure that the function passed in is actually a function
  • it assignes a unique ID to the function.  This is very important because when trying to unbind a function you may not be unbinding the proper function if you are passing in the function to the off() method.  Its best to always use namespaced events when using on() and off() with $.proxy().

Friday, July 27, 2012

Solving JavaScript Async Issues the Easy Way, With Events

By now we all know that JavaScript is asyncronous and what that means, right?  If not the following code will help explain the concept in 30 seconds:


This code will run function a() then b(), even if the ajax request in a() has not yet completed.

There are a lot of approaches that can be used to make sure that b only runs when a is done.  One approach would be to use jQuery deferreds like so:


We can also use a async library, such as q, if we need a bit more power.  Or we can use JavaScript's setTimeout(func, delay) function to continuously check for a variable the function a() sets when it is done before we call b(), how awful does that sound? In some cases there is a quite simple way to achieve this, by using events.  I might even argue that using events is the more JavaScripty way to do things in the right situation.  Lets take a look at the a/b example, this time using events:


Lets take take a look at a real world example of using events to make sure things happen in the proper order.  Here we will use a backbone collection as a wrapper for a one or more Contact objects that will be reused in multiple places in an application:


Let say we want to use this collection to populate a drop down when a view is initialized like so:


Using this code there is a good chance that the models will be an empty array when we try to add them to the dropdown.  Also, when the collection's fetch() completes the app.contacts.models array will be reset, meaning that the reference to the contacts in your view likely will not reference the current app.contacts.models array.

To fix this, lets first update our collection to trigger an event when the contacts are loaded.  In this example I'm going to use jQuery's trigger(eventName) function to keep things easy:


The last step is to make sure we are adding the carriers to the drop down after they have been added to the collection. To do this we just need to add an event listener to our initialize function:



Now we will always be working with a populated collection in our addContacts method.

Monday, July 23, 2012

jQuery Function Of The Week: one

jQuery's one function is an extremely useful function when you want an event to fire exactly one time.   According to the official jQuery documentation use one to, "Attach a handler to an event for the elements. The handler is executed at most once per element"  One is a much more terse way of setting an event handler and calling unbind() or off() in the handler function.

The easiest use of one is to pass it an event and a handler like so:



Click Here to Demo on JS Bin

You can click the link as many times as you wish, however the event will only fire once.

You can pass in more than one event handler to the one function by passing in a list of events separated by a space.  When you do this each event will fire once.  In this example the event will fire 3 times, one time for each event:



Click Here to Demo on JS Bin

You can also  pass in custom data to the event handler, the data comes attached to the event.data object like so:



Click Here to Demo on JS Bin

One additional thing you can do with the one function is use an additional selector to pass into the one event that will attach the event to exactly one of the descendants of the matched set. In the following example click on any of the li elements, then click on another, you'll see the event only fires for the first element selected.



Click Here to Demo on JS Bin

Check out the all of the jQuery function's of the week.


Wednesday, July 18, 2012

Playing Around With JavaScript's stopPropagation and preventDefault Methods

While playing around with pure JavaScript events lately I created this jsfiddle to demonstrate the concepts of the event methods preventDefault() and stopPrpagation().  While you are playing with it make sure to have your Browser's console open so you can see the debugging output.

The preventDefault() method on an event, does exactly that, prevents the event's default behavior.  In this instance it stops an <a> element from going to the link.  The stopPropagation() method stops the event from bubbling up DOM nodes.  In this case we have an <a> link nested in a <span> that is nested in a <div>.  When a user clicks on the <a> the event is triggered on that element, then the span, then the div, all the way up the DOM until it reaches the document node.  Calling stopPropagation() on the <a>'s click event only triggers the event on the <a> element  and none of its parent nodes.  

Thursday, July 5, 2012

Screencast: Awesome New Feature In The ColdFusion SublimeText Package.

If you haven't updated your SublimeText ColdFusion package recently you really need to.  The one I only know as atomi has added function intellisence, which in my opinion is huge!

From what I experienced in the early release it only works after a function is added and the file is saved, however once you do you can now start to type the name of a function and hit "tab" and Sublime will fill in the function WITH the parameter names and types.  Check out the video below to see this in action.


SublimeText ColdFusion Function Intellisence from Ryan Anklam on Vimeo.

Tuesday, July 3, 2012

ColdFusion Koans Drive Extended

I've decided to extend the ColdFusion Koans contribution drive till the end of July!  The project received lots of great contributions, however, some potential contributors ran out of time while working on making their contributions awesome.

If you don't know what the drive is all about check out my original post.


Friday, June 15, 2012

Screencast: Contribute to the ColdFusion Koans in 3 Minutes Without Git!

You may have heard about my recent ColdFusion Koans Contribution Drive, if not I need to do a better job making noise about it!  Just to reiterate, I'm giving away TWO copies of ColdFusion builder to lucky participants.  I'm also giving away a sweet GitHub sticker to the next 8 people to add a test through GitHub.

Since GitHub may feel like a barrier to entry for some people I've created this screencast to show just how easy it is to contribute to the Koans project without even having to have git installed on your system.  GitHub has a fantastic online editor that will allow you to edit the Koans source files without actually affecting the master branch of the project.  When you edit a file online GitHub automatically will put a new copy of the project in your account where you can edit away then send me a "pull request" in two clicks!




Contribute To the ColdFusion Koans from Ryan Anklam on Vimeo.

Monday, June 4, 2012

*Updated* ColdFusion Koans Contribution Drive - Win A Copy Of CFBuilder!

**Update New Screencast**

I've just added a screencast to show you how easy it is to contribute without having to touch Git at all!  http://blog.bittersweetryan.com/2012/06/screencast-contribute-to-coldfusion.html

The title says it all, its time for another ColdFusion Koans contribution drive.  One thing that the title does not say is that I'll actually be giving away TWO copies of ColdFusion Builder!   Adobe has been generous enough to sponsor this drive and donate the two copies of ColdFusion Builder,  I can't thank them enough for their generosity.  

Now its our turn as a community to show Adobe what we can do.  Right now the Koans test suite sits at 80 lessons, I'd like to see that at least double. Please share the word with your fellow developers, tweet about it, blog about it.   Lets rise up and show Adobe how awesome the ColdFusion community really is and how much we care about the next generation of ColdFusion developers learning not only the ColdFusion language, but the proper way to write professional code.

In addition I'll  send a GitHub sticker for the first 9 people who submit a pull request that is brought into the Koans project.   Don't worry, there aren't many reasons why I won't accept a test; only if I find something incorrect with a test or a test is duplicating an existing test will I not pull something in.  In those cases I'll likely just ask you to correct something and resend the pull request instead of flat out rejecting anything.

I'd like to thank Mike Henke and John Whish (of ORM Book fame) who have graciously volunteered their time to help me review the entries to make sure the Koans project is a high quality learning tool for everyone.

What are the Koans?  


By now you are either ready to get to work or  you are completely lost.  If you are lost let me back up a second and explain the Koans project.  Here is a little introduction to the ColdFusion Koans post I did awhile back, and here is a screencast on getting started with the Koans.   In summary, the Koans are a set of unit tests that are designed to teach people ColdFusion and Unit testing at the same time.  You download the Koans, copy the directory to your webroot, open index.cfm, then edit the source code to make all the tests pass.

What should I add?


There is a Readme included in the project's source file that has a few suggested topics such as new ColdFusion 10 functionality, more unit testing lessons, and object oriented topics.   However feel free to add anything you think would be useful to someone learning unit testing or ColdFusion.  Add a test for a particular tag you find yourself using a lot.   Add a test for a pattern you find particularly useful.  Be creative!

I don't know anything about unit testing. 


Thats just fine, and the Koans are for you!  I suggest working through the Koans (you'll even get an entry for doing so, see the "How Will The Contest Work") and I'm sure you'll learn a thing or two about unit testing and come up with an idea or two to make the Koans even better.


How Will The Contest Work?

Now that I've gotten that out of the way let me tell you how the contest will work.   Each new test added to the Koans project will get you one entry into the drawing  (If you have no clue where to start see the "I don't know GitHub Section" below).  If you add 5 new tests you'll get 5 entries into the drawing.   If you complete the Koans project and tweet a picture of the completed koans with the hash tags #ColdFusion #Koans you'll get an entry into the drawing.   If you blog about the Koans you'll get an entry into the drawing.   I'll be selecting the winners on June 30th at approximately 12:00 PM central time.

I Don't Know Git or GitHub!


This is yet another reason to contribute, adding a simple test and sending me a pull request is a great introduction to Git and GitHub!  The best part is that GitHub makes things so easy you don't even have to install Git or know a single Git command to contribute.   To do a Git-less pull request follow these steps:













  • Click on the Download as .zip link to download the Koans source code.














  • Extract the .zip file into your webroot and rename it to something a bit more friendly, I use ColdFusion-Koans.
  • Open the  directory in your browser, typically something like http://localhost/ColdFusion-Koans/index.cfm to make sure everything is working.
  • Open any of the Lesson files in your favorite IDE or Text Editor.  The lesson files are located in the "Koans"  directory, each lesson has its on .cfc.
  • Add a new test to any of the lessons by adding a new function that is public in visibility.
  • Refresh index.cfm in your browser to make sure that everything looks good.
  • Assuming that you have a GitHub account (if you don't it only takes a second to signup), goto the Koans project page and browse to the .cfc file that you just edited.  Click on the "Edit This File" button.  
  • Copy and paste your code from your IDE into the text editor GitHub provides.
  • Add a descriptive Commit Message below the code and click on "Propose File Change"








That's it.  I'll get the pull request and bring your changes in.

If you have any questions please feel free to contact me at ryan.anklam@gmail.com or on twitter at @bittersweetryan.  Good Luck Everyone!

Tuesday, May 22, 2012

Link To "JavaScript Fundamentals for ColdFusion Developers" Slides From cfObjective 2012

In case anybody comes here looking for my cfObjective presentation, here is a link to the slides:

http://bittersweetryan.github.com/javascript-for-coldfusion-devs/

The deck can be navigated by using the "left" and "right" arrows on your keyboard or by clicking on the left and right arrows on the presentation itself.

If you didn't attend my presentation, this deck contains a lot of code, and its all embedded and runnable within the presentation itself.  Clicking on the "Run" button in any of the slides will demonstrate the concepts being presented in your browsers console.

Notes From the cfObjective Sessions I Attended

I'd like to share the notes I took during this years cfObjective.  All the sessions I attended were excellent and I learned a lot listening to such smart people!

Building High Availability Services with Elliott Sprehn


https://www.evernote.com/shard/s20/sh/59782013-3b56-4e51-bfb8-20a60ebbd747/73031e9dde99bd9dff631384ad2b8ebf

HTTP for CF Developers with Nathan Mische


https://www.evernote.com/shard/s20/sh/5688f1d5-98fb-4d7f-bf80-49522f623e78/8cb5b0513343bc26ddf3ce78756c256a

Do's & Dont's Regarding Performance with Gert Franz


https://www.evernote.com/shard/s20/sh/835523f7-14dd-4d6e-9917-b5155f56337b/4012466727f0564a144f9f8c05ee2519

CFML Mythbusters with Mark Drew


https://www.evernote.com/shard/s20/sh/a266f107-2226-4c09-9bf0-59b93a70a473/f89b2ca939a6ee3c90b023c0c1a18374

Deep Dive: ColdFusion ORM with John Whish


https://www.evernote.com/shard/s20/sh/634c75cc-02bb-428a-a7a1-9fb779293d65/ca66cd5c88b68326ad29cba0eb24b1e3

Writing Secure CFML with Pete Freitag


https://www.evernote.com/shard/s20/sh/633924d8-0b74-41fb-8377-6adf3c7f388c/bc7c84f07d11dce1b9cdac8ff530f073

Production Ready JavaScript with Elliott Sprehn


https://www.evernote.com/shard/s20/sh/c6074df0-6253-4c4c-9145-f9aa0432d13d/89aa45a9e3699f4af86a91a23186c0db

Concurrency Zen with Marc Esher 


Marc must be such a compelling speaker that I was too focused to take notes because they really stink for this session.


https://www.evernote.com/shard/s20/sh/01686213-34ce-4108-948e-3fb0e9ceeb80/397ce9c7b0d83c6219d0dd2d30db4d44

Speedy Websites Through Better FrontEnd Optimizations with Peter J. Farrell


https://www.evernote.com/shard/s20/sh/d2996a7b-0048-44b6-af73-2a46371fd47a/9bedebc804b944574f3d1772c42a01d7

Tuesday, February 28, 2012

My Argument Against ColdFusion Sucks & Other Related Putdowns

While I was driving home last week I listening to the "Hearding Code" podcast with Chris Williams (the organizer of jsconf) and I had a small revelation.   Chris brought up how coders will use up one bad experience with a language to completely write it off and publicly denounce the it every chance they get.  Raise your hand if this immediately makes you of think of ColdFusion.   Me too.

Then I started thinking, JavaScript is one of the hottest languages around right now, and for good reason, it has evolved tremendously from where it was in the late 90's.  Does that remind you of anything?  If you are a ColdFusion developer it should seen very familiar to the language you use every day.  Anyone who writes modern ColdFusion code will likely cringe at the code they wrote back in the pre-MX days, just like a lot of the JavaScript developers did in the pre-jQuery/Dojo/Sencha/Prototype/MooTools days.

Next time we hear someone publicly call out ColdFusion for a one bad experience they've had with an app that was written in the late 90's early 2000's lets remind them about JavaScript and the many bad experiences we've all had with it back in its early days.  Lets also remind them how it has evolved into one of the most popular languages in the world.

ColdFusion, in my opinion,  has evolved just as much as JavaScript.  We have a great testing framework in MXUnit, lots of great MVC frameworks to chose from, and a number of other great frameworks that help us be productive such as Validate This, ColdSpring, Hoth, and Hyrule to name a few.  These are all advanced programming frameworks that weren't around in the early days.  In additon ColdFusion itself has also come a really long way as a programming language.  We can how write code in a way that many programmers consider much more elegant and terse with the script updates in ColdFusion9.   We can also use really powerful techniques like onMissingMethod, dynamic typing, and treating functions as first class citizens.  We have ORM capabilities baked right in the framework, how cool is that?!?

While agree it has taken ColdFusion a long time to get this far while languages like Ruby, Python, and even PHP have progressed at a bit faster rate its good that we have gotten where we are.  With the upcoming release of Zeus ColdFusion will take another step further with HTML5 controls built in, RESTful interfaces, closures, and a bunch more exciting features.  These are exciting times to be a ColdFusion developer and I hope that we can advocate the language moving forward by drawing parallels to other languages, like JavaScript,  that have had rough beginnings but are now considered "cool" languages.

Monday, February 20, 2012

Using ColdFusion 10's Function Data Type To Create a Map Function

In functional programming a map function is a way to create an array by passing each element of the array into a function.  Mapping functions are very commonly used in languages like Ruby, Python and JavaScript.  ColdFusion acts more like JavaScript in this respect where a Map is not a native function, however it is easy to implement.

Before I get into the code, lets take a look at how the map function works.   The method signature for map looks like this: public Array function map(Array arr, function fn). The map function takes and array and a function as parameters, and returns an array.  Each element in the array argument is passed into the function and the result is added to the result.

Without further adu, lets take a look a the code:



Running this code would produce this result:









Now this pattern can be applied anywhere you find yourself looping through an array and applying the same logic to each member of the array.

Friday, February 17, 2012

Changing the webroot of the ColdFusion 10 Beta (Zeus) Built In Web Server

If you run the ColdFusion built in web server on your local machine and want to keep your current webroot while playing with the Zeus beta here's how to change the web root:


  • Open coldfusion_install_location/cfusion/runtime/conf/server.xml
  • Scroll down to the end of the document where you see the line:  
<!-- Uncomment the line below to change the default web root or to add virtual directory
Make sure to replace <cf_home> with the absolute path to ColdFusion Home-->

  • Copy the last comment in the group of comments at the end, right before the line.  The line you want toc copy looks like (do not copy the beginning :  
<Context path="/" docBase="<cf_home>\wwwroot" WorkDir="<cf_home>\runtime\conf\Catalina\localhost\tmp" ></Context>

  •  Change the docBase attribute to your the ABSOLUTE path of the directory where you want your web root to be.  In my case it was /Applications/coldfusion9/wwwroot if you are on Windows this will start with a drive letter like c:\... or d:\...
  • Add aliases attributes to both the CFIDE directory AND the WEB-INF directory.  This step is extremely important, without it ColdFusion WILL NOT run.  To do this add a new attribute to the node called aliases.  Inside that attribute add the following text /CFIDE=/absolute_path_to_coldfusion_install_location/cfusion/wwwroot/CFIDE,/WEB-INF=/absolute_path_to_coldfusion_install_location/cfusion/wwwroot/WEB-INF  Again, if you are on Windows this will start with a drive letter like c:\ or d:\.  
  • This is what it looks like on my system (OSX):
<Context path="/" docBase="/Applications/coldfusion9/wwwroot" WorkDir="/Applications/coldfusion10/cfusion/runtime/conf/Catalina/localhost/tmp" aliases="/CFIDE=/Applications/coldfusion10/cfusion/wwwroot/CFIDE,/WEB-INF=/Applications/coldfusion10/cfusion/wwwroot/WEB-INF"></Context>

  • Restart ColdFusion10 and be happy.   

Wednesday, February 15, 2012

You Are Not the Language You Write Code With

Lately I've been thinking a lot about my career and what I'll think about when I reflect on it when I'm retired. Will I look at myself as a ColdFusion programmer?  Will I look at myself as a JavaScript programmer?  I'm pretty sure I'll just look at myself as a programmer.  This got me thinking about how others perceive me as a programmer.  Do others come to my blog and never read past the first two words of  "Ryan's ColdFusion and Web Development Blog"?  Am I automatically dismissed as a programmer because I primarily associate myself with ColdFusion?  I'd like to hope not but I'm sure there are more people that do than I'd like to admit.

This brings me to my point, a developer is not the language they prefer to code with.  A developer is defined by so much more than that.  I'd hire a good Python developer to write ColdFusion applications even if they've never even seen a line of CFML in their life.  A good developer will be a good developer in any language.

So what does define a developer if its not the language they write with?  For me its a few things, first its what they have given back to the programing community through their contributions to open source projects.  I'm not saying Java developers should go out and contribute to Ruby projects.  Its perfectly fine to stay in an area of expertise. The point here is that a developer that gives back by contributing to open source projects shows that they have a passion for writing software that helps others and for writing code in general.  Passion goes a long way to making a good developer.  

Secondly I think a developer can be defined by their thirst for learning new things.  The world of programming is always changing, it can be exhausting to think that the learning never stops.  It can also be exciting and fun.  I wake up each morning looking forward to learning something new, when this feeling stops I'll know its time to get into management.  A developer who doesn't embrase the ever changing landscape will quickly get left behind by others who are actively seeking new things to learn.

Lastly I think a developer can be defined by their willingness to teach and help others.  I'm not talking about speaking at user groups and conferences here.  Yes, those things take tons of time and preparation and do help many others.  However, they are also self-serving engagements.  There's nothing wrong with that, but its the simple truth.  Speaking in public is an ego and career boost for the speaker.  What I'm talking about is spending one on one time with another developer helping them solve a problem or helping them master a new technique.  There's no reward in that other than the self satisfaction of helping someone else.  That't the kind of programmer I want to work with.

Wednesday, February 8, 2012

The Great IDE vs Text Editor Debate: Why I Switched Sides

There are two types of programmers; those who prefer full featured IDE's and those who prefer a lightweight text editor.  I used to be firmly planted in the IDE camp happily opening CFBuilder, CFEclipse, or Aptana every morning to work on my ColdFusion, PHP, and Ruby projects.  Recently however, I have switched camps.  I now have SublimeText 2 and a Terminal open whenever I code and this post will try to explain why I made the switch.

In this corner, the IDE

Sears Mechanics Tool Kit
Let me start by defining what I believe an IDE is. To me an IDE is a prepackaged toolbox with many of the tools you'll need for a job.  Its a lot like the Mechanics Tool Tool Kit from Sears.  In it you get here all the tool necessary to complete the basic tasks a mechanic does.  Two things stand out here, what you don't get, and the fact that you have to lug around all these tools just to get to one single wrench.  Is that socket driver the highest quality tool you can buy at Sears?  Likely not.  Yes, CFBuilder has code insite and intellisence, however it was often a bit too slow and a bit too buggy for me, sometimes it worked, sometimes it didn't.  I never got the feeling that it was actually helping me code faster.  On the other hand knowing the names and types of arguments on my components is awesome and definitely something that I had to be willing to give up when making the switch to a text editor.  Guess what? I don't miss it one bit.

I also use SVN and GIT as my two primary means of source control.  While subclipse or subversive were nice, they rarely worked 100% of the time, especially when I made the switch to a Mac.  I had problems checking projects out where after going through the whole process of setting up the project eclipse would never bring any of the code from the repository so I'd have to start all over.  On my Mac it was a total crap shoot when I'd try to synchronize.  I also tried to use some of the SQL tools inside of Eclipse as well (I think I even blogged about the SQL Editor in CFBuilder once) but I never found them quite as useful as the external SQL tools that I regularly use.  Additionally I used the console view in my IDE quite a bit to write debugging output, this feature is nice, but is easily replaced by tailing a log in the terminal.

Lastly in order to support all of these areas of functionality an IDE needs to use lots of screen space.  When I'm coding I like to see two things: the folder structure of the project I'm working on and the code itself.  When I was using an IDE I found myself constantly readjusting the windows within my workspace.  Maximize the code, minimize the code, show the console, show the server, team synchronization view.  It was distracting to say the least.

Making the Switch


While I was happily coding in my many flavors of Eclipse I'd see many developers talking about Textmate, Notepad++, VIM, and EMACS.  I'd frequently half heart-idly try out E (textmate for windows) but I'd always go back to CFBuilder after a short time.  While I found that I liked the look and feel of these a bit better than Eclipse I failed to see what all the hype was all about.  The first "a-ha" moment I had was when I  was using E and typed in cffunction -> tab, then I pressed tab again.  OK, this is sort of nice, I can fill out a whole tag and cycle through all of its attributes by pressing tab.  This was nice but when I write functions I don't always use all the attributes.  The next step I took towards text editor bliss was to customize the snippits I used the most to match the way I wrote my code.  Shortly after I was writing code faster than I ever was before.  Little by little I started to use E more than CFBuilder and Aptana.

In this corner, SublimeText 2


Snap-On Torque Wrench
This brings us to the point where I installed SublimeText 2 on my machine and started playing with it.  This article on Nettus+ changed things forever.  One of the things I really liked in eclipse was using Ctrl-Click on a component definition in a file to be taken directly to that component in the editor.  I thought Ctrl-P was a lot like the "Open Resource" function in Eclipse, however, what I didn't know is that SublimeText will instantly preview a file in the editor as soon as it gets focus in the search result list.  SublimeText also remembers what files you recently worked on so those files come up first in the file list.  I was finding and opening files faster than ever.  Adding the power of Ctrl-R to quickly find a function in a file I can go to a specific function in a component faster than I can by doing a ctrl-click in eclipse.  SublimeText is the Snap-On Torque Wrench of code editors.  It does one thing and it does it extremely well.  

Additionally now that I wasn't using Eclipse for everything I had to find alternatives for the other things that Eclipse did for me like SVN, GIT, Ftp, and viewing log files.  For the most part the replacements I found have far outperformed what was available in Eclipse. For instance on my Mac Cornerstone has been a great replacement for the SVN integration in Eclipse.  I love the incoming/outgoing file count.  I have less conflicts now because I can see when files are waiting to come in and update more frequently.  There are situations where the eclipse plugin outperforms it, but those are far and few between.

Lastly are the intangibles that make SublimeText a pleasure to work with.  For the first time in my career I have found an editor I am passionate about.  An editor that, for me, makes coding more fun.  Its the little things that make such a big difference.  I love the animations when I close a tab or delete a file. I love the 30,000 foot view of all of my code in a file, I love how the contents of a folder smoothly slides down when I click on it.  I also love how easy it is to pull in a color file and have those colors work on all my code instead of having to import 15 different .col files like I did with eclipse.

Conclusion


In conclusion I'd like to say that no text editor or IDE will make every developer happy.  Each developer should use whatever makes them happy and productive.  In the mean time I'll continue to sing praises of Sublime to whomever will listen.  But who knows, when CFBuilder 3 comes out I'll probably switch to that for a bit simply because I love trying new things.

Tuesday, February 7, 2012

ColdFusion Koans Giveaway: Win a Copy of John Whish's ColdFusion ORM Book

With my work and school commitments I haven't been able to put as much time into the ColdFusion Koans project as I'd like to.  Instead of staying up another hour and working on it late at night I'm turning to you, the ColdFusion community to help me make the project better.  To make it worth your time I'm going to give away a digital copy of John Whish's excellent ColdFusion ORM book (http://www.coldfusionormbook.com/) to one lucky person.  If I get over 20 entries I'll give away TWO copies of the book.

There are three ways to be entered into the contest (if you complete both you'll get three entries).  The first way to enter is to download the Koans project, complete it, and post a link to a screenshot of all the tests passing into the comments of this post, make sure you subscribe to the comments so you know when I announce the winner.  The second way to enter is to add a new test or tests to the project and submit a pull request via github. The third is to write a blog post about the Koans project and post a link to the post in the comments here.

You can download the project here: https://github.com/bittersweetryan/ColdFusion-Koans.  If you'd like a quick intro to the Koans you can view a quick screencast I did here: http://blog.bittersweetryan.com/2011/11/screencast-getting-started-with.html.

I'll be drawing the winner March 1st.

Thursday, February 2, 2012

SublimeText 2 Now Has An Official ColdFusion Package Control Package

This has been making its way around twitter lately but I wanted to share that there is now an official Package Control Package for ColdFusion.  The project is hosted on GitHub https://github.com/SublimeText/ColdFusion so you can either download it from there, or since its an official package now it can be installed directly from PackageControl.   If you use SublimeText and not package control you are really missing out.  Read about it here: http://wbond.net/sublime_packages/package_control.   Installing this version over any of the TextMate bundle ports has a few advantages:

  • The package can now be managed through the "PackageControl" interface.  This means getting an update is as simple as going to Package Control -> Upgrade Package.  
  • Improved tag completion and suggestions.
  • CFScript support
  • The package is written in "Sublime Text" way meaning that some of the syntax and code completion features for ColdFusion are actually compiled into a python file wich should enhance performance. 
  • Brad has been excellent at pushing updates to the project and closing issues that come up.
If you are used to using the TextMate ports its important to note that the snippets are not stored in individual .tmSnippet files in this package.   If you like to customize your snippets you have to go into the ColdFusion.sublime-completions file and update the snippets there.   For instanceI like to remove all of the attributes that I rarely use from the cffunction tag.  If you'd like a quick reference on how the bundles work I have a screencast here: http://blog.bittersweetryan.com/2011/10/screencast-power-coldfusion-editing.html.  This was done using the TextMate port package so I was editing a .tmSnippet file, but the syntax is mostly the same in the .sublime-completions file.

If you like this package please let Brad know, he's on twitter as @atomi.

Monday, January 16, 2012

Using the New OrderedTestDecorator in MXUnit 2.1.1

One request that has come up frequently from users of the ColdFusion Koans was to have the ability to see the test results in order.  This weekend I created a new test decorator that will allow users to do just that, set the order of the test results via annotation.  Thinking it would be useful for others I opened a pull request on the MXUnit project and it was merged into the master branch on GitHub and added to the new 2.1.1 release.

In order to use the new decorator you must have MXUnit 2.1.1 or newer.  One way to check if you have the required decorator is to look in the mxunit/framework/decorators directory for the file OrderdTestDecorator.cfc.

In order to set the order of your tests two things have to happen.  The first is to add the custom decorator to you test component.

In a script based component the decorator is added like so:



In a tag based component you can add the decorator like this:



Once you have the annotation added to your test, you can start ordering them by adding the @order annotation to each test like so:

In a script based component the annotation looks like this:



In a tag based component it looks like this:



That's it, now your tests will run in the order you specified.

Friday, January 6, 2012

Use Oracle's FREE SQL Developer as a Microsoft SQL Server GUI on OSX

I'm on a Mac, my company uses a SQL Server, and since there is not native SQL Server Enterprise manager client I was forced to find a workaround. One common solution is to have aVirtual Machine running windows but to me that approach feels like using a sledgehammer to pound in a finishing nail.  Thanks to this post on stackoverflow I am able to use Oracle's FREE SQL Developer application to connect to Microsoft SQL Server Instances on my MacBook Pro running Lion.  I've used SQL Developer for Oracle development for a number of years now so the learning curve was pretty small for me but anybody who is familiar with SQL Server Enterprise Manager should be able to find their way around pretty easily, however there are a few things to be aware of which I'll discuss a bit later.


Installation


Before you can install SQL Developer you'll need to make sure that you have the JDK installed on your machine.  I have the Java for Mac Developer Preview installed on my machine from: https://developer.apple.com/downloads/.


Once the JDK is installed (you can check by opening a terminal and typing  javac -version ) the next step is to download and install SQL Developer from Oracle's website here.  Once SQL Developer is installed you'll need to get the jDTS plugin files from: http://sourceforge.net/projects/jtds/files/, at the time of this writing the most current version is 1.2.5.  Once the zip is download and extracted move the entire folder someplace where your account will have execute permissions on the jdsts-1.2.3.jar file.  I have a lib directory in my User folder where I keep all my third party .jar files.

You now have everything you need to get SQL Developer executing SQL queries, you just need to do some simple setup in SQL Developer.  Open SQL Developer and as of version 3.0 go to Tools -> Preferences  and expand the "Database" node.  Next click on Third Party JDBC Drivers click on "Add Entry...".  From this menu browse to the /jdts-1.2.5-dist folder you copied in the step above and select jdts-1.2.5.jar (or whichever version corresponds to the version you downloaded) and click "OK".

Configuration


SQL Server Connection Tab
Once you have the plugin installed exit out to the main SQL Developer IDE and add a new connection by either: clicking on File -> New -> Database Connection or by clicking on the green + icon in the "Connections" tab.   You should now see a "SQLServer" tab where you can enter the connection information for your SQL Server.


Using SQL Developer to Query Microsoft SQL Server Databases

Select Default Database
If you have not used SQL Developer before there are a few things to be aware of.  Since it is primarily an Oracle IDE you have to think in a somewhat "Oracle" way when running queries on your database. Since Oracle is a schema-centric database server you'll save yourself lots of typing if you set a default database for your current connection.   If you don't you'll have to type the fully qualified table name for each table you reference in a query (e.g. database.owner.tablename).  To do this right click on the database you'd like to use and click on "Select Default Database" in the context menu.  Once you do this you can do normal SELECT x FROM Table queries and leave out the fully qualified table name.  You'll have to do this each time you connect to SQL Server.   

SQL Developer will allow you to do many of the basic database tasks you can do in Enterprise Manager, however there are quite a few limitations. You can view your Table/View structure and data, you can also view most of the other objects in SQL Server like Stored Procedures and Functions.   SQL Developer will also allow you write DML (Data Manipulation Language) statements like Update, Delete, and Insert.   You can also write some DDL (Data Design Language) statements like ALTER TABLE.  However, the one huge shortcoming of SQL Developer is its inability to recognize the "BEGIN" keyword.  This means that any statement that uses BEGIN, like transactions, stored procedures, and functions will all generate a syntax error and not execute.

One nice "benefit" of using SQL Developer is the "Format" context menu.  When I'm writing code I often get SQL statements in debugging code, however, its usually one long string, debugging this code in Enterprise Manager usually meant having to manually update format the SQL, however in SQL Developer I can paste the code into the SQL Worksheet, right click, and click on "Format" and have a nicely formatted SQL Statement.  

Conclusion

While its not a complete replacement for Enterprise Manager I do find that SQL Developer will allow me to do many of the things I spend 90% of my time doing to my databases.  The best part is that this is a completely Free and somewhat mature solution.     

Wednesday, January 4, 2012

ColdFusion Quickie: Using the null attribute in cfqueryparam

In a database with foreign key constraints a "null" value is typically used to store a value that doesn't have a link to the referenced table. Lets look at a simple example:

In this example we have a contact table with a foreign key reference to the address table.  This means that every value in the addressId column must have a matching value in the addressId table.  There may be situations where a contact's address is not known so in order to satisfy the foreign key constraint the value "null" must be stored in the addressId field.  

Now lets look at the typical CFC's for these objects: 


Contact.cfc

/** * @accessors true */component Contact{ /** *@getters true *@setters true */ property numeric contactId; /** *@getters true *@setters true */ property String firstName; /** *@getters true *@setters true */ property String lastName; /** *@getters true *@setters true */ property address Address; public void function init(numeric contactId = 0,                                   String firstName = "",                                  String lastName = "",                                   Address address = new Address()) output=false hint="default constructor"{  variables.contactId = arguments.contactId;  variables.firstName = arguments.firstName;  variables.lastName = arguments.lastName;  variables.address = arguments.address; }}

Address.cfc

/*** @accessors true*/component{ /** *@getters true *@setters true */ property numeric addressId; /** *@getters true *@setters true */ property String line1;                //rest of implementation hidden public void function init(numeric addressId = 0,                                   String line1 = "",                                   String line2 = "",                                   String city = "") output=false hint=""{  variables.addressId = arguments.addressId;                ... }}

Most of this code is quite uninteresting, however, whats important to note is that the addressId field is instantiated to a value of 0 in the default constructor.   If we were to write our own persistance layer inserting this value into the database would throw a foreign key constraint error, since there is likely to be no matching Address record with an addressId of 0.

We all know by know that we should use cfqueryparam for all of our params.  As it turns out this function has an attribute called "null".  When the "null" attribute is set to true cfqueryparam ignores the "value" attribute and inserts a value into the database.  In our above example we would write our insert/update statements like so (assuming that the contactId field is auto-generated):

<cfquery name="insertQuery" datasource="#variables.datasource#">INSERT INTO    Contact(firstName           ,lastName           ,addressId)VALUES(      <cfqueryparam cfsqltype="cf_sql_varchar"                        value="#Contact.getFirstName#" />     ,<cfqueryparam cfsqltype="cf_sql_varchar"                        value="#Contact.getLastName#" />     ,<cfqueryparam cfsqltype="cf_sql_varchar"                        value="#Contact.getLastName#"                        null="#Contact.getAddressId() eq 0#" />)</cfquery>

Now if we insert a record with the default addressId value of 0 our database wont throw an error because ColdFusion will insert the value into the database, this is assuming that the column does allow the value of of course.