Notes: Using Structures With CFCs

By Selene Bainum (WebTricks.com).

Structure refresher: They are complex data types that can help you provide a logical grouping of data. They can also be called associative arrays and are made up of key/value pairs. Server, Application, Session, Request, URL scopes are all examples of structures.

CFC refresher: Contain data and functions. Zero or many arguments may be passed to the functions, but only zero or ONE values can be returns. And the values in and out of CFCs can be typed (any, array, binary, boolean, date, numeric, query, string, struct, UUID, Variablename, Void, XML).

Recall that you can call functions with the cfinvoke tag (passing in arguments with cfinvokeargument or with the argumentcollection attribute). Via script, you can use CreateObject() to instantiate the component, and then call the function. Not necessarily more efficient, but it looks cleaner, easier to read.

Why use structures with the CFC functions? Less arguments to declare in the function and the function calls. New elements can be added to the structure without having to change the function declaration or calls. However, doing this subverts the argument typing validation and security. You can’t type the individual keys of the elements in the struct. So using cfqueryparam is even more important in this scenario. And there is no introspective documentation of the CFC. Available arguments must be manually documented with comments in the code if you want. Very nice!

She didn’t discuss any way to do more detailed filtering and encapsulate that in the struct data, for instance, “is equal to”, “is not equal to”, “is greater than”, “is less than”, etc. Her example pretty much did an “is equal to” match, or at least a “contains” type of search.

Nevertheless, this is a great idea, and perfect for the example of submitting search criteria into a search function.

The arguments scope is already a structure. Each cfargument tag just defines a key of the structure. So passing the argumentsCollection attribute allows you to send all the arguments at once.

Structs for Form Population/Submission

When preparing to display an add/edit form, can populate a struct that contains all the data in the form. Can write some pretty flexible code to do this based on the queries you pass your code. Just loop through the query fields and assign the elements correspondingly in the struct. Joined tables that may have a one-to-many relationship can be structs within the main struct. Each element can be named as the ID of the joined table records, and then that element contains a struct mimicking the joined table query, in the same manner as the main table.

BUT NOTE: When you submit the form, you cannot maintain this nested struct methodology. So, Selene tacks on an “_n” at the end of the field names, where n is the key of the record for the one-to-many records. For instance, phone_1, phone_2, etc. The code that retrieves the form fields can then rebuild these fields back into the struct structure as it was originally.

Structs for Search Criteria

Use a search struct for submitting search criteria to a search function. Various fieldnames will correspond to the files in the table to filter against. Search function can know which ones to use based on the struct. Naturally, the alternative is a nasty list that you have to parse, or a huge list of arguments. Struct approach is much cleaner to implement.

Conclusion

Course material is posted at Selene’s Presentation Download page.

CFUnited Keynote

The CFUnited 2007 keynote was started by Michael Smith, followed by TIm Buntel and Ben Forta.

ColdFusion 8: 8 Reasons You Want It Now!

1. Making applications is even easier. Now comes with Eclipse plugins and wizards, and a server monitor. So this goes beyond the power of the language; now the server itself makes it easier to do development. For instance, there is now step debugging. This all works well with CFEclipse. Also will work well in Flex Builder. The server monitor is useful too; it isn’t just for admins. Developers can use the server monitor to see what pages or queries are running slowly to diagnose your app before you even deploy it.

2. Have confidence in production applications. Server monitor and API are accessible, you can develop some of your own monitoring or administrative functionality. ColdFusion 8 is very backward-compatible. Can upgrade with confidence.

3. It runs in more places. Can run on Mac OS X (Intel), VMWare and Microsoft Virtual Server, 64-bit Solaris, JBoss. Regarding virtualization: It may seem unnecessary for it to support that, but it has been optimized to support the virtualization environment.

4. Your users will be happier. Much better support for Flex and AJAX. This allows us to build much more powerful and more intuitive interfaces and applications for our customers. Reporting and PDF applications, on-demand presentations, image support. These are NOT wrappers around Java classes that do image manipulation; the image tags are using Adobe’s own technology.

