Wednesday, February 9, 2011

Using Metadata To Add Static Variables to ColdFusion Components

Let me start out by saying that everything in this this post I learned from Elliot Sprehn's fantastic CFMeetup presentation "I bet you didn't know you could do that with ColdFusion".  If you haven't already seen this presentation, you should.  Even if you have seen it you should watch it again, and show it to anyone you know who loves to bash ColdFusion.   Anyways, I wanted to play around with this concept on my own to see how I could get it to work for me.  

First, if you are unfamiliar with the concept of metadata in ColdFusion read "Using introspection to get  metadata for components" at adobe.com on for some background.  Also should check out the getMetaData and getComponentMetaData functions over at CFQuickDocs.  The most important thing to know for this post is that these functions return a structure that describes an object.  These properties are generated the first time an object is instantiated and will persists until the object is recompiled by the ColdFusion server.

So what exactly am I talking about when it comes to adding static variables to ColdFusion components?  Well if anybody has worked with a strongly typed language such as .NET or Java you'll be familiar with the static keyword.  Static variables are variables that are variables that exist in only one place and are accessible without having to instantiate a instance of a object.  Basically you can access a property on an object by calling ObjectName.staticVar without having to create a new ObjectName().

Lets take a look at a bare bones component called Employee:

<cfscript>
component name="Employee"
{
 public Employee function Init(){
  var metadata = getComponentMetaData("Employee"); 
  
  if(!structKeyExists(metadata,"myStaticVar")){
   
   lock name="metadata.myStaticVar" timeout="10"{
    metadata.myStaticVar = "Hello Static Variable."; 
   }
  }
  
  return this;
 }
}

As you can see when this component's Init() method is called I get the components metadata and look for a key called "myStaticVar" and if it doesn't exist I create it.  Note: it's important to lock the creation of this key since you are manipulating a shared scope.  Its important to note here that until this component is compiled by ColdFusion this key does not exist.  Dumping the output of getComponentMetaData("Employee")at this point will produce the following output:






















As you can see there is no key for "myStatcVar" which was defined in the init() method of the component.   So let's create an instance of the component and dump its metadata.

