What's In It for Me?
What's In It for Me?

If you're as busy as I am, chances are you seldom have the time to sift through all the support documentation that accompanies your new authoring software - especially if that software is an upgrade to one of your familiar tools. I generally install it and run (we don't need no stinking directions!). In December 1998, I downloaded Allaire's ColdFusion 4.0, the upgrade for one of my favorite and most trusted applications. Fortunately, I actually read the documentation this time.

ColdFusion 4.0 includes many powerful new features that demonstrate Allaire's continuing commitment to this industry-leading technology. In this three-part series I'll share some of the features I've discovered and how I'm putting them to use. Who knows? Maybe you'll decide to start reading your documentation too.

In this issue I'll introduce you to several new tags and functions found in 4.0, and cover some of the ways you may want to implement them. In upcoming issues of ColdFusion Developer's Journal we'll explore performance tuning and improved security features.

New <Tags> Available in ColdFusion 4.0
The following section covers several of the new ColdFusion tags that you can probably put to use in your code immediately. Additional new tags (not included here) provide advanced functions such as access to registry settings, stored procedures, Verity collections, user authentication, CFScripting and WDDX formatting, which are beyond the scope of this article. For more information on these tags refer to Advanced ColdFusion Development in your documentation or explore the other ColdFusion developer resources available (see sidebar).

<CFLOCK> CFML Language Reference definition: The CFLOCK tag single-threads access to the CFML constructs in its body. Single-threaded access implies that the body of the tag can be executed by at most one request at a time. A request executing inside a CFLOCK tag has an "exclusive lock" on the tag. No other requests are allowed to start executing inside the tag while a request has an exclusive lock. ColdFusion issues exclusive locks on a first-come, first-serve basis.

Syntax
<CFLOCK
NAME="lockname"
TIMEOUT="timeout in seconds"
THROWONTIMEOUT="Yes/No">
<!--- CFML to be synchronized --->
</CFLOCK>

I'm using the CFLOCK tag to maintain integrity in several application processes. File manipulation routines (read, write, move, delete, etc.) that must be executed by just one user at a time are one appropriate use of this new tag. Wrapping CFLOCK tags around application constructs that perform database modifications (update and insert queries) helps maintain database integrity, especially when used in conjunction with the CFTRANSACTION tag that rolls back any modifications if the entire block is not executed (see Listing 1). In fact, any process in your code that needs to be protected from multiuser access should be wrapped with the CFLOCK tag. This also applies to CFXs (custom CFX tags) that aren't implemented in a thread-safe manner.

The CFLOCK tag will accept the optional THROWONTIMEOUT attribute to configure how your application proceeds if an exclusive lock can't be achieved within the specified timeout period. The default is THROWONTIMEOUT="Yes", which throws an exception. The alternative, THROWONTIMEOUT="No", will pass control to the next line of code following the </CFLOCK> tag.

Hint: Be careful to set the TIMEOUT attribute to the minimum value necessary to avoid clogging your throughput. Otherwise you may create a bottleneck in your application as users stack up while trying to access the code within the CFLOCK block.

<CFTRY>, <CFCATCH> and <CFTHROW>
CFML Language Reference definition: Used with one or more CFCATCH tags, the CFTRY tag allows developers to catch and process exceptions in ColdFusion pages. Exceptions include any event that disrupts the normal flow of instructions in a ColdFusion page such as failed database operations, missing include files, and developer-specified events. The CFTHROW tag raises a developer-specified exception that can be caught with CFCATCH TYPE="APPLICATION" or CFCATCH TYPE="ANY".

Syntax
<CFTRY>
... Add code here
<CFCATCH TYPE="exceptiontype">
... Add exception processing code here
</CFCATCH>
... Additional CFCATCH blocks go here
</CFTRY>

The combination of these exception-handling tags provides ColdFusion programmers with greater control over what happens if the train comes off the track:

By wrapping code in a CFTRY block (which contains at least one CFCATCH tag), you can display special instructions or execute specific commands when a predetermined exception occurs. In fact, you can wrap an entire ColdFusion template with a CFTRY tag, using a CFCATCH block around potential errors.