5. It’s nice and secure. Multiple Admin accounts. So you can set up multiple accounts (for either ColdFusion Administrator or RDS) that have only the access you have set up. Sandboxes can also be bound to particular user accounts. Dreamweaver and even Eclipse with the new plugins will benefit from this security because they use RDS. Stronger encryption is now in place, for free.

6. CFML Evolution. JavaScript operators! No more “GTE” as an operator! Argument collections, which makes conditional arguments, i.e. for CFMail, much easier to do. CFC interfaces. Many added file handling functions that are more efficient. No more tricks and games to manipulate/read large files without bogging down your server. For instance, line-by-line reading. Array and structure creation. CFC serialization. So the language is just continuing to evolve and be more powerful.

7. Plays well with others. ColdFusion has always played well with others in some ways, but maybe not the .NET world so much. Now plays well with .NET, Exchange Server. Added support for RSS/ATOM. Data synchronization and improved Flash Media Server support. So ColdFusion can be effective as a back-end technology that can connect various disparate systems. ColdFusion isn’t just about webpages anymore. ColdFusion can act as a hub between numerous back-end and numerous front-end systems.

8. It’s fast! Really, really fast! Overall server performance. Without making any changes to your code, your application will experience improved speed! The Adobe team analyzed customer code and reviewed the bottlenecks. Made many changes to tag code to improve performance.

For instance, structure manipulate code has DOUBLED in speed. List manipulation and CFSWITCH/CFCASE have TRIPLED in speed. CFParam has basically gone 30 times faster. Date functions are 5-6 times faster. RegEx functions are over twice as fast. IsDefined() is 50% faster. CFC creation (which is known to be exceptionally slow) is around 10-30 times faster (depending on if you compare CFMX6 or CFMX7). Real-world comparison: BlogCFC performance improved by about 40% (255 to 355).

It is very evident from these numbers, then, that ColdFusion 8 is worth the upgrade. Will make your existing apps much, much faster. And we haven’t even touched on stuff like CFThread and how your apps can benefit from that. Also consider how this will save your organization money. Apps are slow and need to upgrade to faster server? Upgrading to ColdFusion 8 may even be more cost-effective!

The release date of ColdFusion 8: Soon. :-) They wouldn’t tell us, but that’s okay.

Flex, Today and Tomorrow

There are apps out there today that we can look at to see the power of Flex. There is a word processor out there, race tracker, Adobe-specific apps (around 15 projects). The ColdFusion monitor in CF8 is in Flex.

Of course, it sits on top of the Flash Player. Expect 90% saturation of Flash Player 9 by the end of the year.

Flex is now open source. Public bug database and roadmap. The open source project will be fully up and running by the end of 2007. Once it is free and open source, makes it difficult to argue implementing it in your company. Low barrier of entry.

Public betas of Flex 3 are available now. Expected that final release of Flex 3 SDK and AIR 1.0 final releases will be available on or around MAX 2007 and the start of 2008.

Why Flex 3?

1. Improvements for designers and developers working together.

2. Hybrid desktop/internet applications with AIR. Cross-OS application engine. Online/offline functionality. Makes it easy for a customer to stay connected to what is going on in their server app without having to create a webpage that they have to browse to. Special AIR-enabled features in Flex.

3. Working with data with advanced DataGrid and charting improvements. New list and data effects. Flex Builder has web services introspection to make it easier to get your app running.

4. Platform evolution. Improved caching of Flex libraries. This will make load-time of applications significantly faster, potentially. Also has improved JavaScript/Ajax wrappers. So the HTML and Flex components of your applications can speak to each other more easily. Flex Builder has improved compiler performance.

MiniMAX SE7EN Notes

These are my notes from the MiniMAX SE7EN conference.

ActionScript 3 for Dummies