<cfscript>
Employee = new Employee();
writeDump(getComponentMetaData("Employee");
</cfscript>
 






















Now you can see that my  the component metadata structure has a key "MYSTATICVAR".  The real beauty of this is that this metadata persists server wide for this component until it is recompiled by the ColdFusion server.   I tested this by creating  a new directory with a new application.cfc and with a new application name and dumped the metadata on the Employee component as shown below:

<cfscript>
writeDump(getComponentMetaData("Employee");
</cfscript>

Sure enough, the MYSTATICVAR key was there.  I even created a completely new website and mapped the component directory to the directory that holds my Employee component and ran the code above again and the metadata was there.

Now anytime I want to access the value of my static variable all I have to do is write code like this to retrieve the value of the static variable:

<cfscript>
 staticVariableValue = getComponentMetaData("Employee").myStaticVar;
 
 writedump(staticVariableValue);
</cfscript>

It's important to note that when the server is restarted this metadata will once again disappear until the component is created for the first time.

Monday, January 31, 2011

Getting the Generated Key From A Query in ColdFusion (Including Script Based Queries)

Are you are still writing things like SELECT SCOPE_IDENTITY()  or LAST_INSERT_ID() in your ColdFusion Queries?  One of the more powerful and perhaps lesser known features of the cfquery tag is the ability to return the generated ID from an insert statement.

Prior to ColdFusion 9 the value returned in the query struct would change depending on the type of database the value was being inserted into (see cfquickdocs for more information).   For Instance Oracle would return a key called RowID  and SQL Server would return a key called identitycol in the result structure of a query (provided you supplied a result argument in the query itself).

<cfquery name="insertMe" datasource="mysql_db" result="queryResult">
 INSERT INTO
   Contact(firstname, lastname) 
 VALUES('ryan','anklam');
</cfquery>

In ColdFusion 9 Adobe simplified this by always returning a value called generatedkey in the result structure as shown below:



 






Things get a bit more interesting when leveraging ColdFusion's new script based queries.  Lets use the following code as an example:

<cfscript>
 insertQuery = new query();
 
 insertQuery.SetDatasource("facets_sql");
 
 insertQuery.SetSql("insert into contact(firstname, lastname) values('ryan','anklam')");
 
 result = insertQuery.Execute();
</cfscript>

One might expect that generated key would be a property that could be accessed through the result variable.  However, looking at the dump of the result variable we can see that ColdFusion actually wraps all the result goodness in a property called prefix:














So, in order to get the generated key from a script based query the following code is required:

<cfscript>
theKey = result.getPrefix().generatedkey;
</cfscript>

Wednesday, January 26, 2011

The Books / Classes I Wish to complete in 2011

Since I've purchased my nook color last year I've been addicted to reading tech-ebooks and with that has come the motivitation to learn everything that I can, including webinars and online classes. 

Tuesday, January 25, 2011

Book Review: Sitepoint's Simply JavaScript by Kevin Yank & Cameron Adams

My life has finally slowed down over the last few weeks which has allowed me to start to tackle my huge list of books to read.  The first book I decided to read was SitePoint's Simply JavaScript written by Kevin Yank and Cameron Adams.  This was also the first book I read on my new Nook Color (I previously had a e-paper Nook) and I have to say that I waas very impressed with the quality of SitePoint's ePub format.  The code was fairly easy to read in within the constraints of the ePub format and the illustrations generally looked really good.   The splashes of color were also a nice touch when reading, its amazing much a subtle detail like a blue line can make your reading experience a little more enjoyable.  

So why did I choose this book to read first from the list of about 15 books I want to read?  I've been a software developer for over 10 years but I never really learned the basics of JavaScript.  I've spent a good part of  my career behind a firewall where I only had to target my company's standard browser so I was always able to hack away a solution that worked.  Once I moved on to a company that had more public facing sites I picked up jQuery and pretty much learned how to write jQuery code and not worry too much about the JavaScript behind what I was writing.  This always somewhat bothered me and when Site Point (http://www.sitepoint.com) offered this book as one of their 25 days of Christmas deals this year I jumped on it.

I immediately felt comfortable with the way the authors spoke to me in this book.  Some technical books are so dry they could suck the mositure out of the desert air, however this book has a plesent delivery that made reading it that much more easy.  Another caviat I have about a lot of technical books is that they typically spend too much time delving into a topic and bore me into glazing over the pages and not really absorbing what the author is trying to convey.  Kevin and Cameron do a great job of pacing the concepts they cover in this book.

The first chapter is all about one of the fundamential building blocks of JavaScript in the browser: the DOM.  They start by explaining the concepts of the DOM and some of its idiosyncrasies. A good example of this is their explanation of how whitespace can actually create new text nodes in the DOM structure. The next chapter dives into the event model, and goes quite in-depth about all of the cross browser issues that developers used to complain about before frameworks became popular and took care of most of these issues automatically.  After events are covered the authors then delve into the world of animation, another thing that the popular libraries do a great job of abstracting out for modern JavaScript developers.  This book did a very good job of explaining a lot of the details qne techniques behind animation, again providing some very good examples along the way.  After animation is covered the authors build upon the lessons learned in previous chapters and introduce the conepts of form enhancement using JavaScript.   In this chapter the authors will walk the reader through creating some common form enhancements, which after you'll begin to really appreciate how much work goes into plugin development for your favorite JS library.  Next the authors walk you through the black art of debugging JavaScript code and finish up with a brief introduction to Ajax.

What I really liked about this book is that the sample code in this book is easy to follow and really helps strengthen the concepts that are discussed throughout. The code builds upon the concpepts that are introduced throughout the book and by the end you feel very comfortable using the techniques described througout.   Kevin and Cameron also do a great job of breaking down the code after it is presented and give an in-depth description important steps throughout the code.  Other important JavaScript concepts are sprinkled throughout text as well, for example closures and object literal syntax are both covered  in this book.  In addition basics like variable scoping, array creation, looping concepts and conditional statments are also introduced and explained in this book.  One of the biggest compliments I can give this book is that after reading it I actually understood the concept of closures, something I had been trying to grasp for sometime.

Since this book is aimed at a beginner to JavaScript I feel like it could have done a better job of explaining some of the built in functions of the JavaScript language and perhaps touched some more on a few of the shorthand methods that one will see in many scripts such as ternary operators.  

I'd definately reccomend this book to anyone that wants to learn a little bit more about JavaScript and whats behind the magic of some of today's popular JavaScript frameworks.  An advanced JavaScript developer will probabaly find this book a boring, but thats not the intended audience for this book anyway.

Thursday, October 21, 2010

Presentation Materials From my CFMeetup Presentation on TDD & Katas

As promised, here are my slides and code from today's presentation.

The slides can be found at: http://slidesix.com/view/TDD-Demystified

The code is at: http://github.com/bittersweetryan/Katas

Thanks for visiting!
Fork me on GitHub