The TYPE attribute of the CFCATCH tag recognizes the following types of exceptions:

  • Application - Developer-defined exceptions configured with the CFTHROW tag
  • Database - Failed SQL statements, ODBC errors or other database failure
  • Template - General ColdFusion template errors
  • Security - Exceptions involving security functions
  • Object - Exceptions in code working with objects
  • MissingInclude - Exceptions when CFINCLUDE targets are missing
  • &127; Expression - Exceptions thrown by failed expression evaluations
  • Lock - Generated when CFLOCK blocks timeout or fail at runtime
  • Any (default) - All of the above, plus unrecognized exceptions

    ColdFusion tests CFCATCH tags in the order they appear on the page, so you'll obviously want to place CFCATCH TYPE="Any" last if you are catching more than one type of exception. Since the TYPE="Any" attribute will capture any exceptions thrown, subsequent CFCATCH blocks will not have the opportunity to catch exceptions.

    Hint: The CFTRY block will not handle exceptions thrown by the CFCATCH blocks that it encloses. This means that the code within any CFCATCH block should be relatively fail-safe or the flow of your application will be interrupted and the whole purpose of your CFTRY/CFCATCH construct will be defeated.

    The CFTHROW tag is used in conjunction with the CFTRY and CFCATCH tags to generate developer-specified exceptions. Using the CFIF conditional is a good way to implement this technique (see Listing 2).

    Caution: Documentation indicates that attempting to handle unexpected exceptions in CFML code can cause unpredictable results and may seriously degrade or crash the ColdFusion Server. Although I haven't experienced problems with this, it warrants consideration as you develop your exception handling routines.

    <CFSWITCH>, <CFCASE> and <CFDEFAULTCASE>
    CFML Language Reference definition: Used with CFCASE and CFDEFAULTCASE, the CFSWITCH tag evaluates a passed expression and passes control to the CFCASE tag that matches the expression result. You can optionally code a CFDEFAULTCASE tag, which receives control if there is no matching CFCASE tag value.

    Syntax
    <CFSWITCH EXPRESSION="expression">

    <CFCASE VALUE="value" DELIMITERS="delimiters">
    HTML and CFML tags
    </CFCASE>

    additional <CFCASE></CFCASE> tags
    <CFDEFAULTCASE>
    HTML and CFML tags
    </CFDEFAULTCASE>

    </CFSWITCH>

    The CFSWITCH/CFCASE construct provides better performance and is easier to read than a series of CFIF/CFELSEIF tags. First, define a condition with the CFSWITCH tag. Then add one or more CFCASE tags within the CFSWITCH block, optionally ending with a CFDEFAULTCASE tag. The CFSWITCH tag selects the CFCASE tag that matches its specified condition and executes the code between the CFCASE start and end tags.

    This program control structure is especially useful when you need to sift through a large amount of data returned by a database query (see Listing 3).

    New Functions( ) Available in ColdFusion 4.0
    This section introduces several new functions you may find immediately useful. Once again, there are several new functions we won't be able to address within the scope of this article; most of them pertain to working with structures and new security features. Consult your documentation and other ColdFusion resources for more information (see sidebar).

  • DirectoryExists(absolute_path): This function returns YES if the directory specified in the argument does exist and NO if it doesn't.

    Several of my applications create user-named directories, which means that my applications must check for the existence of a directory before a new one can be created. In the past, I've had to write and save a marker file in a new directory when it was built and then use the FileExists(absolute_path) function to check for the marker file as a workaround. I now use this function to check for duplicate directory names (see Listing 4). This saves time and resources, making my life easier (always a good thing).

  • Encrypt (string, key): This function allows encryption of the specified string.
  • Decrypt (encrypted_string, key): This function decrypts an encrypted string.

    These two new tags add encryption capabilities to your set of ColdFusion tools. If you need to exchange sensitive data in your application, these functions allow you to scramble (encrypt) strings that can be sorted out (decrypted) only if the exact key value that was used to encrypt the string is present in the decrypt function (see Listing 5).

    I have a third-party security certificate and utilize the SSL (https://) protocol in all of my commerce applications, so I haven't had any pressing need for these functions. I have experimented with them, however, and I'll probably find a use for them in the future. Look for more about security features of ColdFusion 4.0 in the third part of this series.

  • GetTickCount(): Returns a millisecond clock counter that can be used for timing sections of CFML code or any other aspects of page processing.

    Although the CF Application Server provides logging triggered by page access times, this particular function gives you an easy way to monitor the performance of specific sections of your code. By setting a variable before and after a block of code and then comparing the values, you can use a CFSWITCH/CFCASE construct to trigger predetermined actions. For example, if the execution of a database query exceeds 3000 milliseconds, you may want to execute code that sends the administrator an e-mail message or perhaps triggers an optimization routine (see Listing 6).

  • REFindNoCase (reg_expression, string [, start] [,returnsubexpressions]): Returns the position of the first occurrence of a regular expression in a string starting from the specified position. Returns 0 if no occurrences are found. The search is case-insensitive.
  • REReplaceNoCase (string, reg_expression, substring [, scope]): Returns string with a regular expression being replaced with substring in the specified scope. The search is case-insensitive.

    The regular expression functions are powerful tools that provide you with a mechanism for searching and matching text. These functions are used in conjunction with string manipulation functions, usually in file operations. For example, if you needed to write code that locates the second occurrence of the text "Sample Target" in a file, but you're not sure if the actual text is "sample target" or "SAMPLE Target" or even "Sample Target," you could weave a complex series of searches and conditional statements to accomplish this, but regular expressions give you a tool that can achieve this feat in one fell swoop (see Listing 7).

    The "No Case" aspect of these two tags brings a new twist to these tools. In previous versions of ColdFusion, if you wanted to use regular expressions to execute a case-insensitive search, you needed to code that in the regular expression string itself, which is a fairly complicated affair. These new tags make this powerful search technique much easier to implement. For more information on Regular Expressions and their use in string manipulation, I suggest reading Mastering Regular Expressions by Jeffrey E. F. Friedl.

    I'd like to make two points in closing. First, ColdFusion 4.0 contains a wealth of new features and functions that build upon previous releases to define a powerful platform that scales well and deploys rapidly. Since you're reading this journal I'll assume that I'm preaching to the choir. Second, the widespread acceptance of ColdFusion has generated a growing community of CF developers who offer numerous opportunities for you to find quick answers to your programming problems. Use them - and remember to pass your knowledge on to others who seek assistance.

    About Michael J. Murdy
    Michael J. Murdy is a founding partner and lead
    developer for FastTrac International, specializing in
    Internet applications for business. ColdFusion is a central
    component of their Internet solutions. Contact Mike by
    e-mail at murdy@FastTrac-INTL.com or visit the FastTrac Web site at www.FastTrac-INTL.com.

  • In order to post a comment you need to be registered and logged in.

    Register | Sign-in

    Reader Feedback: Page 1 of 1