THE MYSTERY DESIGN PATTERN PG 7 ColdFusionJournal.com January 2007 Volume:9 Issue: 1 Create Using ColdFusion to a Search Images Based on Color - 16 Pseudo Dynamic ColdFusion: So Easy, Web Site with CF Even a Caveman Can Do It 5 2222 RRiicchh IInntteerrnneett AApppplliiccaattiioonnss:: AAJJAAXX,, FFllaasshh,, WWeebb 22..00 aanndd BBeeyyREooGISnTnER dTdODA..Y. .AN..D $AVE! www.AjaxWorldExpo.com Presorted 40 Standard US Postage PAID St. Croix Press SEE PAGE 29 THE ROOSEVELT HOTEL LOCATED AT MADISON & 45th SYS-CON Events is proud to announce the AjaxWorld East Conference 2007! The world-beating Conference program will provide developers and IT managers alike with comprehensive information and insight into the biggest paradigm shift in website design, development, and deployment since the invention of the World Wide Web itself a decade ago. The terms on everyone’s lips this year include “AJAX,” “Web 2.0” and BEING HELD MARCH 19 - 21, 2007! “Rich Internet Applications.” All of these themes play an integral role at We are interested in receiving original speaking proposals for this AjaxWorld. So, anyone involved with business-critical web applications event from i-Technology professionals. Speakers will be chosen that recognize the importance of the user experience needs to attend from the co-existing worlds of both commercial software and open this unique, timely conference – especially the web designers and source. Delegates will be interested in learning about a wide range developers building those experiences, and those who manage them. of RIA topics that can help them achieve business value. ©COPYRIGHT 2006 SYS-CON MEDIA. ALL RIGHTS RESERVED 17.125 in. 16.75 in. 16.25 in. 3 . 2 e® t i u S e v i t a e r C e® b o d A 11.0 in.10.75 in.10.25 in. Say hello to the next generation. It’s found in the world’s most inspirational places. It’s pushing the boundaries of art direction and design. Introducing Adobe® Creative Suite® 2.3. Today’s most talented designers and art directors are working smarter and faster because of it. Just ask the masterminds behind INTERspectacular—they rely on the Creative Suite to help bring their ideas into the world. See how they do it at adobe.com/creativemind. It’s everything but the idea. Better by Adobe.™ Luis Blanco and Michael Uman, INTERspectacular adobe.com/creativemind ©2006 Adobe Systems Incorporated. All rights reserved. Adobe, the Adobe logo, Creative Suite and Better by Adobe are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. 2 CFDJ JANUARY 2007 ColdFusionJournal.com 11.13.06 Client: ADOBE Creative Dir. Steve Simpson APPROVAL INITIALS DATE Job # ADBE-286 Art Director: Mark Sikes Creative Director Title: Interspectacular Copy Writer: Spencer Riviera Art Director INDESIGN CS 2 Copywriter Unit: SPREAD Print Prod.: Jenny Taich PRO. YEL PRO. MAG PRO. CYAN PRO. BLACK Proofreader DA: Rob Cribley Account Magr. 172650 GSP/Adobe 1 Bleed: 17.125 x 11.0 Act. Man / AAM.: Mike Barbeau / Amanda Sims Production Magr. A 11.13.06 bh Trim: 16.75 x 10.75 Pubs: Sys Con Cold Fusion Dev. Jrnl. Project Magr. Live: 16.25 x 10.25 Goodby, Silverstein & Partners. 2006 720 California St., SF, CA 415-392-0669 Client 17.125 in. 16.75 in. 16.25 in. 3 . 2 e® t i u S e v i t a e r C e® b o d A 11.0 in.10.75 in.10.25 in. Say hello to the next generation. It’s found in the world’s most inspirational places. It’s pushing the boundaries of art direction and design. Introducing Adobe® Creative Suite® 2.3. Today’s most talented designers and art directors are working smarter and faster because of it. Just ask the masterminds behind INTERspectacular—they rely on the Creative Suite to help bring their ideas into the world. See how they do it at adobe.com/creativemind. It’s everything but the idea. Better by Adobe.™ Luis Blanco and Michael Uman, INTERspectacular adobe.com/creativemind ©2006 Adobe Systems Incorporated. All rights reserved. Adobe, the Adobe logo, Creative Suite and Better by Adobe are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries. ColdFusionJournal.com CFDJ JANUARY 2007 3 11.13.06 Client: ADOBE Creative Dir. Steve Simpson APPROVAL INITIALS DATE Job # ADBE-286 Art Director: Mark Sikes Creative Director Title: Interspectacular Copy Writer: Spencer Riviera Art Director INDESIGN CS 2 Copywriter Unit: SPREAD Print Prod.: Jenny Taich PRO. YEL PRO. MAG PRO. CYAN PRO. BLACK Proofreader DA: Rob Cribley Account Magr. 172650 GSP/Adobe 1 Bleed: 17.125 x 11.0 Act. Man / AAM.: Mike Barbeau / Amanda Sims Production Magr. A 11.13.06 bh Trim: 16.75 x 10.75 Pubs: Sys Con Cold Fusion Dev. Jrnl. Project Magr. Live: 16.25 x 10.25 Goodby, Silverstein & Partners. 2006 720 California St., SF, CA 415-392-0669 Client 4 CFDJ JANUARY 2007 ColdFusionJournal.com editorial editorial advisory board Jeremy Allaire, founder emeritus, macromedia, inc. ColdFusion: So Easy, Even Charlie Arehart, CTO, new atlanta communications Michael Dinowitz, house of fusion, fusion authority Steve Drucker, CEO, fig leaf software Ben Forta, products, macromedia Hal Helms, training, team macromedia Kevin Lynch, chief software architect, macromedia a Caveman Can Do It Karl Moss, principal software developer, macromedia Michael Smith, president, teratech Bruce Van Horn, president, netsite dynamics, LLC editorial W hile focusing on speaking directly with business editor-in-chief Simon Horwith [email protected] owners and important decision makers in re- large businesses that, in reality, are the folks executive editor who can really make ColdFusion a quantifi- Nancy Valentine [email protected] cently able success. Speaking with these business- decision makers and advising them on techni- research editor Bahadir Karuv, PhD [email protected] channel surfing, one of cal and architectural issues has influenced my perception of how ColdFusion fits into the “Geico caveman” the larger IT picture, and it has shaped how I production By Simon Horwith choose to respond to these questions. lead designer commercials came on I’ll begin with the fundamental question as Abraham Addo [email protected] to whether or not there is such a thing as a art director the tube to remind me that Geico.com is so programming language that is too easy. It’s Alex Botero [email protected] not such an easy question to answer. Devel- associate art directors easy to use, even a caveman can do it. oping software is largely all about solving Louis F. Cuffari [email protected] problems – and I for one will take all the help Tami Beatty [email protected] The marketing campaign is very clever; I can. CFML and the features built in to the watching it, I couldn’t help thinking what a ColdFusion Application Server don’t elimi- editorial offices shame it was that Allaire didn’t think of the nate every problem I face as a developer, but slogan first. After all, ease of use certainly is they do make many otherwise difficult tasks SYS-CON MEDIA one of ColdFusion’s greatest strengths. That trivial. Wanting development to be easier is 577 Chestnut Ridge Rd., Woodcliff Lake, NJ 07677 Telephone: 201 802-3000 Fax: 201 782-9638 night I couldn’t stop thinking about the cave- something that programmers in all develop- COLDFUSION DEVELOPER’S JOURNAL (ISSN #1523-9101) man commercial and how applicable it is ment environments strive for. Any Java or is published monthly (12 times a year) by SYS-CON Publications, Inc. to CF. Questions kept entering my mind like .NET developer who tells you they don’t want spam forcing its way into my inbox. Is being their jobs to be any easier than they already postmaster: send address changes to: COLDFUSION DEVELOPER’S JOURNAL very easy to learn and use a good thing for are is either lying or ignorant. Java frameworks SYS-CON MEDIA a programming language? Does being easy like JUnit, Aspect-J, and Struts to name a few 577 Chestnut Ridge Rd., Woodcliff Lake, NJ 07677 make ColdFusion a less viable business solu- were all developed to make developers’ lives tion? Are ColdFusion developers illegitimate easier. .NET developers don’t use Visual Studio in the programming world? It is no secret that because it looks pretty – they use it because ©copyright Java, .NET, and other developers sometimes it rapidly speeds up development. There are Copyright © 2007 by SYS-CON Publications, Inc. All rights reserved. No part of this publication may look down on ColdFusion and ColdFusion thousands of other examples of frameworks, be reproduced or transmitted in any form or by any means, developers. Is it a simple case of ignorance? IDEs, APIs, and other tools that developers electronic or mechanical, including photocopy or any information, storage and retrieval system, ...or jealousy? ...or is this perception justified? use to make their jobs and their lives easier. without written permission. I’ll preempt addressing these questions with Be happy to admit that you use ColdFusion a statement that makes my own perspective because it makes your life easier. and interests clear. Like many other develop- Worldwide Newsstand Distribution – CONTINUED ON PAGE 34 ers, I do what I do because of a real love for my Curtis Circulation Company, New Milford, NJ FOR LIST RENTAL INFORMATION: trade. Like all other developers, I also do what Kevin Collopy: 845 731-2684, [email protected] I do for profit, i.e., to make money. For a very About the Author Frank Cipolla: 845 731-3832, [email protected] long time I’ve been an extremely active mem- Simon Horwith is the editor-in-chief of Cold- For promotional reprints, contact reprint ber of the ColdFusion development commu- Fusion Developer’s Journal and is the CIO coordinator Megan Mussa, [email protected]. SYS-CON Publications, Inc., reserves the right to nity – I enjoy being active in the CF commu- at AboutWeb, LLC, a Washington, DC based revise, republish and authorize its readers to use nity and I love working with ColdFusion. For company specializing in staff augmentation, the articles submitted for publication. All brand and product names used on these pages the past five or six months, however, I’ve been consulting, and training. Simon is a Macro- are trade names, service marks, or trademarks pretty quiet. The reason for this is that rather media Certified Master Instructor and is a of their respective companies. than focusing on engagements where I largely member of Team Macromedia. end up “preaching to the choir,” I’ve been [email protected] CFDJ JANUARY 2007 5 6 CFDJ JANUARY 2007 ColdFusionJournal.com cf 101 founder & ceo Fuat Kircaali [email protected] group publisher Jeremy Geelan [email protected] Data Access Objects advertising The mystery design pattern senior vp, sales & marketing Carmen Gonzalez [email protected] vp, sales & marketing Miles Silverman [email protected] I t seems that their business model. Design patterns in the advertising sales director Megan Mussa [email protected] model are a way to structure code in such a there’s a lot of way that allows the most flexibility long-term. advertising sales manager Andrew Peralta [email protected] Software applications spend most of their life associate sales manager talk in the Cold- in a maintenance change as I’m sure you’ve Corinna Melcon [email protected] already experienced. Lauren Orsi [email protected] Fusion community Design patterns aren’t limited to your business model, though. Model-View-Con- about data access ob- troller is a design pattern many CF developers sys-con events By Jeffry Houser are familiar with that’s not related to how to jects and data gateway structure your model; it’s designed to help president, events Carmen Gonzalez [email protected] separate your model from your view code. design patterns. Everyone talks about how Yahoo released a series of design patterns that events manager Lauren Orsi [email protected] are related to the user interface. You can read great they are and why everyone should be about them at http://developer.yahoo.com/ ypatterns/index.php. When you implement using these patterns. DAOs or gateway objects you’ll be doing so in customer relations your model. circulation service coordinator Unfortunately, there seems to be little Edna Earle Russell [email protected] talk about what exactly they are and how What Is a Data Access Object? you would implement them in a ColdFusion Data Access Objects are a design pat- application. At one point I did a lot of search- tern that lets you separate your data access ing for resources on these two patterns and from any business logic. This lets you easily sys-con.com came up with nothing. These patterns aren’t change your data storage mechanism with vp, information systems discussed in the famous “Gang of Four” book, minimal code changes. Perhaps you want to Robert Diamond [email protected] nor are they covered in Head First Design Pat- move from a MySQL database to a SQL Server web designers Stephen Kilmurray [email protected] terns. A Web search also came up empty. So database. Or perhaps you’re ditching local Richard Walter [email protected] where does one go to learn? Hopefully I can data storage in favor of using a Web Service shed some light on these patterns. It was only mechanism? Maybe you want to move some after talking to different people about them data out of the database and into XML files? that I started to understand their purpose and Or perhaps you’ll want to move them out of accounting how you could implement them. In this ar- XML files into a database. If your application financial analyst ticle I’ll explore the Data Access Object (DAO) is implemented using DAOs then you’ll just Joan LaRose [email protected] in detail. Next month I’ll examine the gateway have to write a new DAO objects for the new accounts payable Betty White [email protected] pattern. data mechanism and then tell your applica- tion to use the new one instead of the old one. What Is a Design Pattern? In most cases, a DAO will have four A design pattern is just another name for methods in it, one for inserting data, one for subscriptions a best practice. There are usually certain trad- updating data, one for selecting data, and [email protected] eoffs you make for choosing one approach one for deleting data. Your business model Call 1-888-303-5282 over another. I recommend you try to learn as components will access the DAO objects as many patterns as you can, and then you’ll be needed to maintain the data properly. This For subscriptions and requests for bulk orders, please send your letters to Subscription Department in a better position to decide what will work probably sounds harder than it is, so let me Cover Price: $8.99/issue best for your current situation. demonstrate with an example. Domestic: $89.99/yr (12 issues) Canada/Mexico: $99.99/yr When talking about design patterns, most All other countries $129.99/yr ColdFusion developers are usually talking MyFriends RSSCategory Component (U.S. Banks or Money Orders) Back issues: $12 U.S. $15 all others about ways to structure the code that makes To illustrate a DAO object, I want to take a CFDJ JANUARY 2007 7 TABLE OF CONTENTS editorial Using ColdFusion to Search Images Based on ColdFusion: So Easy, Even a Color Caveman Can Do It 5 By Simon Horwith Seth Duffey…16 cf 101 Data Access Objects 7 By Jeffry Houser AJAX Spry for ColdFusion Developers 14 AJAX made simple By Andrew Powell Create a Pseudo-Dynamic Web Site with CF By Michael H. Markowski…22 cfugs 30 ColdFusion User Groups techniques Poor Man’s HTTP Compression with Cold Fusion Speed up your Website and 32 lower bandwidth utilization By Sami Hoda 8 CFDJ JANUARY 2007 ColdFusionJournal.com cf 101 look at the RSSCategory.cfc from the MyFriends RSS aggregator. as part of the pseudo constructor code: You can download the aggregator code from the software pod on my Web site at www.jeffryhouser.com. RSS feeds that are entered variables.instance.DAO = “”; into the system can be categorized. This component is used for creating or updating one of those categories. It was originally The modified init method is shown in Listing 4. It adds a third built in the interest of speed without much thought to database argument, which is the type of DAO you want to use. Most likely portability. this will be a global setting somewhere in your app. So I don’t The RSSCategory component has two properties, a Catego- have to change any already-written code, I made this argument ryID and a Category. It has two methods, an init method and a optional and added a default value, which refers to the Data commit method. The init method contains a select statement. Access Object I just created. First I define a local query variable. The commit method contains an update statement and an insert Then the code creates an instance of the DAO object. In the old statement. If we change our data storage mechanism, all the SQL version of the component, the query was located next. Here we statements would have to be changed inside the component. call the select method and assign the results to the query variable. This could, potentially, mean changing every component in our The remainder of the method sets the instance variables based on Model. This is about as close to a full rewrite as you can get. The the query data. intent in creating a DAO is to move the SQL statements outside of The modified commit method is shown in Listing 5. The com- the main component and into a separate component. That way, mit method remains largely unchanged. The method signature is you only have to change the DAO, leaving the rest of your app the same. There is one argument for the data source. A local query untouched. variable is defined. If the primary key is an empty string then the new primary key is created and the insert method executed. Writing the Data Access Object Otherwise, the update method is run. The Data Access Object won’t have any properties, just the methods for selecting, inserting, updating, and deleting. (For the Why Use a Data Access Object? sake of brevity, I won’t provide the delete method.). A CFC without With the example behind you, you might ask yourself why any local properties is like a function library, and that is exactly would you care about DAOs? I can honestly say that I rarely use what we’re using it for. them. Most of my applications are custom built for clients. How Listing 1 shows the select method. The method name is select often do companies change their database? Yes, it happens, but and it returns a query. It accepts two arguments, the CategoryID it’s rare. In my early days I converted a lot of Microsoft Access and the datasource name. The CategoryID is the primary key for databases to SQL Server, but it’s rare to find an Access-built app. the category you want to retrieve. The query name is defined as a It’d be even rarer to see an Access-built Web app that uses DAOs local variable then the select query is run. I chose RSSCategory.cfc or any advanced design concepts. because of the simplicity of the queries. The resultant query, even DAOs really start being a benefit if you’re going to build an if no data is returned, is passed out of the function. Easy as pie. application that will be deployed in multiple environments and Listing 2 shows the insert method. This method is named in- those environments are unknown. Perhaps you’re building a killer sert, but returns void. It accepts three arguments, the CategoryID, CMS? Or free blogging software? If so then you’re going to want the Category, and the datasource. This is different than the select to use DAOs in your development. You don’t know if the next method, which only needs the primary key. Since we’re creating a deployment will be on SQL Server, Oracle, or even XML files. new category from scratch, we need all the associated data for the query. The query variable is defined as a local variable on the next Final Thoughts line. Then comes the query. In the case of the MyFriends project, You should now have an understanding of what DAOs are UUIDs are used as primary keys so they’ll be created outside of and how to use them in your ColdFusion applications. I wish I the component and passed in. If you were using other methods could give you a list of resources to learn about gateways, but my for primary key creation, such as an auto-incrementing integer, research has always come up empty. I can think of many alternate then you may not want to pass that value into the method. You implementations of this pattern that could achieve the same af- may want to get it from the database after the insert and return fect. I’d love to hear how you implement DAOs. Let me know! it out of the method. These decisions are application-specific decisions, though, not data storage-specific. The update method, shown in Listing 3 is identical in form to the insert method and I About the Author don’t have anything else to add about the code. Jeffry Houser has been working with computers for over 20 years and in Web development for over 8 years. He owns a consulting Modifying the RSSCategory Component company and has authored three separate books on ColdFusion, With the Data Access Object created, the next step is to modify most recently ColdFusion MX: The Complete Reference (McGraw- the RSSCategory component to use the methods in the DAO Hill Osborne Media). instead of directly executing SQL. First, we want to create an instance variable to contain the DAO object. We can add this line [email protected] ColdFusionJournal.com CFDJ JANUARY 2007 9 cf 101 Listing 1 The select method Listing 4 The RSSCategory init method <cffunction name=”Select” access=”public” returntype=”Query”> <cffunction name=”Init” access=”public” returntype=”Boolean”> <cfargument name=”CategoryID” type=”string” required=”true”> <cfargument name=”CategoryID” type=”string” required=”true”> <cfargument name=”dsn” type=”string” required=”true”> <cfargument name=”dsn” type=”string” required=”true”> <cfargument name=”DAOType” type=”String” required=”false” <cfset var qGetCat = “”> default=”RSSCategory_DAO_SQLServer”> <cfquery name=”qGetCat” datasource=”#arguments.dsn#”> <cfset var qGetCat = “”> select * from RSSCategories <cfset variables.instance.DAO = createobject(‘component’, ‘#arguments. where RSSCategories.CategoryID = DAOType#’)> <cfqueryparam value=”#arguments.CategoryID#” cfsqltype=”cf_sql_var- char”> <cfset qGetCat = variables.instance.DAO.select(arguments.CategoryID , </cfquery> arguments.dsn)> <cfreturn qGetCat> </cffunction> <cfif qGetCat.recordcount is 0> Listing 2 The insert method <cfreturn false> </cfif> <cffunction name=”Insert” access=”public” returntype=”Void”> <cfargument name=”CategoryID” type=”string” required=”true”> <cfscript> <cfargument name=”Category” type=”string” required=”true”> variables.instance.CategoryID = qGetCat.CategoryID; <cfargument name=”dsn” type=”string” required=”true”> variables.instance.Category = qGetCat.Category; </cfscript> <cfset var qUpdateCat = “”> <cfreturn true> <cfquery name=”qUpdateCat” datasource=”#arguments.dsn#”> insert into RSSCategories(CategoryID, Category) </cffunction> values ( <cfqueryparam value=”#arguments.CategoryID#” cfsqltype=”cf_sql_var- char”>, Listing 5 The RSSCategory commit method <cfqueryparam value=”#arguments.Category#” cfsqltype=”cf_sql_var- <cffunction name=”Commit” access=”public” returntype=”void”> char”> ) <cfargument name=”dsn” type=”string” required=”true”> </cfquery> <cfset var qUpdateCat = “”> </cffunction> <cfif variables.instance.CategoryID is “”> Listing 3 The update method <cfset variables.instance.CategoryID = createuuid()> <cffunction name=”Update” access=”public” returntype=”void”> <cfset variables.instance.DAO.insert(variables.instance.CategoryID, <cfargument name=”CategoryID” type=”string” required=”true”> vari- <cfargument name=”Category” type=”string” required=”true”> ables.instance.Category, <cfargument name=”dsn” type=”string” required=”true”> argu- ments.dsn)> <cfset var qUpdateCat = “”> <cfelse> <cfquery name=”qUpdateCat” datasource=”#arguments.dsn#”> <cfset variables.instance.DAO.update(variables.instance.CategoryID, update RSSCategories vari- set Category = ables.instance.Category, <cfqueryparam value=”#arguments.Category#” cfsqltype=”cf_sql_ argu- varchar”> ments.dsn)> where CategoryID = </cfif> <cfqueryparam value=”#arguments.CategoryID#” cfsqltype=”cf_ sql_varchar”> </cffunction> </cfquery> Download the Code... Go to http://coldfusion.sys-con.com </cffunction> 10 CFDJ JANUARY 2007 ColdFusionJournal.com