ActionScript used to be much simpler. Went from assigning AS to an element, to assigning it to the keyframe, where you would assign a function to an event of an element, to now creating an event listener. Following the same route as JavaScript. Nice. Events are made to be more like JavaScript as well.

New Adobe CS3 Photoshop Feature: Stacks

Can autoalign layers from multiple photos, and then remove unwanted people, i.e. in a scenic shot, with very little technical skill required! Open your files, execute script “Open files into stack”. Even an option to attempt to automatically align images. “Set stack median”, and it will automatically remove anything that exists in one photo but not in the others.

Using Spry

AJAX framework by Adobe. Easy to use. Can provide UI widgets, visual effects, XPath filtering, load and display data dynamically with minimal work.

After including the required JavaScript files, you can pull in data with on line of JavaScript. Then, just define Spry regions in your HTML. That table will then automatically listen to that datasource as it changes. The way you bind data to HTML elements is also very similar to FLEX.

Sorting? A single method call. Marking a column has a certain data type? A single method. Everything is quick.

Example: Demonstrated an AJAX call to XML with one line of JavaScript and just a couple lines of HTML, and wrote it in four minutes. Excellent!

ColdFusion 8 Gems

You can clear template cache via Admin API. No longer all or nothing. You can clear specific caches.

<cfdump> enhancements! Expand/contract items in the dump. You can do show=”list,of,fields” or hide=”list,of,fields” to show or hide just those records or items in the dump! Very nice! You can also do output=”filename.txt” and it will write the dump to a text file!

Testing for array element existence. Do this with ArrayIsDefined(myarray,3) to check if there is a third element in the array.

Per application settings. Finally can use cfqueryparam in a cached query. Implicit array and structure creation! JavaScript-style operators, i.e. i++. Pass tag attributes as a collection (attributesCollection). onMissingMethod for CFCs. onMissingTemplate in Application.cfc. Easily refresh WSDL for web services. CFFunction supports more return data types like wddx, xml, etc.

Tons of great stuff!

CFUnited 2007 Preconference Classes

I attended Rob Gonda’s “FLEX Intensive for ColdFusion Developers” class on Monday and Peter Bell’s “Practical Code Generation: By Example” class on Tuesday.

I didn’t take any notes during Rob’s class, as we spent practically the entire class scouring through FLEX examples. I did take notes during Peter’s class during the discourse sections of his class.

FLEX Intensive for ColdFusion Developers

I have two reasons for learning FLEX: (1) I am interested in developing AIR applications, and I’d like to do some of the more advanced functionality, which requires FLEX. (2) After learning the basics of FLEX, I want to try to use FLEX for some enhanced form functionality!

I think I’d only want to write full-fledged FLEX apps when writing AIR apps. To do this, Rob recommended the official Cairngorm microarchitecture, although Model Glue: FLEX is now a new option to look into as well. He also recommended using Cairngen to get things set up and started with Cairngorm.

Rob usually does include the compiled FLEX SWFs in his Subversion repository. He will have the FLEX source in one directory outside of the web directory, and have the binary output directory be the assets directory within the web directory. This way, the compiled FLEX is ready to be used within the web app, and everything can just be committed to the repository.

Rob recommends using SWFObject for deploying the SWFs.

Finally, he recommended the FLEX-AJAX Bridge.

Practical Code Generation: By Example

Peter Bell’s class was amazing. Even if you decide to use frameworks, you can automate work or application generation by using code generation. Below are my notes from his class.

Active generation (can regenerate as requirements change, and custom code is in separate files) is better, although passive generation (can generate once, but requires tweaking, and cannot regenerate) is faster to implement.

Methods for creating the code.

Concatenation: Code stored in a variable. <cfset ScriptHTML=”<cfquery>..</cfquery>”>. Good for when there’s variables, looping, etc. When there is a lot of specialized processing.

Templating: Much better. Template-based approach is easier to read and takes up less space. Good for mainly fixed code. Simple models. And it’s an approach we are familiar. ColdFusion itself is a manner of building HTML templates that get modified by the code.

Anatomy of a Generator.

  • Metadata (List of fields, etc). Could be in database, XML, etc.

  • Template.
  • Iterator. We immediately think, “For each business object, do…”
  • Orchestrator.

Metadata.

Use ColdFusion to build structs. Use XML. Or even flat text in a particular format. Any are fine.

Template.

XSL, CF Template. We will use CF Template because its readability is so much better than XSL.

Iterator.

Generate n files. One DAO per business object. One template per screen. Need filter support.

Orchestrator.

Generate m collections of n files. Tell it what metadata to use with what template, iterating how many times, and how to generate the filenames.

Extending Generated Code.

Need to mix the custom modifications with the standard generated code.

Protected blocks. Mark where generated code exists with a special string, and generator will not touch code inside custom blocks. Can actually be harder to write a generator using this method too. So this method is out of favor.

Inheritance. Just generate the standard CFCs, and you can have custom decorators that inherit the standard CFCs.

Events. Have custom code that looks for events, and when particular events are thrown by the standard code, the custom code method would generate.

Mixins. You basically put a right into the standard code so that the custom code can be inserted right into the execution stream. Of course, this introduces lots of conflicts since you’re sharing the time and space with all of your standard code.

Aspect Oriented Programming (AOP). When someone calls this method, before, after, or during that, call some custom code.

Frameworks vs. Code Generation

Remember when there was the initial conflict between compiled vs. interpreted languages? Same consideration for frameworks vs. code generation. Not either/or. Typically there will be a combination of generated code vs. frameworks you use. Intellectual property and performance concerns may be there. You may not want to give away an entire framework that will build something quickly that the clients can change themselves. So, this may cause you to choose code generation.

Getting Started

http://cftemplate.riaforge.org
http://cfgen.riaforge.org
http://www.pbell.com

Also check out opensource projects ColdSpring, LightWire, IBO.

Additional Notes During Walkthroughs

If you want to automagically generate IDs, titles, etc. for all aspects of the database and CFC, decouple it from the primary code generation. This way, you can generate stuff with almost no work, but yet it is still customizable because you just tweak the generated metadata for the code generation!

Design Patterns

Model-View-Controller. Business logic in the model. The meat of your application. View is the presentation. Perhaps some HTML or AJAX or Flex that displays it. Controller glues the two together, getting something from the view to the model.

Be careful against putting things in the wrong area. Most notably, beware logic in the controller! If just a web app, you may not notice, but when implementing AJAX or other connectivity, this can cause a problem.

Model consists of:

  • Bean. Basic business object. Gets, sets, validation.
  • Service Class / Manager. Used to get beans, in different ways. GetByFilter(), GetByProperty(), DeleteByFilter(), DeleteByProperty(), Save(), New().
  • Data Access Object / Gateway.

CFM page — Service, which may gen bean — DAO — DB.

Generic getters and setters can be handy for dynamic references. Easier for code generation too. Use in conjunction with a GettablePropertyList and SettablePropertyList for controlling access. Can have custom processing too by checking for the custom getter or setter and calling that with an Evaluate().

Typical IBO: get(), set(), access(), mutate(), loadStruct(), loadQuery(), first(), last(), next(), reset()

Remember, even if you just use a code generator to generate forms, or ColdSpring config files, or various other repetitive items, do it! If there is a framework that will meet your needs well enough, just go with that, but you can still help implement it with code generation.

Be careful–there is so much data overlap between the database specs and the CFCs and the forms and whatnot, that before you know it, you’ll be writing code generation for the whole app.

When doing the code generation, you then should use inheritance for the custom code. Develop your service so that it will look to see if the custom CFC exists, and if not, it just sends back the base CFC. You could autogenerate an empty CFC, but then you have to look inside the empty file to see if you have any customization. It is more apparent if the custom CFC doesn’t even exist!

Conclusion

These were a couple great classes. A lot to think about.

  Theme Brought to you by Directory Journal and Elegant Directory.