MACROMEDIA COLDFUSION MX 61-DEVELOPING COLDFUSION MX Develop Manual

Developing coldfusion mx applications
Table of Contents

Advertisement

Quick Links

Developing ColdFusion MX Applications

Advertisement

Table of Contents
loading

Summary of Contents for MACROMEDIA COLDFUSION MX 61-DEVELOPING COLDFUSION MX

  • Page 1 Developing ColdFusion MX Applications...
  • Page 2 If you access a third-party website mentioned in this guide, then you do so at your own risk. Macromedia provides these links only as a convenience, and the inclusion of the link does not imply that Macromedia endorses or accepts any responsibility for the content on those third-party sites.
  • Page 3: Table Of Contents

    ColdFusion MX Administrator........32 Using ColdFusion MX with Macromedia Flash MX ..... . . 32 About J2EE and the ColdFusion architecture .
  • Page 4 Data types ............45 ColdFusion components .
  • Page 5 CHAPTER 4: Using Expressions and Pound Signs ......83 Expressions ............84 Operator types .
  • Page 6 CHAPTER 6: Extending ColdFusion Pages with CFML Scripting ... . 127 About CFScript..........128 Comparing tags and CFScript .
  • Page 7 PART II: Reusing CFML Code CHAPTER 8: Reusing Code in ColdFusion Pages ......163 About reusable CFML elements ........164 Including pages with the cfinclude tag.
  • Page 8 CHAPTER 10: Writing and Calling User-Defined Functions ....191 About user-defined functions ........192 Calling user-defined functions.
  • Page 9 CHAPTER 12: Building Custom CFXAPI Tags ......251 What are CFX tags?..........252 Before you begin developing CFX tags in Java .
  • Page 10 Optimizing ColdFusion applications........277 Caching ColdFusion pages that change infrequently....277 Caching parts of ColdFusion pages.
  • Page 11 Accessing and changing session variables......330 Ending a session ..........330 Configuring and using application variables .
  • Page 12 Processing a request in ColdFusion ........377 Determining the character encoding of a ColdFusion page.
  • Page 13 Writing queries using Dreamweaver MX ......422 Writing queries using Macromedia HomeSite+......424 CHAPTER 20: Accessing and Retrieving Data .
  • Page 14 CHAPTER 22: Using Query of Queries ....... . 451 About record sets..........452 Referencing queries as objects .
  • Page 15 CHAPTER 24: Building a Search Interface ......505 About Verity ........... . 506 Using Verity with ColdFusion .
  • Page 16 Requiring users to enter values in form fields ......566 Form variable notes and considerations......567 Working with queries and data .
  • Page 17 CHAPTER 28: Charting and Graphing Data ......617 Creating a chart..........618 Chart types.
  • Page 18 Using the CF.query function ........658 About CF.query function syntax .
  • Page 19 Using WDDX........... 702 Using the cfwddx tag .
  • Page 20 Using JSP tags and tag libraries ........739 Using a JSP tag in a ColdFusion page .
  • Page 21 PART VII: Using External Resources CHAPTER 35: Sending and Receiving E-Mail ......789 Using ColdFusion with mail servers ........790 Sending e-mail messages .
  • Page 22 Contents...
  • Page 23: Introduction

    Using this book ............24 About Macromedia ColdFusion MX documentation ....... . 26...
  • Page 24: Using This Book

    How to dynamically request information from users and display Information results on the user’s browser, including graphing data and providing data to Macromedia Flash clients. Using Web Elements and How to use XML, Java objects including Enterprise JavaBeans, External Objects JSP pages, web services (including creating web services in ColdFusion), and COM and CORBA objects.
  • Page 25 Beginning with ColdFusion If you are learning ColdFusion, a path such as the following might be most effective: Introduction to ColdFusion MX through Using Expressions and Pound Signs to learn the basics of CFML. Introduction to Databases and SQL through Updating Your Database to learn about using databases.
  • Page 26: About Macromedia Coldfusion Mx Documentation

    The index and the table of contents are useful tools for finding new features or changed documentation. About Macromedia ColdFusion MX documentation The ColdFusion MX documentation is designed to provide support for the complete spectrum of participants.
  • Page 27: Chapter 1: Introduction To Coldfusion Mx

    Using ColdFusion MX with Macromedia Flash MX ....... . 32...
  • Page 28: About Internet Applications And Web Application Servers

    Server (IIS) and the Apache web server, fulfill those requests by returning the requested information to the browser. This information includes, but is not limited to, HTML and Macromedia Flash files. A web server’s capabilities are limited because all it does is wait for requests to arrive and attempt to fulfill those requests as soon as possible.
  • Page 29 To extend the capabilities of a web server, you use a web application server, a software program that extends the web server’s capabilities to do tasks such as those in the preceding list. How a web server and web application server work together The following steps explain how a web server and web application server work together to process a page request: The user requests a page by typing a URL in a browser, and the web server receives the request.
  • Page 30: About Coldfusion Mx

    However, CFML is not limited to enhancing HTML. For example, you can create Macromedia Flash MX applications that consist entirely of Flash elements and CFML. Similarly, you can use CFML to create web services for use by other applications.
  • Page 31 CFML development tools Macromedia Dreamweaver MX helps you develop ColdFusion applications efficiently. It includes many features that simplify and enhance ColdFusion development, including tools for debugging CFML. Because CFML is written in an HTML-like text format, and you often use HTML in ColdFusion pages, you can also use an HTML editor or a text editor, such as Notepad, to write ColdFusion applications.
  • Page 32: Coldfusion Application Services

    ColdFusion MX. Using ColdFusion MX with Macromedia Flash MX Macromedia Flash MX is designed to overcome the many limitations of HTML and solve the problem of providing efficient, interactive, user interfaces for Internet applications. ColdFusion MX is designed to provide a fast, efficient environment for developing and providing data-driven Internet applications on your server.
  • Page 33: About J2Ee And The Coldfusion Architecture

    J2EE application on an independent J2EE application server. ColdFusion MX Enterprise includes a fully featured version of the Macromedia JRun J2EE application server, or can be deployed on third-party J2EE servers such as IBM WebSphere and BEA WebLogic.
  • Page 34: Coldfusion Features Described In This Book

    ColdFusion features described in this book ColdFusion provides a comprehensive set of features for developing and managing Internet applications. These features enhance speed and ease-of-development, and let you dynamically deploy your applications, integrate new and legacy technologies, and build secure applications. The following table describes the primary ColdFusion features that are discussed in this book, and lists the chapters that describe them.
  • Page 35 Server-side Macromedia Flash Remoting lets Macromedia Flash MX ActionScript developers create server-side ActionScript. ActionScript files can directly access Macromedia ColdFusion MX query and HTTP features through two functions: CF.query CF.http XML document ColdFusion applications can create, use, and manipulate XML processing and (Extensible Markup Language) documents.
  • Page 36 Feature Description Chapters COM and CORBA tag lets you use COM (Component Object Model) or cfobject objects DCOM (Distributed Component Object Model) and CORBA (Common Object Request Broker) objects in your ColdFusion applications. E-mail messages You can add interactive e-mail features to your ColdFusion applications using the tags.
  • Page 37 The CFML Programming Language This part describes the elements of the CFML programming language. It tells you how to use CFML tags, functions, variables and expressions, the CFScript scripting language, and regular expressions. The following chapters are included: Chapter 2: Elements of CFML ........39 Chapter 3: Using ColdFusion Variables .
  • Page 39: Chapter 2: Elements Of Cfml

    CHAPTER 2 Elements of CFML This chapter provides an overview of the basic elements of CFML, including tags, functions, constants, variables, expressions, and CFScript. The chapters in Part I of this book describe these topics in detail. Contents Introduction ............. . 40 Character case .
  • Page 40: Introduction

    Introduction This chapter introduces and describes the basic elements of CFML. These elements make CFML a powerful tool for developing interactive web applications. Because CFML is a dynamic application development tool, it has many of the features of a programming language, including the following: •...
  • Page 41: Built-In Tags

    Currently, over 1,000 custom tags are available on the Macromedia developer’s exchange (www.coldfusion.com/Developer/Gallery/index.cfm). They perform tasks ranging from checking if Cookies and JavaScript are enabled on the client's browser to moving items from one list box to another.
  • Page 42: Functions

    CFML custom tags When you write a custom tag in CFML, you can take advantage of all the features of the ColdFusion language, including all built-in tags and even other custom tags. CFML custom tags can include body sections and end tags. Because they are written in CFML, you do not need to know a programming language such as Java.
  • Page 43: User-Defined Functions

    You use built-in functions throughout ColdFusion pages. Built-in functions are frequently used in a tag to prepare data for display or further use. For example, the following cfset cfoutput line displays today’s date in the format October 12, 2001: <cfoutput>#DateFormat(Now(), "mmmm d, yyyy")#</cfoutput> Note that this code uses two nested functions.
  • Page 44: Constants

    Constants The value of a constant does not change during program execution. Constants are simple scalar values that you can use within expressions and functions, such as “Robert Trent Jones” and 123.45. Constants can be integers, real numbers, time and date values, Boolean values, or text strings.
  • Page 45: Data Types

    ColdFusion pages, across multiple applications. Flash Variables sent by a Macromedia Flash movie to ColdFusion and returned by ColdFusion to the movie. Arguments Variables passed in a call to a user-defined function or ColdFusion component method.
  • Page 46: Coldfusion Components

    Category Description and types Binary Raw data, such as the contents of a GIF file or an executable program file Object COM, CORBA, Java, web services, and ColdFusion Component objects: Complex objects that you create and access using the tag and other cfobject specialized tags.
  • Page 47: Flow Control

    if(Find("key",strings[i],1)) break; } </cfscript> <cfoutput>Entry #i# starts with "key"</cfoutput><br> You use CFScript to create user-defined functions. For more information on CFScript, see Chapter 6, “Extending ColdFusion Pages with CFML Scripting,” on page 127. For more information on user-defined functions, see Chapter 10, “Writing and Calling User-Defined Functions,”...
  • Page 48: Cfswitch, Cfcase, And Cfdefaultcase

    cfswitch, cfcase, and cfdefaultcase , and tags let you select among different code blocks cfswitch cfcase cfdefaultcase based on the value of an expression. ColdFusion processes these tags as follows: tag evaluates an expression. The tag body contains one or more cfswitch cfswitch tags and optionally includes...
  • Page 49 Loop type Description List Loops through the body of the tag once for each entry in a list. Collection Loops through the body of the tag once for each key in a ColdFusion structure or item in a COM/DCOM object. The following example shows a simple index loop: <cfloop index = "LoopCount"...
  • Page 50: Cfabort And Cfexit

    cfabort and cfexit tag stops processing of the current page at the location of the tag. cfabort cfabort ColdFusion returns to the user or calling tag everything that was processed before the cfabort tag. You can optionally specify an error message to display. You can use the tag as the cfabort body of a...
  • Page 51: Reserved Words

    The output looks like this: We all said "For He's a jolly good fellow." Then we said "For She's a jolly good fellow." Here is a pound sign: # Reserved words As with any programming tool, you cannot use just any word or name for ColdFusion variables, UDFs and custom tags.
  • Page 52 Chapter 2: Elements of CFML...
  • Page 53: Chapter 3: Using Coldfusion Variables

    CHAPTER 3 Using ColdFusion Variables Macromedia ColdFusion variables are the most frequently used operands in ColdFusion expressions. Variable values can be set and reset, and can be passed as attributes to CFML tags. Variables can be passed as parameters to functions, and can replace most constants.
  • Page 54: Creating Variables

    Creating variables You create most ColdFusion variables by assigning them values. (You must use the ArrayNew function to create arrays.) Most commonly, you create variables by using the tag. You can cfset also use the tag, and assignment statements in CFScript. Tags that create data objects cfparam also create variables.
  • Page 55: Variable Characteristics

    Variable characteristics You can classify a variable using the following characteristics: • The data type of the variable value, which indicates the kind of information a variable represents, such as number, string, or date • The scope of the variable, which indicates where the information is available and how long the variable persists The following sections provide detailed information on Data types and scopes.
  • Page 56: Numbers

    Data type notes Although ColdFusion variables do not have types, it is often convenient to use “variable type” as a shorthand for the type of data that the variable represents. ColdFusion can validate the type of data contained in form fields and query parameters. For more information, see Chapter 26, “Validating form field data types,”...
  • Page 57: Strings

    Real numbers Real numbers, numbers with a decimal part, are also known as floating point numbers. ColdFusion real numbers can range from approximately -10 to approximately 10 . A real number can have up to 12 significant digits. As with integers, you can assign a variable a value with more digits, but the data is stored as a string.
  • Page 58: Boolean Values

    To insert a pound sign in a string, you must escape the pound sign, as follows: "This is a pound sign ##" Lists ColdFusion includes functions that operate on lists, but it does not have a list data type. In ColdFusion, a list is just a string that consists of multiple entries separated by delimiter characters.
  • Page 59 When you do this, ColdFusion stores the information as a string. If you use a date-time function, ColdFusion stores the value as a date-time object, which is a separate simple data type. When possible, use date-time functions such as to specify dates and times, CreateDate CreateTime because these functions can prevent you from specifying the date or time in an invalid format and...
  • Page 60: Binary Data Type And Base64 Encoding

    How ColdFusion stores dates and times ColdFusion stores and manipulates dates and times as date-time objects. Date-time objects store data on a time line as real numbers. This storage method increases processing efficiency and directly mimics the method used by many popular database systems. In date-time objects, one day is equal to the difference between two successive integers.
  • Page 61: Complex Data Types

    Complex data types Arrays, structures, and queries are ColdFusion built-in complex data types. Structures and queries are sometimes referred to as objects, because they are containers for data, not individual data values. For details on using arrays and structures, see Chapter 5, “Using Arrays and Structures,”...
  • Page 62 You can use either of the following methods to reference elements stored in a structure: • StructureName.KeyName • StructureName["KeyName"] The following examples show these methods: depts.John="Sales" depts["John"]="Sales" When you assign an existing structure to a new variable, ColdFusion does not create a new structure.
  • Page 63 When you reference query columns inside tags, such as , in which you cfoutput cfloop specify the query name in a tag attribute, you do not have to specify the query name. You can access query columns as if they are one-dimensional arrays. For example, the following line assigns the contents of the Employee column in the second row of the myQuery query to the variable myVar: <cfset myVar = myQuery.Employee[2]>...
  • Page 64: Using Periods In Variable References

    Using a query column When you are not inside a , or tag that has a attribute, you can cfloop cfoutput cfmail query treat a query column as an array. However, query column references do not always behave as you might expect.
  • Page 65: Understanding Variables And Periods

    With the exception of Cookie and Client scope variables, which must always be simple variable types, you cannot normally include periods in simple variable names. However, ColdFusion makes some exceptions that accommodate legacy and third-party code that does not conform to this requirement.
  • Page 66: Creating Variables With Periods

    For example, assume you have the following code: <cfset myVar.a.b = "This is a test"> If a variable myVar does not exist, it does the following: Creates a structure named myVar. Creates a structure named a in the structure myVar. Creates a key named b in myVar.a.
  • Page 67: Data Type Conversion

    Creating Client and Cookie variables with periods To create a Client or Cookie variable with a name that includes one or more periods, simply assign the variable a value. For example, the following line creates a Cookie named User.Preferences.CreditCard: <cfset Cookie.User.Preferences.CreditCard=”Discover”> Data type conversion ColdFusion automatically converts between data types to satisfy the requirements of an expression’s operations, including a function’s argument requirements.
  • Page 68 The following table explains how conversions are performed. The first column shows values to convert. The remaining columns show the result of conversion to the listed data type. Value As Boolean As number As date-time As string "Yes" True Error "Yes"...
  • Page 69: Evaluation And Type Conversion Issues

    Converting binary data ColdFusion cannot automatically convert binary data to other data types. To convert binary data, use the functions. For more information, see “Binary data type and ToBase64 ToString Base64 encoding” on page Converting date and time data To ensure that a date and time value is expressed as a real number, add zero to the variable. The following example shows this: <cfset mynow = now()>...
  • Page 70 However, if myVariable has a numeric value such as 12, only the first example produces a result. In the second case, the value of myVariable is not converted to a Boolean data type, because the IS operator does not require a specific data type and just tests the two values for identity. Therefore, ColdFusion compares the value 12 with the constant True.
  • Page 71: Examples Of Type Conversion In Expression Evaluation

    If you use SQL to insert data into a database or in a WHERE clause to select data from a database, and the database driver does not support ODBC-formatted dates, use the DateFormat function to convert the date-time value to a valid format for the driver. This rule also applies to queries of queries.
  • Page 72: About Scopes

    Example 2 True AND 2 * 3 Result value as string: "YES" Explanation: 6 is converted to Boolean True because it is nonzero; True AND True is True. Example 3 "Five is " & 5 Result value as string: "Five is 5" Explanation: 5 is converted to the string "5".
  • Page 73 Scope Description Contains parameters passed to the current page in the URL that is used to call it. The parameters are appended to the URL in the format ?variablename = value[&variablename=value...]; for example www.MyCompany.com/ inputpage.cfm?productCode=A12CD1510& quantity=3. Note: If a URL includes multiple parameters with the same name, the resulting variable in the ColdFusion URL scope consists of all parameter values separated by commas.
  • Page 74 Chapter 15, “Using Persistent Data and Locking,” on page 315. Flash Variables sent by a Macromedia Flash movie to ColdFusion and returned by ColdFusion to the movie. For more information, see Chapter 29, “Using the Flash Remoting Service,” on page 641.
  • Page 75: Creating And Using Variables In Scopes

    Creating and using variables in scopes The following table shows how you create and refer to variables in different scopes in your code. For more information on the mechanisms for creating variables in most scopes, see “Creating variables” on page Scope Prefix prefix...
  • Page 76 Scope Prefix prefix required to (type) reference Where available Created by Cffile Following an invocation of tag. cffile cffile Cookie For one client in one or more cfcookie tag. You can also set applications and pages, over memory-only cookies by specifying multiple browser sessions.
  • Page 77: Using Scopes

    Using scopes The following sections provide details on how you can create and use variables in different scopes. Evaluating unscoped variables If you use a variable name without a scope prefix, ColdFusion checks the scopes in the following order to find the variable: Arguments Variables (local scope) Cffile...
  • Page 78: Ensuring Variable Existence

    Caution: Do not call StructClear to clear session variables. This deletes the (Session) SessionID , and built-in variables, effectively ending the session. If you want to use CFID CFtoken StructClear delete your application variables, put those variables in a structure in the Session scope, then clear that structure.
  • Page 79: Testing For A Variable's Existence

    • You can use a tag with a attribute to tell ColdFusion to display a helpful cfform input hidden message to any user who does not enter data in a required field. For more information on this technique, see Chapter 26, “Requiring users to enter values in form fields,” on page 566.
  • Page 80: Validating Data Types

    • With only the attribute to test that a required variable exists. If it does not exist, the name ColdFusion server stops processing the page and displays an error message. • With the attributes to test for the existence of an optional variable. If the name default variable exists, processing continues and the value is not changed.
  • Page 81: Using The Cfparam Tag To Validate The Data Type

    • Use the tag in a SQL WHERE clause to validate query parameters. For cfqueryparam information on this technique, see Chapter 20, “Using cfqueryparam,” on page 435. Note: Data validation using the cfparam, cfqueryparam, and form tags is done by the server. Validation using cfform tags is done using JavaScript in the user’s browser, before any data is sent to the server.
  • Page 82: Passing Variables To Custom Tags And Udfs

    Passing variables to custom tags and UDFs The following sections describe rules for how data gets passed to custom tags and user-defined functions that are written in CFML, and to CFX custom tags that are written in Java or C++. Passing variables to CFML tags and UDFs When you pass a variable to a CFML custom tag as an attribute, or to a user-defined function as an argument, the following rules determine whether the custom tag or function receives its own...
  • Page 83: Chapter 4: Using Expressions And Pound Signs

    CHAPTER 4 Using Expressions and Pound Signs This chapter discusses how to use expressions in CFML. It discusses the elements of ColdFusion Expressions and how to create expressions. It also describes the correct use of pound signs to indicate expressions in ColdFusion tags such as , in strings, and in expressions.
  • Page 84: Expressions

    Expressions ColdFusion expressions consist of operands and operators. Operands are comprised of constants and variables. Operators, such as the multiplication symbol, are the verbs that act on the operands; functions are a form of operator. The simplest expression consists of a single operand with no operators. Complex expressions have multiple operators and operands.
  • Page 85 Operator Description Integer division: Divide an integer by another integer. Use the backslash character (\) to separate the integers. The right operand cannot be zero. For example, 9\4 is 2. Exponentiation: Return the result of a number raised to a power (exponent). Use the caret character (^) to separate the number from the power;...
  • Page 86 Operator Description LESS THAN Opposite of GREATER THAN. Return True if the value on the left is smaller than the value on the right. GREATER THAN OR EQUAL TO Return True if the value on the left is greater than or equal to the value on the right.
  • Page 87: Operator Precedence And Evaluation Ordering

    String operators There is one string operator, which is the concatenation operator. Operator Description & Concatenates strings. Operator precedence and evaluation ordering The order of precedence controls the order in which operators in an expression are evaluated. The order of precedence is as follows: Unary +, Unary - *, / +, -...
  • Page 88 Function syntax The following table shows function syntax and usage guidelines: Usage Example No arguments Function() Basic format Function(Data) Nested functions Function1(Function2(Data)) Multiple arguments Function(Data1, Data2, Data3) String arguments Function('This is a demo') Function("This is a demo") Arguments that are expressions Function1(X*Y, Function2("Text")) All functions return values.
  • Page 89: Using Pound Signs

    Executes the function on the string argument "we all need more sleep!" to get "WE ALL UCase NEED MORE SLEEP!". Assigns the string value "WE ALL NEED MORE SLEEP!" to the variable myStringVar. ColdFusion completes steps 1-3 before invoking the function. Using pound signs Pound signs (#) have a special meaning in CFML.
  • Page 90: Using Pound Signs In Tag Bodies

    Note: You do not need to use pound signs when you use the cfset tag to assign one variable’s value to another value. For example, the following tag assigns the value of the oldVar variable to the new variable, newVar: <cfset newVar = oldVar>. Using pound signs in tag bodies You can put variables or functions freely inside the bodies of the following tags by enclosing each variable or expression with pound signs:...
  • Page 91: Nested Pound Signs

    As with the statement, two expressions can be adjacent to each other in strings, as in cfoutput the following example: <cfset TheString = "Monk is #Left("Moon", 2)##Mid("Monkey", 3, 2)#"> The double quotes around "Moon" and "Monkey" do not need to be escaped (as in ""Moon"" and ""Monkey"").
  • Page 92: Dynamic Expressions And Dynamic Variables

    Dynamic expressions and dynamic variables This section discusses the advanced topics of dynamic expressions, dynamic evaluation, and dynamic variable naming. Many ColdFusion programmers never encounter or need to use dynamic expressions. However, dynamic variable naming is important in situations where the variable names are not known in advance, such as in shopping cart applications.
  • Page 93: Dynamic Variable Naming Without Dynamic Evaluation

    Selecting how to create variable names The following two examples describes cases when you need dynamic variable names: • Form applications where the number and names of fields on the form vary dynamically. In this case, the form posts only the names and values of its fields to the action page. The action page does not know all the names of the fields, although it does know how the field names (that is, the variable names) are constructed.
  • Page 94: Using Dynamic Evaluation

    Dynamic variable limitation When you use a dynamic variable name in quotes on the left side of an assignment, the name must be either a simple variable name or a complex name that uses object.property notation (such as MyStruct.#KeyName#). You cannot use an array as part of a dynamic variable name. For example, the following code generates an error: <cfset MyArray=ArrayNew(1)>...
  • Page 95 Function Purpose Evaluates a boolean condition expression. Depending on whether this expression is True or False, dynamically evaluates one of two string expressions and returns the result of the evaluation. The function is convenient for incorporating a cfif tag in-line in HTML. For an example of using this function, see “Using the IIF function”...
  • Page 96 Reviewing the code The following table describes how ColdFusion processes this code: Code Description Sets the two variables to the following strings: <cfset myVar2="myVar"> <cfset myVar="27/9"> myVar 27/9 Displays the values assigned to the variables, myVar and 27/9 <cfoutput> #myVar2#<br> respectively.
  • Page 97 Example 2 This example shows how you can use an associative array reference in place of an Evaluate function. This technique is powerful because: • Most ColdFusion scopes are accessible as structures. • You can use ColdFusion expressions in the indexes of associative array structure references. (For more information on using associative array references for structures, see Chapter 5, “Structure notation,”...
  • Page 98: Using The Iif Function

    In the second line, enclosing the myVar#i# variable name in quotation marks tells ColdFusion to evaluate the name and process any text in pound signs as a variable or function. ColdFusion replaces the #i# with the value of the variable i, so that if the value of i is 12, this code is equivalent to the line <cfset myVar12 = myVal>...
  • Page 99: Example: A Dynamic Shopping Cart

    <cfif i mod 2 EQ 0> <cfset Color = "white"> <cfelse> <cfset Color = "gray"> </cfif> <tr bgcolor="#color#"> <td> hello #i# </td> </tr> </cfloop> </table> </cfoutput> Example: a dynamic shopping cart The following example dynamically creates and manipulates variable names without using dynamic expression evaluation by using associative array notation.
  • Page 100 <td>Order?</td> <td>Product</td> <td>Code</td> <td>Quantity</td> </tr> <cfloop index="i" from="1" to="#cartItems#"> <tr> <cfset productName= "product_" & Cart[i].ID> <cfset skuName= "sku_" & Cart[i].ID> <cfset qtyname= "qty_" & Cart[i].ID> <td><cfinput type="checkbox" name="itemID" value="#Cart[i].ID#" checked> </td> <td><cfinput type="text" name="#productName#" value="#Cart[i].Name#" passThrough = "readonly = 'True'"></td> <td><cfinput type="text"...
  • Page 101 Code Description <cfloop index="i" from="1" Loop through the shopping cart entries to generate to="#cartItems#"> the cart form dynamically. For each loop, generate <tr> variables used for the form field name attributes by <cfset productName= "product_" & appending the cart item ID (Cart[i].ID) to a field Cart[i].ID>...
  • Page 102 Reviewing the code The following table describes the code: Code Description <cfif isDefined("Form.submit")> Run the CFML on this page only if it is called by submitting a form. This is not needed if there are separate form and action pages, but is required if the form and action page were one ColdFusion page.
  • Page 103: Chapter 5: Using Arrays And Structures

    CHAPTER 5 Using Arrays and Structures ColdFusion supports dynamic multidimensional arrays. This chapter explains the basics of creating and handling arrays. It also provides several examples showing how arrays can enhance your ColdFusion application code. ColdFusion also supports structures for managing lists of key-value pairs. Because structures can contain other structures or complex data types as it values, they provide a flexible and powerful tool for managing complex data.
  • Page 104: About Arrays

    About arrays Traditionally, an array is a tabular structure used to hold data, much like a spreadsheet table with clearly defined limits and dimensions. In ColdFusion, you typically use arrays to temporarily store data. For example, if your site lets users order goods online, you can store their shopping cart contents in an array.
  • Page 105 A conventional 2D array is like a fixed-size table made up of individual cells, as the following figure shows: The following figure represents a ColdFusion 2D array: A ColdFusion 2D array is actually a one-dimensional array that contains a series of additional 1D arrays.
  • Page 106: Basic Array Techniques

    Basic array techniques The following sections describe how to reference array elements, create arrays, add and remove array elements, and copy arrays. Referencing array elements You reference array elements by enclosing the index with brackets: arrayName[x] where x is the index that you want to reference.
  • Page 107 The best way to understand an asymmetrical array is by looking at it. The following example creates an asymmetric, multidimensional array and the tag displays the resulting array cfdump structure. Several array elements do not yet contain data. <cfset myarray=ArrayNew(1)> <cfset myotherarray=ArrayNew(2)>...
  • Page 108: Adding Elements To An Array

    Adding elements to an array You can add an element to an array by assigning the element a value or by using a ColdFusion function. Adding an array element by assignment You can add elements to an array by defining the value of an array element, as shown in the following tag: cfset...
  • Page 109: Deleting Elements From An Array

    For more information about these array functions, see CFML Reference. Deleting elements from an array Use the function to delete data from the array at a particular index, instead of ArrayDeleteAt setting the data value to zero or an empty string. If you remove data from an array, the array resizes dynamically, as the following example shows: <!--- Create an array with three elements --->...
  • Page 110: Populating Arrays With Data

    <cfset myNewArray=myArray> <cfdump var=#myNewArray#><br> <br> Change the values in the new array.<br> <cfset myNewArray[1].key1="New first array element"> <cfset myNewArray[2]="New second array element"> <br> Contents of the original array after the changes:<br> <cfdump var=#myArray#><br> Contents of the new array after the changes:<br> <cfdump var=#myNewArray#>...
  • Page 111 <cfloop index="loopcount" from=1 to=12> <cfoutput> #months[loopcount]#<br> </cfoutput> </cfloop> Using nested loops for 2D and 3D arrays To output values from 2D and 3D arrays, you must employ nested loops to return array data. With a one-dimensional (1D) array, a single is sufficient to output data, as in the previous cfloop example.
  • Page 112: Populating An Array From A Query

    Populating an array from a query When populating an array from a query, keep the following things in mind: • You cannot add query data to an array all at once. A looping structure is generally required to populate an array from a query. •...
  • Page 113: Array Functions

    Array functions The following functions are available for creating, editing, and handling arrays: Function Description ArrayAppend Appends an array element to the end of a specified array. Returns the average of the values in the specified array. ArrayAvg Deletes all data in a specified array. ArrayClear ArrayDeleteAt Deletes an element from a specified array at the specified index and resizes the...
  • Page 114: Structure Notation

    A structure’s key must be a string. The values associated with the key can be any valid ColdFusion value or object. It can be a string or integer, or a complex object such as an array or another structure. Because structures can contain any kind of data they provide a very powerful and flexible mechanism for representing complex data.
  • Page 115 <cfset key1Var="key1"> <cfset key2Var="key2"> <cfset key3Var="key3"> <cfset var2="2"> <cfoutput> Value of the first key<br> #mystruct.key1#<br> #mystruct["key1"]#<br> #mystruct[key1Var]#<br> <br> Value of the second entry in the key2 array<br> #myStruct.key2[2]#<br> #myStruct["key2"][2]#<br> #myStruct[key2Var][2]#<br> #myStruct[key2Var][var2]#<br> <br> Value of the struct2key2 entry in the key3 structure<br> #myStruct.key3.struct2key2#<br>...
  • Page 116: Creating And Using Structures

    Creating structures by assigning values You can create a structure by assigning a key-value pair. For example, the following line creates a structure named myStruct with one element, name, that has the value Macromedia. <cfset myStruct.name="Macromedia"> Creating structures using a function...
  • Page 117: Adding Data Elements To Structures

    Adding data elements to structures You add an element to a structure by assigning the element a value or by using a ColdFusion function. It is cleaner and more efficient to use direct assignment, so only this technique is described. You add structure key-value pairs by defining the value of the structure key, as shown in the following example: <cfset myNewStructure.key1="A new structure with a new key">...
  • Page 118 To discover whether a specific Structure contains data, use the function, as StructIsEmpty follows: StructIsEmpty(structure_name) This function returns True if the structure is empty, and False if it contains data. Finding a specific key and its value To determine whether a specific key exists in a structure, use the function, as StructKeyExists follows:...
  • Page 119: Copying Structures

    Copying structures ColdFusion provides several ways to copy structures and create structure references. The following table lists these methods and describes their uses: Technique Makes a complete copy of the structure. All data is copied from the original Duplicate function structure to the new structure, including the contents of structures, queries, and other objects.
  • Page 120 <cfdump var=#structRef#><br> <br> Change a string, array element, and structure value in the StructCopy copy.<br> <br> <cfset CopiedStruct.key1="1A"> <cfset CopiedStruct.key3[2]="4A"> <cfset CopiedStruct.key4.Struct2key2="6A"> Original structure<br> <cfdump var=#myNewStructure#><br> Copied structure<br> <cfdump var=#CopiedStruct#><br> Duplicated structure<br> <cfdump var=#DupStruct#><br> Structure reference <cfdump var=#structRef#><br> <br> Change a string, array element, and structure value in the Duplicate<br> <br>...
  • Page 121: Deleting Structure Elements And Structures

    StructClear the contents of the structure and all references point to the empty structure, as shown in the following example: <cfset myStruct.Key1="Macromedia"> Structure before StructClear<br> <cfdump var="#myStruct#"> <cfset myCopy=myStruct>...
  • Page 122: Structure Example

    Structure example Structures are particularly useful for grouping together a set of variables under a single name. The example in this section uses structures to collect information from a form, and to submit that information to a custom tag, named .
  • Page 123 Last Name:&nbsp; <input name="lastname" type="text" hspace="30" maxlength="30"><br> EMail:&nbsp; <input name="email" type="text" hspace="30" maxlength="30"><br> Phone:&nbsp; <input name="phone" type="text" hspace="20" maxlength="20"><br> Department:&nbsp; <input name="department" type="text" hspace="30" maxlength="30"><br> <input type="Submit" value="OK"> </form> <br> </body> </html> Reviewing the code The following table describes the code: Code Description <cfparam name="Form.firstname"...
  • Page 124 Code Description <cf_addemployee Call the custom tag and pass it cf_addemployee empinfo="#duplicate(employee)#"> a copy of the employee structure in the </cfif> empinfo attribute. The duplicate function ensures that the custom tag gets a copy of the employee structure, not the original. While this is not necessary in this example, it is good practice because it prevents the custom tag from modifying the calling page’s structure contents.
  • Page 125: Structure Functions

    Reviewing the code The following table describes the code: Code Description If the custom tag was called without an <cfif StructIsEmpty(Attributes.empinfo)> <cfoutput> attribute, display an error message empinfo Error. No employee data was passed. and exit the tag. </cfoutput> <cfexit method="ExitTag"> Add the employee data passed in the empinfo <cfelse>...
  • Page 126 Function Description StructFindValue Searches through a structure for the specified simple data value (for example, a string or number) and returns an array containing information on the value location in the structure. StructGet Returns a reference to a substructure contained in a structure at the specified path.
  • Page 127: Chapter 6: Extending Coldfusion Pages With Cfml Scripting

    CHAPTER 6 Extending ColdFusion Pages with CFML Scripting ColdFusion MX offers a server-side scripting language, CFScript, that provides ColdFusion functionality in script syntax. This JavaScript-like language gives developers the same control flow as ColdFusion, but without tags. You can also use CFScript to write user-defined functions that you can use anywhere that a ColdFusion expression is allowed.
  • Page 128: About Cfscript

    About CFScript CFScript is a language within a language. It is a scripting language that is similar to JavaScript but is simpler to use. Also, unlike JavaScript, CFScript only runs on the ColdFusion server; it does not run on the client system. CFScript code can use all the ColdFusion functions and expressions, and has access to all ColdFusion variables that are available in the script’s scope.
  • Page 129: The Cfscript Language

    Using CFScript <cfscript> if (IsDefined("Form.submit")) { if ((Form.lastname NEQ "") AND (Form.department NEQ "")) { employee=StructNew(); employee.firstname=Form.firstname; employee.lastname=Form.lastname; employee.email=Form.email; employee.phone=Form.phone; employee.department=Form.department; WriteOutput("Adding #Form.firstname# #Form.lastname# <br>"); else WriteOutput("You must enter a Last Name and Department.<br>"); </cfscript> The CFScript language This section explains the syntax of the CFScript language. Identifying CFScript You enclose CFScript regions inside tags.
  • Page 130: Statement Blocks

    switch-case break return (in custom functions only) continue The following rules apply to statements: • You must put a semicolon at the end of a statement. • Line breaks are ignored. A single statement can cross multiple lines. • White space is ignored. For example, it does not matter whether you precede a semicolon with a space character.
  • Page 131: Reserved Words

    • The end of a multiline comment can be followed on the same line by active code. For example, the following line is valid, although it is poor coding practice: End of my long comment */ foo = "bar"; • You can use multiline format for a comment on a single line, for example: /*This is a single line comment using multiline format.
  • Page 132: Using Cfscript Statements

    CFScript equivalent Indexed cfloop for loops Conditional cfloop while loops and do while loops Structure cfloop for in loop. (There is no equivalent for queries, lists, or objects.) cfbreak break statement. CFScript also has a continue statement that has no equivalent CFML tag.
  • Page 133 Using if and else statements statements have the following syntax: else if(expr) statement [else statement] In its simplest form, an if statement looks like this: if(value EQ 2700) message = "You’ve reached the maximum"; A simple if-else statement looks like the following: if(score GT 1) result = "positive";...
  • Page 134: Using Looping Statements

    • The statements following the colon in a statement block do not have to be in braces. If a case constant value equals the expression, ColdFusion executes all statements through the switch statement. break • statement at the end of the statement tells ColdFusion to exit the break case...
  • Page 135 Using for loops The for loop has the following format: for (initial-expression; test-expression; final-expression) statement The initial-expression and final-expression can be one of the following: • A single assignment expression; for example, x=5 or loop=loop+1 • Any ColdFusion expression; for example, SetVariable("a",a+1) •...
  • Page 136 if(Find("key",strings[indx],1)) { WriteOutput("Found key at " & indx & ".<br>"); break; else if (indx IS ArrayLen(strings)) { WriteOutput("Exited at " & indx & ".<br>"); break; </cfscript> This example shows one important issue that you must remember when creating loops: you must always ensure that the loop ends.
  • Page 137 statement does the following: do while Executes the statement, which can be a single semicolon-terminated statement or a statement block in curly braces. Evaluates the expression. If the expression is true, it returns to step 1. If the expression is False, processing continues with the next statement. The following example, like the while loop example, populates a 10-element array with multiples of 5: a = ArrayNew(1);...
  • Page 138 Note: Unlike the tag, CFScript for-in loops do not provide built-in support for looping over cfloop queries and lists. Using continue and break statements The continue and break statements enable you to control the processing inside loops: • statement tells ColdFusion to skip to the beginning of the next loop iteration. continue •...
  • Page 139: Handling Exceptions

    Handling exceptions ColdFusion provides two statements for exception handling in CFScript: . These catch statements are equivalent to the CFML tags. cftry cfcatch Note: This section does not explain exception-handling concepts. For a discussion of exception handling in ColdFusion, see Chapter 14, “Handling Errors,”...
  • Page 140: Cfscript Example

    CFScript example The example in this section uses the following CFScript features: • Variable assignment • Function calls • For loops • If-else statements • functions WriteOutput • Switch statements The example uses CFScript without any other ColdFusion tags. It creates a structure of course applicants.
  • Page 141 WriteOutput("Reject reason: Score was too low.<br>"); break; case "late": WriteOutput("Reject reason: Application was late.<br>"); break; default: WriteOutput("Rejected with invalid reason code.<br>"); } //end switch } //end if else { WriteOutput("Reject reason was not defined.<br>"); } //end else WriteOutput("<br>"); } //end for </cfscript>...
  • Page 142 Code Description if (StructKeyExists(rejectCode,applicant)) { Checks the structure for a rejectCode switch(rejectcode[applicant]) { rejection code for the applicant. case "score": If a code exists, enters a switch WriteOutput("Reject reason: Score was too statement that examines the rejection low.<br>"); code value. break;...
  • Page 143: Chapter 7: Using Regular Expressions In Functions

    CHAPTER 7 Using Regular Expressions in Functions Regular expressions let you perform string matching operations using ColdFusion functions. This chapter describes how regular expressions work with the following functions: • REFind • REFindNoCase • REReplace • REReplaceNoCase This chapter does not apply to regular expressions used in the tags.
  • Page 144: About Regular Expressions

    About regular expressions In traditional string matching, as used by the ColdFusion functions, you Find Replace provide the string pattern to search for and the string to search. The following example searches a string for the pattern " BIG " and returns a string index if found. The string index is the location in the search string where the string pattern begins.
  • Page 145: Basic Regular Expression Syntax

    Basic regular expression syntax The simplest regular expression contains only a literal characters. The literal characters must match exactly the text being searched. For example, you can use the regular expression function to find the string pattern " BIG ", just as you can with the function: REFind Find...
  • Page 146: Finding Repeating Characters

    Note: The * only applies to the character set that immediately precedes it, not to the entire regular expression. A + after the closing square bracket specifies to find one or more occurrences of the character set. You interpret the regular expression [A-Z]+ as matching one or more uppercase letters "...
  • Page 147: Case Sensitivity In Regular Expressions

    • Where m is 0 or greater. Match at least m occurrences. The syntax is not allowed. The expression {1,} is equivalent to the special character +, and {0,} is equivalent to *. • Where m is 0 or greater. Match exactly m occurrences. Case sensitivity in regular expressions ColdFusion supplies case-sensitive and case-insensitive functions for working with regular expressions.
  • Page 148 The following table describes the special characters for regular expressions: Special Character Description A backslash followed by any special character matches the literal character itself, that is, the backslash escapes the special character. For example, "\+" matches the plus sign, and "\\" matches a backslash. A period matches any character, including newline.
  • Page 149 Special Character Description (?x) If at the beginning of a regular expression, it specifies to ignore whitespace in the regular expression and lets you use ## for end-of-line comments. You can match a space by escaping it with a backslash. For example, the following regular expression includes comments, preceded by ##, that are ignored by ColdFusion: reFind("(?x)
  • Page 150: Using Escape Sequences

    Special Character Description (?!...) If at the beginning of a regular expression, it specifies to use negative lookahead. Negative is just like positive lookahead, as specified by (?=...), except that it tests for the absence of a match. Lookahead parentheses do not capture text, so backreference numbering will skip over these groups.
  • Page 151: Using Character Classes

    In character sets within regular expressions, you can include a character class. You enclose the character class inside square brackets, as the following example shows: REReplace (“Macromedia Web Site”,”[[:space:]]”,”*”,”ALL”) This code replaces all the spaces with *, producing this string: Macromedia*Web*Site You can combine character classes with other expressions within a character set.
  • Page 152: Using Backreferences

    Character class Matches :alnum: Any alphanumeric character. Same as \w. :xdigit: Any hexadecimal digit. Same as [0-9A-Fa-f]. :blank: Space or a tab. :space: Any whitespace character. Same as \s. :print: Any alphanumeric, punctuation, or space character. :punct: Any punctuation character :graph: Any alphanumeric or punctuation character.
  • Page 153: Using Backreferences In Replacement Strings

    Using backreferences in replacement strings You can use backreferences in the replacement string of both the REReplace functions. For example, to replace the first repeated word in a text string with REReplaceNoCase a single word, use the following syntax: REReplace("There is is a cat in in the kitchen", "([A-Za-z ]+)\1","\1") This results in the sentence: “There is a cat in in the kitchen”...
  • Page 154: Omitting Subexpressions From Backreferences

    For example, the following statement replaces the uppercase string "HELLO" with a lowercase "hello". This example uses backreferences to perform the replacement. For more information on using backreferences, see “Using backreferences in replacement strings” on page 153. reReplace("HELLO", "([[:upper:]]*)", "Don't shout\scream \L\1") The result of this example is the string "Don't shout\scream hello".
  • Page 155 To find the second occurrence of the string, you must know that the first string occurred at index 5 and that the string’s length was 5. However, only returns starting index of the string, REFind not its length. So, you either must know the length of the matched string to call REFind second time, or you must use subexpressions in the regular expression.
  • Page 156 The following figure shows the output of the tag: cfdump If you include subexpressions in your regular expression, each element of after element one contains the position and length of the first occurrence of each subexpression in the search string. In the following example, the expression [A-Za-z]+ is a subexpression of a regular expression.
  • Page 157: Specifying Minimal Matching

    The following figure shows the output of the tag: cfdump For a full discussion of subexpression usage, see the sections on in the REFind REFindNoCase ColdFusion functions chapter in CFML Reference. Specifying minimal matching The regular expression quantifiers ?, *, +, {min,} and {min,max} specify a minimum and/or maximum number of instances of a given expression to match.
  • Page 158: Regular Expression Examples

    However, sometimes you might want to override this default behavior to find the shortest string that matches the regular expression. ColdFusion includes minimal-matching quantifiers that let you specify to match on the smallest string. The following table describes these expressions: Expression Description minimal-matching version of *...
  • Page 159: Regular Expressions In Cfml

    Expression Description (\+|-)?[1-9]\.[0-9]*E(\+|-)?[0-9]+ A real number in engineering notation. a{2,4} Two to four occurrences of “a”: aa, aaa, aaaa. (ba){3,} At least three “ba” pairs: bababa, babababa, and so on. Regular expressions in CFML The following examples of CFML show some common uses of regular expression functions: Expression Returns The query string with parameter CFID...
  • Page 160 The following Perl statements are not supported: • Lookbehind (?<=) (<?!) • \x{hhhh} • • • An excellent reference on regular expressions is Mastering Regular Expressions, by Jeffrey E. F. Friedl, O'Reilly & Associates, Inc., 1997, ISBN: 1-56592-257-3, available at www.oreilly.com. Chapter 7: Using Regular Expressions in Functions...
  • Page 161 PART II Reusing CFML Code This part describes techniques for reusing code in ColdFusion pages. These techniques let you write your code once and use it, without copying it, in many places. These techniques include the tag, user-defined functions, cfinclude custom tags, ColdFusion components, and ColdFusion Extension (CFX) tags.
  • Page 163: Chapter 8: Reusing Code In Coldfusion

    CHAPTER 8 Reusing Code in ColdFusion Pages This chapter describes techniques for reusing code in ColdFusion pages. These techniques let you write your code once and use it, without copying it, in many places. This chapter describes the techniques and their features, and provides advice on selecting among the techniques. Contents About reusable CFML elements.
  • Page 164: About Reusable Cfml Elements

    About reusable CFML elements ColdFusion provides you with several types of reusable elements, sections of code that you can create once and use multiple times in an application. Many of these elements also let you extend the built-in capabilities of ColdFusion. ColdFusion provides the following reusable CFML elements: •...
  • Page 165: Using The Cfinclude Tag

    The model of an included page is that it is part of your page; it just resides in a separate file. The tag cannot pass parameters to the included page, but the included page has access to cfinclude all the variables on the page that includes it. The following figure shows this model: Using the cfinclude tag When you use the tag to include one ColdFusion page in another ColdFusion page,...
  • Page 166: Recommended Uses

    <title>Test for Include</title> </head> <body> <cfinclude template="header.cfm"> </body> </html> Save the file as includeheader.cfm and view it in a browser. The header should appear along with the logo. Recommended uses Consider using the tag in the following cases: cfinclude • For page headers and footers •...
  • Page 167: For More Information

    Consider using UDFs in the following circumstances: • You must pass in a number of arguments, process the results, and return a value. UDFs can return complex values, including structures that contain multiple simple values. • You want to provide logical units, such as data manipulation functions. •...
  • Page 168: Calling Custom Cfml Tags

    Although a custom tag and a ColdFusion page that you include using the tag are both cfinclude ColdFusion pages, they differ in how they are processed. When a page calls a custom tag, it hands processing off to the custom tag page and waits until the custom tag page completes. When the custom tag finishes, it returns processing (and possibly data) to the calling page;...
  • Page 169: Recommended Uses

    These tags let you maintain a CFML-like design scheme for your code. You can easily distribute your custom tags and share tags with others. For example, the Macromedia ColdFusion Developer’s Exchange includes a library of custom tags that perform a wide variety of often- complex jobs;...
  • Page 170: Recommended Uses

    • They can provide web services and make them available over the internet. • They can provide ColdFusion services that Macromedia Flash clients can call directly. • They have several features that are familiar to object-oriented programmers including data hiding, inheritance, packages, and introspection.
  • Page 171: Recommended Uses

    Recommended uses Consider using ColdFusion components when doing the following: • Creating web services. (To create web services in ColdFusion, you must use components.) • Creating services that are callable by Flash clients. • Creating libraries of related functions, particularly if they must share data. •...
  • Page 172 cfinclude Custom Purpose Component Provide accessibility from Flash clients. Use built-in user security features. Encapsulate multiple related functions and properties. Create web services. Implement object-oriented coding methodologies. Chapter 8: Reusing Code in ColdFusion Pages...
  • Page 173: Chapter 9: Creating And Using Custom Cfml Tags

    CHAPTER 9 Creating and Using Custom CFML Tags This chapter describes how to create and use custom CFML tags that encapsulate common code. Contents Creating custom tags ............174 Passing data to custom tags .
  • Page 174: Creating Custom Tags

    Creating custom tags Custom tags let you extend CFML by adding your own tags to the ones supplied with ColdFusion. After you define a custom tag, you can use it on a ColdFusion page just as you would any of the standard CFML tags, such as cfquery cfoutput You use custom tags to encapsulate your application logic so that it can be referenced from any...
  • Page 175 View callingdate.cfm in your browser. This custom tag returns the current date in the format DD-MMM-YY. As you can see from this example, creating a custom tag in CFML is no different from writing any ColdFusion page. You can use all CFML constructs, as well as HTML. You are free to use any naming convention that fits your development practice.
  • Page 176 Attribute Description (continued) name Required if the attribute is not used. Use period-separated names to uniquely template identify a subdirectory under the CustomTags root directory. Example: identifies the file <cfmodule name="MyApp.GetUserOptions"> GetUserOptions.cfm in the CustomTags\MyApp directory under the ColdFusion root directory.
  • Page 177: Securing Custom Tags

    Accessing existing custom tags Before creating a custom tag in CFML, you should review the Custom Tag section of the ColdFusion Developer Exchange at http://devex.macromedia.com/developer/gallery/index.cfm. You might find a tag here that does what you want. Tags are grouped in several broad categories and are downloadable as freeware, shareware, or commercial software.
  • Page 178: Using Tag Attributes Summary

    Variables created within a custom tag are deleted when the processing of the tag terminates. Therefore, if you want to pass information back to the calling page, you must write that information back to the Caller scope of the calling page. You cannot access the custom tag’s variables outside the custom tag itself.
  • Page 179: Custom Tag Example With Attributes

    • Use the tag with a attribute at the top of a custom tag to test for and assign cfparam default defaults for optional attributes that are passed from a calling page. For example: <!--- The value of the variable Attributes.Name comes from the calling page. "...
  • Page 180: Passing Custom Tag Attributes Using Cfml Structures

    <!--- Create a variable called Doctor, make its value "Doctor " followed by the value of the variable Attributes.Name. Make its scope Caller so it is passed back to the calling page ---> <cfset Caller.Doctor="Doctor " & Attributes.Name> Save the page as getmd.cfm Open the file in your browser.
  • Page 181: Managing Custom Tags

    Custom tag processing reserves the attribute to refer to the structure attributecollection holding a collection of custom tag attributes. If does not refer to such a attributecollection collection, ColdFusion generates a template exception. The following example uses an attribute to pass two of four attributes: attributecollection <cfset zort=StructNew()>...
  • Page 182: Executing Custom Tags

    tag uses the following syntax: cfencode cfencode infile outfile [/r /q] [/h "message"] /v"2" The following table describes the options: Option Description infile The file you want to encode. The tag does not process an encoded file. cfencode outfile Path and filename of the output file. Warning: If you do not specify an output filename, a warning message asks if you want to continue, and the encoded file will overwrite the source file.
  • Page 183: Handling End Tags

    The following example accesses the variable of the structure from ExecutionMode thisTag within a custom tag: <cfif thisTag.ExecutionMode is 'start'> Handling end tags The examples of custom tags shown so far in this chapter all reference a custom tag using just a start tag, as in: <cf_date>...
  • Page 184 • Inactive Mode when the custom tag uses nested tags. For more information, see “Nesting custom tags” on page 186. If an end tag is not explicitly provided, ColdFusion invokes the custom tag page only once, in Start mode. A custom tag page named bold.cfm that makes text bold could be written as follows: <cfif thisTag.ExecutionMode is 'start'>...
  • Page 185: Processing Body Text

    Processing body text Body text is any text that you include between the start and end tags when you call a custom tag; for example: <cf_happybirthdayMessge name="Ellen Smith" birthDate="June, 8, 1993"> <P> Happy Birthday Ellen!</P> <P> May you have many more!</P> </cf_happybirthdayMessge>...
  • Page 186: Nesting Custom Tags

    The following table summarizes behavior: cfexit Method attribute value Location of cfexit call Behavior ExitTag (default) Base page Acts like cfabort ExecutionMode=start Continue after end tag ExecutionMode=end Continue after end tag ExitTemplate Base page Acts like cfabort ExecutionMode=start Continue from first child in body ExecutionMode=end Continue after end tag Loop...
  • Page 187: Passing Data Between Nested Custom Tags

    Nested custom tags operate through three modes of processing, which are exposed to the base tags through the variable thisTag.ExecutionMode • The start mode, in which the base tag is processed for the first time. • The inactive mode, in which sub tags and other code contained within the base tag are processed.
  • Page 188: High-Level Data Exchange

    Where is data accessible? Two custom tags can be related in a variety of ways in a page. Ancestor and descendant relationships are important because they relate to the order of tag nesting. A tag’s descendants are inactive while the page is executed; that is, the descendent tags have no instance data.
  • Page 189 The code accessing sub-tag attributes in the base tag could look like the following: <!--- Protect against no sub-tags ---> <cfparam Name='thisTag.assocAttribs' default=#arrayNew(1)#> <!--- Loop over the attribute sets of all sub tags ---> <cfloop index=i from=1 to=#arrayLen(thisTag.assocAttribs)#> <!--- Get the attributes structure ---> <cfset subAttribs = thisTag.assocAttribs[i]>...
  • Page 190 To create the second custom tag page: Create a ColdFusion page with the following content: <cfif thisTag.executionmode is 'start'> <!--- Get the tag context stack. The list will look something like "MYTAGNAME, CALLINGTAGNAME, ..." ---> <cfset ancestorlist = getbasetaglist()> <!--- Output your own name. You are the first entry in the context stack. --->...
  • Page 191: Chapter 10: Writing And Calling User-Defined Functions

    CHAPTER 10 Writing and Calling User-Defined Functions This chapter describes how to create and call user-defined functions (UDFs). Contents About user-defined functions ..........192 Calling user-defined functions .
  • Page 192: About User-Defined Functions

    About user-defined functions You can create user-defined functions, or UDFs (also known as custom functions), and use them in your application pages as you do standard ColdFusion functions. This lets you create a function for an algorithm or procedure that you use frequently, and then use the function wherever you need the procedure.
  • Page 193: Creating User-Defined Functions

    You might call the function with argument names, as follows: <cfoutput> Interest: #TotalInterest(principal=Form.Principal, annualPercent=Form.Percent, months=Form.Months)# </cfoutput> Creating user-defined functions You can use tags or CFScript to create a UDF. Each technique has advantages and disadvantages. Creating functions using CFScript You use the statement to define the function in CFScript.
  • Page 194: Rules For Function Definitions

    Rules for function definitions The following rules apply to functions that you define using CFScript or the tag: cffunction • The function name must be unique. It must be different from any existing variable, UDF, or built-in function name. • The function name must not start with the letters cf in any form.
  • Page 195 The following sections describe the general rules for using the Arguments scope as an array and a structure. For more information on using the Arguments scope in functions defined using CFScript, see “Using the Arguments scope in CFScript” on page 199.
  • Page 196 Using the Arguments scope as an array The following rules apply to referencing Arguments scope as an array: • If you call the function using unnamed arguments, the array index is the position of the argument in the function call. •...
  • Page 197 Using the Arguments scope as a structure The following rule applies when referencing Arguments scope as a structure: • Use the argument names as structure keys. For example, if your function definition includes a Principal argument, refer to the argument as Arguments.Principal. The following rules are also true, but avoid writing code that uses them.
  • Page 198: Defining Functions In Cfscript

    Defining functions in CFScript You define functions using CFScript in a manner similar to defining JavaScript functions. You can define multiple functions in a single CFScript block. Note: For more information on using CFScript, see Chapter 6, “Extending ColdFusion Pages with CFML Scripting,”...
  • Page 199 A simple CFScript example The following example function adds the two arguments and returns the result: <cfscript> function Sum(a,b) { var sum = a + b; return sum; </cfscript> In this example, a single line declares the function variable and uses an expression to set it to the value to be returned.
  • Page 200: Defining Functions Using The Cffunction Tag

    Note: Avoid referring to a required argument in the body of a function by both the argument name and its place in the Arguments scope array or structure, as this can be confusing and makes it easier to introduce errors. For more information on the Arguments scope, see “About the Arguments scope”...
  • Page 201 Attribute Description roles (Optional) A comma-delimited list of security roles that can invoke this method. If you omit this attribute, ColdFusion does not restrict user access to the function. If you use this attribute, the function executes only if the current user is logged in using the tag and is a member of one or more of the roles specified in cfloginuser...
  • Page 202: Calling Functions And Using Variables

    Using a CFML tag in a user-defined function The most important advantage of using the tag over defining a function in CFScript cffunction is that you can include CFML tags in the function. Thus, UDFs can encapsulate activities, such as database lookups, that require ColdFusion tags. Also, you can use the tag to display cfoutput output on the calling page with minimal coding.
  • Page 203: Referencing Caller Variables

    Referencing caller variables A function can use and change any variable that is available in the calling page, including variables in the caller’s Variables (local) scope, as if the function was part of the calling page. For example, if you know that the calling page has a local variable called Customer_name (and there is no function scope variable named Customer_name) the function can read and change the variable by referring to it as Customer_name or (using better coding practice) Variables.Customer_name.
  • Page 204: Using Arguments

    Using arguments Function arguments can have the same names, but different values, as variables in the caller. Avoid such uses for clarity, however. The following rules apply to argument persistence: • Because simple variable and array arguments are passed by value, their names and values exist only while the function executes.
  • Page 205: Defining The Function Using The Cffunction Tag

    Reviewing the code The following table describes the code: Code Description Starts the function definition. function TotalInterest(principal, TotalInterest annualPercent, Requires three variables: the principal amount, months) { the annual percentage rate, and the loan duration in months. Declares intermediate variables used in the Var years = 0;...
  • Page 206: Using Udfs Effectively

    Using UDFs effectively This section provides information that will help you use user-defined functions more effectively. Using Application.cfm and function include files Consider the following techniques for making your functions available to your ColdFusion pages: • If you consistently call a small number of UDFs, consider putting their definitions on the Application.cfm page.
  • Page 207 Selecting a function scope The following table describes the advantages and disadvantages of scopes that you might considering using for your functions: Scope Considerations Application Makes the function available across all invocations of the application. Unlike with functions defined in Application.cfm or included from other ColdFusion pages, all pages use the same in-memory copy of the function.
  • Page 208: Using The Request Scope For Static Variables And Constants

    Using the Request scope for static variables and constants This section describes how to partially break the rule described in the section “Referencing caller variables” on page 203. Here, the function defines variables in the Request scope. However, it is a specific solution to a specific issue, where the following circumstances exist: •...
  • Page 209: Identifying And Checking For Udfs

    For example, the following code defines a function to combine a single first name and last name to make a full name. It queries the CompanyInfo database to get the first and last names of all employees, then it uses a tag to loop through the query and call the function on each cfoutput row in the query.
  • Page 210: Using The Evaluate Function

    WriteOutput("MyFunc is not defined"); </cfscript> You do not surround the argument to in quotation marks, so you can use this IsCustomFunction function to determine if function arguments are themselves functions. Using the Evaluate function If your user-defined function uses the function on arguments that contain strings, you Evaluate must make sure that all variable names you use as arguments include the scope identifier.
  • Page 211 Passing arrays If you want your function to modify the caller’s copy of the array, the simplest solution is to pass the array to the function and return the changed array to the caller in the function return statement. In the caller, use same variable name in the function argument and return variable. The following example shows how to directly pass and return arrays.
  • Page 212: Using Recursion

    </br> <cfdump var="#arrayStruct#"> You must use the same structure element name for the array (in this case Array) in the calling page and the function. Using recursion A recursive function is a function that calls itself. Recursive functions are useful when a problem can be solved by an algorithm that repeats the same operation multiple times using the results of the preceding repetition.
  • Page 213 For example, the following variation on a “Hello world” function displays an error message if you do not enter a name in the form: <cfform method="POST" action="#CGI.script_name#"> <p>Enter your Name:&nbsp; <input name="name" type="text" hspace="30" maxlength="30"> <input type="Submit" name="submit" value="OK"> </cfform> <cfscript>...
  • Page 214 Providing status information In some cases, such as those where the function cannot provide a corrective action, the function cannot, or should not, handle the error directly. In these cases, your function can return information to the calling page. The calling page must handle the error information and act appropriately.
  • Page 215 Reviewing the code The following table describes the code that has been changed or added to the previous version of this example. For a description of the initial code, see “A User-defined function example” on page 204. Code Description The function now takes an additional argument, a status function TotalInterest(principal, structure.
  • Page 216 Code Description <cfif myInterest EQ -1> If the function returns -1, there must be an error. <cfoutput> Displays the message that the function placed in the ERROR: #status.errorMsg#<br> status.errorMsg structure key. </cfoutput> If the function does not return -1, it returns an interest <cfelse>...
  • Page 217 Generating exceptions in UDFs If you define your function using the tag, you can use the cffunction cfthrow cfrethrow tags to throw errors to the page that called the function. You can use this technique whenever your UDF identifies an error, instead of displaying a message or returning an error status. For example, the following code rewrites the example from “Providing status information”...
  • Page 218 Chapter 10: Writing and Calling User-Defined Functions...
  • Page 219: Chapter 11: Building And Using Coldfusion Components

    CFCs. It does not discuss CFC methodologies or provide information on designing applications for CFC use. For more information on creating applications that use CFCs, see the Macromedia website: www.macromedia.com.
  • Page 220: About Coldfusion Components

    CFCs support introspection; that is, they can provide information about themselves. If you display a component page directly in an HTML browser, inspect it in the ColdFusion and Macromedia Dreamweaver MX component browsers, or use the CFML...
  • Page 221 This chapter describes how to use CFC object-oriented features. It does not discuss general object-oriented programming concepts or methods. When to use CFCs You can use CFCs in several ways: • To develop structured, reusable ColdFusion code • To create web services •...
  • Page 222: Coldfusion Component Features And Use

    CFC methods. For more information on creating web services in ColdFusion, see Chapter 32, “Using Web Services,” on page 707. Creating Macromedia Flash Remoting elements Flash applications that use Flash Remoting MX can access CFC methods by using the CFC path as the service name in a NetServices method.
  • Page 223 Elements of a CFC A CFC definition has the following characteristics: • It is a single CFML page with a .cfc file extension. The component name is the same as the filename. For example, if the file is myComponent.cfc, the component name is myComponent.
  • Page 224: Using Coldfusion Components

    • Briefly discusses invoking CFC methods from outside ColdFusion • Discusses how to use ColdFusion MX and Macromedia Dreamweaver MX tools to learn about the CFCs on a server Specifying the CFC location When you instantiate or invoke a component, you can specify the component name only, or you can specify a qualified path.
  • Page 225: Instantiating Cfcs

    • If you invoke a CFC method remotely, using a specific URL, form field, Flash Remoting MX, or a web service invocation, ColdFusion looks in the specified path relative to the web root. For form fields and URLs specified directly on local web pages, ColdFusion also searches relative to the page directory.
  • Page 226: Invoking Cfc Methods With The Cfinvoke Tag

    Invoking CFC methods with the cfinvoke tag tag can invoke CFC methods transiently or invoke methods on a CFC instance. cfinvoke You can also use the tag to invoke CFC methods from within a CFC. cfinvoke Invoking component methods transiently using the cfinvoke tag In ColdFusion pages or components, the tag can invoke component methods without cfinvoke...
  • Page 227 To invoke a method of a component instance using the cfinvoke tag: Create a file named tellTime2.cfc with the following code: <cfcomponent> <cffunction name="getLocalTime" access="remote"> <cfreturn TimeFormat(now())> </cffunction> <cffunction name="getUTCTime" access="remote"> <cfscript> serverTime=now(); utcTime=GetTimeZoneInfo(); utcStruct=structNew(); utcStruct.Hour=DatePart("h", serverTime); utcStruct.Minute=DatePart("n", serverTime); utcStruct.Hour=utcStruct.Hour + utcTime.utcHourOffSet; utcStruct.Minute=utcStruct.Minute + utcTime.utcMinuteOffSet;...
  • Page 228 Using cfinvoke within the CFC definition You can use the tag to invoke a component method within the component definition; cfinvoke for example, to call a utility method that provides a service to other methods in the component. To use in this instance, do not create an instance or specify the component name in the cfinvoke tag, as the following example shows:...
  • Page 229: Using Components Directly In Cfscript And Cfml

    Passing parameters using the cfinvokeargument tag To pass parameters in the tag body, use the tag. Using the cfinvoke cfinvokeargument tag, for example, you can build conditional processing that passes a different cfinvokeargument parameter based on user input. The following example invokes the corpQuery component: <cfinvoke component="corpQuery"...
  • Page 230: Invoking Cfc Methods Using Forms And Urls

    In the example, the three CFScript statements do the following: function instantiates the tellTime CFC as tellTimeCFC. CreateObject The first function displays text followed by the results returned by the WriteOutput method of the tellTimeCFC instance. getLocalTime The second function displays text followed by the results returned by the WriteOutput method of the tellTimeCFC instance.
  • Page 231 For example: http://localhost:8500/ corpQuerySecure.cfc?method=getAuth&store=women&dept=shoes Note: To ensure data security, Macromedia strongly recommends that you not pass sensitive information over the web using URL strings. Potentially sensitive information includes all personal user information, including passwords, addresses, telephone numbers, and so on.
  • Page 232: Accessing Cfcs From Outside Coldfusion And Basic Html

    Query button, the web browser displays the results. Accessing CFCs from outside ColdFusion and basic HTML Macromedia Flash applications that use Flash Remoting MX can easily take advantage of ColdFusion components for business logic. Similarly, you can export CFCs so that any web application can access CFC methods as web services.
  • Page 233: Introspection: Getting Information About Components

    Introspection: getting information about components ColdFusion provides several ways to get information about components: • Requesting a component page from the browser • Using the ColdFusion component browser • Using the Dreamweaver component browser • Using the function GetMetaData Development teams can use the descriptions as up-to-date API reference information. Note: For information about how to include documentation in CFCs for display using introspection, “Documenting CFCs”...
  • Page 234 add (Addition Function) remote numeric add ( numeric arg1, numeric arg2 ) Adds integers or floating point numbers Output: enabled Parameters: arg1: numeric, optional, argument 1 - must be numeric arg2: numeric, optional, arg2 multiply* private numeric multiply ( numeric argA, numeric argB ) Output: enabled Parameters: argA: numeric, optional, argA...
  • Page 235: Building Coldfusion Components

    Using the GetMetaData function The CFML function returns a structure containing all the metadata of a CFC GetMetaData instance. This structure contains substantially more data about the CFC than shows, and cfdump includes the following information: • All attributes to the component tag, including any metadata-only attributes, plus the component path.
  • Page 236: Initializing Instance Data

    Initializing instance data Some components have instance data, data that persists as long as the component instance exists. For example, a shopping cart component might have instance data that includes the IDs and quantities of items the user puts in the shopping cart. Instance data is often shared by several methods that can create, delete, or modify the data.
  • Page 237 The following tag attributes are used only for CFCs: cffunction • attributes document the CFC; for more information, see displayname hint “Documenting CFCs” on page 240. • attribute controls access to the CFC; for more information , see “Using access access security”...
  • Page 238 Defining and using method parameters To define the component method parameter, use the tag in the cfargument cffunction body. To define multiple parameters, use multiple tags. You can create CFC methods cfargument that do not use tags, for example, if you use positional parameters in your methods. cfargument However, most CFC methods use the tag.
  • Page 239: Providing Results

    In the example, the attributes specify the following: cfargument • attributes define the parameter names name • attribute for the lastName argument specifies that the parameter must be a text type string. The attribute for the cost argument specifies that the parameter must be a type numeric value.
  • Page 240 Note: If a CFC is invoked using a URL or by submitting a form, ColdFusion MX returns the variable as a WDDX packet. ColdFusion MX cannot return methods to Flash. Therefore, a CFC that is invoked by Flash Remoting MX must not return the This scope. You can return values of all data types, including strings, integers, arrays, and structures.
  • Page 241 In this case, a ColdFusion page with the following code sets the MetaTypeInfo variable to Float: <cfobject component="mathCFC" name="MathFuncs"> <cfset MetaTypeInfo=GetMetadata(MathFuncs).MetaType> Note: Avoid using expressions in custom metadata attributes. Using expressions in metadata attributes can cause unpredictable behavior, because all metadata expressions are replaced by strings in the metadata structure returned from the GetMetadata function.
  • Page 242: Cfc Variables

    Establishing a descriptive naming convention is a good practice, especially if the components will be installed as part of a packaged application. CFC variables This section describes how CFCs use variables and interact with ColdFusion scopes. Note: Components also have a Super keyword that is sometimes called a scope. For information on the Super keyword, see “Using the Super keyword”...
  • Page 243 Example: sharing the Variables scope The following example shows how a CFC can change data in the calling page’s Variables scope. The callGreetMe.cfm page <cfset Variables.MyName="Oswaldo"> <cfobject component="greetMe" name="myGreetings"> <cfoutput> Before invoking the CFC Variables.Myname is #Variables.MyName#.<br> Calling GreetMe CFC. It returns: #myGreetings.hello(VScope=Variables)#<br> After invoking the CFC Variables.Myname is #Variables.MyName#.
  • Page 244: Structuring And Reusing Code

    You can access variables in the Arguments scope using structure notation (Arguments.variablename) or array notation (Arguments[1] or Arguments[“variablename”]). The Arguments scope does not last between calls to CFC methods. These variables are available to pages included by the function. Function local variables Variables declared with the Var keyword inside a tag or CFScript cffunction...
  • Page 245 • The Super keyword lets a component that overrides a base component method execute the original base component method. This technique lets your subclassed component override a method without losing the ability to call the original version of the method. The following sections describe these coding techniques in greater detail.
  • Page 246 Create a ColdFusion page with the following code, and save it as inherit.cfm in your web root directory: <cfinvoke component="corpQuery" method="getEmp" lastName="gilson"> <cfinvoke component="corpQuery" method="getLocalTime"> When you execute the inherit.cfm file, the component method executes even getLocalTime though it is invoked using the corpQuery component. Using component.cfc All CFCs automatically extend the ColdFusion WEB-INF\cftags\component.cfc component.
  • Page 247 Using component packages Components stored in the same directory are members of a component package. Component packages help prevent naming conflicts and facilitate easy component deployment. For example: • ColdFusion searches the current directory first for a CFC. If you put two components in a single directory as a package, and one component refers to the other with only the component name, not a qualified path, ColdFusion always searches the package directory first for the component.
  • Page 248: Building Secure Coldfusion Components

    For an example of an application that uses a component in a persistent scope, see the CFML/ HTML PetMarket application, available from the Macromedia Pet Market Blueprint Application page, www.macromedia.com/devnet/mx/blueprint/. The Session scope user CFC has properties with information about the user, such as name, telephone number, e-mail address, and billing and shipping addresses.
  • Page 249 Using role-based security If you specify a attribute in a tag, as the following example shows, only users roles cffunction who are logged in with one of the specified roles can execute the function: <cffunction name="foo" roles="admin,moderator"> When a user tries to invoke a method that he or she is not authorized to invoke, an exception is returned.
  • Page 250 Chapter 11: Building and Using ColdFusion Components...
  • Page 251: Chapter 12: Building Custom Cfxapi Tags

    CHAPTER 12 Building Custom CFXAPI Tags Sometimes, the best approach to application development is to develop elements of your application by building executables to run with ColdFusion. Perhaps the application requirements go beyond what is currently feasible in CFML. Perhaps you can improve application performance for certain types of processing.
  • Page 252: What Are Cfx Tags

    What are CFX tags? ColdFusion Extension (CFX) tags are custom tags written against the ColdFusion Extension Application Programming Interface. Generally, you create a CFX tag if you want to do something that is not possible in CFML, or if you want to improve the performance of a repetitive task. One common use of CFX tags is to incorporate existing application functionality into a ColdFusion application.
  • Page 253: Setting Up Your Development Environment To Develop Cfx Tags In Java

    (JDK) version 1.3.1 from Sun, to build Java CFX tags. You can download the JDK from Sun http://java.sun.com/j2se. Macromedia recommends that you use one of the commercial Java IDEs, such as Dreamweaver MX, that provide an integrated environment for development, debugging, project management, and access to documentation.
  • Page 254: Calling The Cfx Tag From A Coldfusion Page

    To create a Java CFX tag: Create a new source file in your editor with the following code: import com.allaire.cfx.* ; public class MyHelloColdFusion implements CustomTag { public void processRequest( Request request, Response response ) throws Exception { String strName = request.getAttribute( "NAME" ) ; response.write( "Hello, "...
  • Page 255: Processing Requests

    Save the file in a directory configured to serve ColdFusion pages. For example, you can save the file as C:\inetpub\wwwroot\cfdocs\testjavacfx.cfm on Windows or /home/docroot/cfdocs/ testjavacfx.cfm on UNIX. If you have not already done so, register the CFX tag in the ColdFusion MX Administrator (see “Registering CFX tags”...
  • Page 256: Loading Java Cfx Classes

    Response object The Response object is passed to the method of the CustomTag interface. The processRequest following table lists the methods of the Response object for writing output, generating queries, and setting variables within the calling page: Method Description write Outputs text to the calling page.
  • Page 257: Automatic Class Reloading

    Automatic class reloading You can determine how the server treats changed Java CFX class files by specifying the reload attribute when you use a CFX tag in your ColdFusion page. The following table describes the allowable values for the reload attribute: Value Description Auto...
  • Page 258 The Java implementation of ZipBrowser is as follows: import com.allaire.cfx.* ; import java.util.Hashtable ; import java.io.FileInputStream ; import java.util.zip.* ; public class ZipBrowser implements CustomTag { public void processRequest( Request request, Response response ) throws Exception { // validate that required attributes were passed if ( !request.attributeExists( "ARCHIVE"...
  • Page 259: Approaches To Debugging Java Cfx Tags

    Approaches to debugging Java CFX tags Java CFX tags are not stand-alone applications that run in their own process, like typical Java applications. Rather, they are created and invoked from an existing process. This makes debugging Java CFX tags more difficult, because you cannot use an interactive debugger to debug Java classes that have been loaded by another process.
  • Page 260: Using The Debugging Classes

    Debug your application by setting breakpoints, single stepping, displaying variables, or by performing other debugging actions. Using the debugging classes To develop and debug Java CFX tags in isolation from the ColdFusion, you use three special debugging classes that are included in the package.
  • Page 261: Developing Cfx Tags In C

    { "Lynne", "Teague", "Developer" } } DebugQuery query = new DebugQuery( "Employees", columns, data ) ; // create tag, process debugging request, and print results OutputQuery tag = new OutputQuery() ; DebugRequest request = new DebugRequest( attributes, query ) ; DebugResponse response = new DebugResponse() ;...
  • Page 262: Compiling C++ Cfx Tags

    Select Build > Start Debug > AttachProcess. Select jrunsvc.exe. Macromedia recommends that you shut down all other Java programs. Execute any ColdFusion page that calls the CFX tag. Select File > Open to open a file in VisualDev in which to set a breakpoint.
  • Page 263: Registering Cfx Tags

    Registering CFX tags To use a CFX tag in your ColdFusion applications, first register it in the Extensions, CFX Tags page in the ColdFusion MX Administrator. To register a C++ CFX tag: On the ColdFusion MX Administrator Server tab, select Extensions > CFX Tags to open the CFX Tags page.
  • Page 264 Chapter 12: Building Custom CFXAPI Tags...
  • Page 265 PART III Developing CFML Applications This part describes how to develop ColdFusion applications. It describes the elements of a ColdFusion application and how to structure an application, handle errors, use variables that are shared among pages, lock code segments, and secure your application. It also describes how to create a globalized application, and debug and troubleshoot application problems.
  • Page 267: Chapter 13: Designing And Optimizing A Coldfusion Application

    CHAPTER 13 Designing and Optimizing a ColdFusion Application This chapter describes the elements that make your ColdFusion pages into an effective Internet application. It provides an overview of application elements, describes how you can structure an application on your server, and provides detailed information on using the Application.cfm file. It also describes coding methods for optimizing application efficiency.
  • Page 268: About Applications

    About applications The term application can mean many things. An application can be as simple as a guest book or as sophisticated as a full Internet commerce system with catalog pages, shopping carts, and reporting. However, an application has a specific meaning in ColdFusion. A ColdFusion application consists of one or more ColdFusion pages that work together and share a common set of resources.
  • Page 269: Application-Level Settings And Functions

    “Mapping an application” on page 270. Note: For one example of an application framework, see “ColdFusion Methodologies for Content Management,” available at www.macromedia.com/v1/handlers/index.cfm?ID=20750&method=full. Application-level settings and functions ColdFusion processes the following two pages, if they are available, every time it processes any page in the application: •...
  • Page 270: Shared Variables

    For an overview of these elements, and information about how to choose among them, see Chapter 8, “Reusing Code in ColdFusion Pages,” on page 163. Shared variables The following ColdFusion variable scopes maintain data that lasts beyond the scope of the current HTTP request: Variable scope Description...
  • Page 271: Processing The Application.cfm And Onrequestend.cfm Pages

    Processing the Application.cfm and OnRequestEnd.cfm pages ColdFusion uses similar, but different, rules to locate and process the Application.cfm and OnRequestEnd.cfm pages. Processing the Application.cfm page When ColdFusion receives a request for an application page, it searches the page's directory for a file named Application.cfm.
  • Page 272: Creating The Application.cfm Page

    You can divide your logical web application into multiple ColdFusion applications by using multiple Application.cfm pages with different application names. Alternatively, you can use multiple Application.cfm pages that specify the same application name, but have different common code, for different subsections of your application. The directory trees in the following figure show two approaches to implementing an application framework: •...
  • Page 273: Naming The Application

    • Login processing • Application-specific error handling Naming the application In ColdFusion, you define an application by giving it a name using the tag. By cfapplication using a specific application name in a tag, you define a set of pages as part of the cfapplication same logical application.
  • Page 274: Defining Page Processing Settings

    Defining page processing settings tag lets you specify the following page processing attributes that you might want cfsetting to apply to all pages in your application: Attribute showDebugOutput Specifies whether to show debugging output. This setting cannot enable debugging if it is disabled in the ColdFusion MX Administrator. However, this option can ensure that debugging output is not displayed, even if the Administrator enables it.
  • Page 275: Example: An Application.cfm Page

    You can also use the Application.cfm page to develop more sophisticated application-wide error- handling techniques, including error-handling methods that provide specific messages or use structured error-handling techniques. For more information on error pages and error handling, see Chapter 14, “Handling Errors,” on page 285.
  • Page 276 <cfset session.pagesHit=session.pagesHit+1> </cfif> </cflock> <!--- Set Application-specific Variables scope variables. ---> <cfset mainpage = "default.cfm"> <cfset current_page = "#cgi.path_info#?#cgi.query_string#"> <!--- Include a file containing user-defined functions called throughout the application ---> <cfinclude template="commonfiles/productudfs.cfm"> Reviewing the code The following table describes the code and its function: Code Description <cfapplication name="Products"...
  • Page 277: Optimizing Coldfusion Applications

    Chapter 18, “Debugging and Troubleshooting Applications,” on page 389. For additional information on optimizing ColdFusion, see the Macromedia ColdFusion support center at www.macromedia.com/support/coldfusion. Caching ColdFusion pages that change infrequently Some ColdFusion pages produce output that changes infrequently. For example, you might have an application that extracts a vendor list from a database or produces a quarterly results summary.
  • Page 278: Caching Parts Of Coldfusion Pages

    • The directory on the server in which to store the cached pages. The default directory is cf_root/ cache. It is a good practice to create a separate cache directory for each application. Doing so can prevent the action from inappropriately flushing more than one cfcache flush application’s caches at a time.
  • Page 279 tag saves the results of processing the tag body in a variable. For example, if cfsavecontent the body of the tag contains a tag that runs an executable program cfsavecontent cfexecute that displays data, the variable saves the output. You can use the tag to cache infrequently changing output in a shared scope cfsavecontent variable.
  • Page 280 </tr> </cfoutput> </table> </cfsavecontent> <!--- Save the results in the Application scope ---> <cflock scope="Application" type="Exclusive" timeout=30> <cfset Application.productCache = ProductCache> </cflock> </cfif> <!--- Use the Application scope variable to display the sale items ---> <cflock scope="application" timeout="20" type="readonly"> <cfoutput>#Application.ProductCache#</cfoutput> </cflock>...
  • Page 281: Optimizing Database Use

    Code Description <cflock scope="Application" Inside an Exclusive tag, saves the contents of cflock type="Exclusive" the local variable in the Application ProductCache timeout=30> scope variable Application.productCache. <cfset Application.productCache = productcache> </cflock> Ends the code that executes only if the </cfif> Application.productCache variable does not exist. Inside a tag, displays the contents of the <cflock scope="application"...
  • Page 282 <cfprocparam type = "OUT"CFSQLType = CF_SQL_DATE variable = FOO dbVarName = @param2> <!--- Close the cfstoredproc tag ---> </cfstoredproc> <cfoutput> The output param value: '#foo#'<br> </cfoutput> <h3>The Results Information</h3> <cfoutput query = RS1> #name#,#DATE_COL#<br> </cfoutput> <br> <cfoutput> <hr> Record Count: #RS1.recordCount#<br> Columns: #RS1.columnList#<br>...
  • Page 283 Code Description <cfprocparam type = "IN" Specifies two parameters for the stored CFSQLType = CF_SQL_INTEGER procedure, an input parameter and an output value = "1" dbVarName = @param1> parameter. Sets the input parameter to 1 and <cfprocparam type = "OUT" CFSQLType = the ColdFusion variable that gets the output CF_SQL_DATE to FOO.
  • Page 284: Providing Visual Feedback To The User

    You can also use the tag to create a progress bar. For information on this technique, see cfflush the technical article “Understanding Progress Meters in ColdFusion 5” at www.macromedia.com/ v1/handlers/index.cfm?id=21216&method=full. (Although this article was written for ColdFusion 5, it also applies to ColdFusion MX.)
  • Page 285: Chapter 14: Handling Errors

    CHAPTER 14 Handling Errors ColdFusion includes many tools and techniques for responding to errors that your application encounters. These tools include error handling mechanisms and error logging tools. This chapter describes these tools and how to use them. This chapter does not discuss techniques for preventing errors, including methods for specifying user input validation.
  • Page 286: About Error Handling In Coldfusion

    About error handling in ColdFusion By default, ColdFusion generates its own error messages when it encounters errors. In addition, it provides a variety of tools and techniques for you to customize error information and handle errors when they occur. You can use any of the following error-management techniques: •...
  • Page 287: Coldfusion Error Types

    Errors such as validation errors, for which the application cannot continue processing the request, but can provide an error-specific response, can also be considered recoverable. For example, an error that occurs when a user enters text where a number is required can be considered recoverable, because the application can recognize the error and redisplay the data field with a message providing information about the error’s cause and telling the user to reenter the data.
  • Page 288: About Coldfusion Exceptions

    About ColdFusion exceptions You can categorize ColdFusion exceptions in two ways: • When they occur • Their type When exceptions occur ColdFusion errors can occur at two times, when the CFML is compiled into Java and when the resulting Java executes, called runtime exceptions. Compiler exceptions Compiler exceptions are programming errors that ColdFusion identifies when it compiles CFML into Java.
  • Page 289 Basic exception types All ColdFusion exceptions except for custom exceptions belong to a basic type category. These types consist of a broadly-defined categorization of ColdFusion exceptions. The following table describes the basic exception types: Type Type name Description Database failures Database Failed database operations, such as failed SQL statements, ODBC problems, and so on.
  • Page 290: How Coldfusion Handles Errors

    Advanced exception types The Advanced exceptions consist of a set of specific, narrow exception types. These types are supported in ColdFusion MX for backward-compatibility. For a list of advanced exception types, “Advanced Exception types” Chapter 2, “ColdFusion Tags,” in CFML Reference. Java exception classes Every ColdFusion exception belongs to, and can be identified by, a specific Java exception class in addition to its basic, custom, or advanced type.
  • Page 291: Error Messages And The Standard Error Format

    If the Administrator Settings Site-wide Error Handler field specifies an error handler page, ColdFusion displays the specified error page. Otherwise, ColdFusion reports the error using the standard error message format described “Error messages and the standard error format” on page 291.
  • Page 292: Determining Error-Handling Strategies

    Stack trace The Java stack at the time of the exception, including the specific Java class of the exception. This section can be helpful if you must contact Macromedia Technical Support. The stack trace is collapsed by default. Click the heading to display the trace.
  • Page 293: Handling Compiler Exceptions

    Handling compiler exceptions You cannot handle compiler exceptions directly on the page where they occur, because the exception is caught before ColdFusion starts running the page code. You should fix all compiler exceptions as part of the development process. Use the reported error message and the code debugging techniques discussed in Chapter 18, “Debugging and Troubleshooting Applications,”...
  • Page 294: Specifying Custom Error Messages With Cferror

    Specifying custom error messages with cferror Custom error pages let you control the error information that users see. You can specify custom error pages for different types of errors and handle different types of errors in different ways. For example, you can create specific pages to handle errors that could be recoverable, such as request time-outs.
  • Page 295: Creating An Error Application Page

    The following tag specifies a custom error page for exceptions that occur in locking code cferror and informs the error page of the of an e-mail address it can use to send a notification each time this type of error occurs: <cferror type = "exception"...
  • Page 296 The following table describes the variables available on error pages: Error page type Error variable Description Validation error.invalidFields Unordered list of validation errors that occurred. This includes any text that you specify in the value attribute or a hidden tag used to validate form input. error.validationHeader Text for the header of the default validation message.
  • Page 297: Logging Errors With The Cflog Tag

    Example of a request error page The following example shows a custom error page for a request error: <html> <head> <title>Products - Error</title> </head> <body> <h2>Sorry</h2> <p>An error occurred when you requested this page.</p> <p>Please send e-mail with the following information to #error.mailTo# to report this error.</p>...
  • Page 298 tag lets you specify the following information: cflog • A custom file or standard ColdFusion log file in which to write the message. • Text to write to the log file. This can include the values of all available error and cfcatch variables.
  • Page 299: Handling Runtime Exceptions With Coldfusion Tags

    Diagnostics: Cannot find CFML template for custom tag testCase. Cannot find CFML template for custom tag testCase. ColdFusion attempted looking in the tree of installed custom tags but did not find a custom tag with this name." The text consists of a comma delimited list of the following entries: •...
  • Page 300 For example, you can use to catch errors in code that enters data from a user registration cftry form to a database. The code could do the following: cfcatch Retry the query, so the operation succeeds if the resource was only temporarily unavailable. If the retries fail: Display a custom message to the user Post the data to an email address so the data could be entered by company staff after the...
  • Page 301 If an exception occurs in the first level of exception-handling code, the inner block cfcatch can catch and handle it. (An exception in a block cannot be handled by cfcatch cfcatch blocks at the same level as that block.) • ColdFusion always responds to the latest exception that gets raised.
  • Page 302 Property variable Description cfcatch.RootCause The Java servlet exception reported by the JVM as the cause of the "root cause" of the exception. An array of structures structure containing information for each tag in the cfcatch.TagContext tag stack The tag stack consists of each tag that is currently open. The exception’s type, returned as a string.
  • Page 303: Using Cftry: An Example

    Property variable Description cfcatch.Sql The SQL statement sent to the data source. The error message as reported by the database driver. cfcatch.queryError If the query uses the tag, query parameter name- cfcatch.where cfqueryparam value pairs. Expression exceptions The following variable is only available for Expression exceptions: Property variable Description An internal expression error number, valid only when...
  • Page 304 </cfquery> <html> <head> <title>Test cftry/cfcatch</title> </head> <body> <cfinclude template="includeme.cfm"> <cfoutput query="test"> <p>Department: #Dept_ID#<br> Last Name: #LastName#<br> First Name: #FirstName#</p> </cfoutput> <!--- Use cfcatch to test for missing included files. ---> <!--- Print Message and Detail error messages. ---> <!--- Block executes only if a MissingInclude exception is thrown. ---> <cfcatch type="MissingInclude">...
  • Page 305 Use the following procedure to test the code. Testing the code: Make sure there is no includeme.cfm file and display the page. The cfcatch block displays the error. type="MissingInclude" Create a nonempty includeme.cfm file and display the page. If your database is configured properly, you should see an employee entry and not get any error.
  • Page 306 Reviewing the code The following table describes the code: Code Description Initializes the employee ID to a valid value. An <cfset EmpID=3> application would get the value from a form or <cfparam name="errorCaught" default=""> other source. Sets the default variable value to errorCaught the empty string (to indicate no error was caught).
  • Page 307: Using The Cfthrow Tag

    Code Description Handles exceptions thrown when accessing a <cfcatch type="Database"> database. <h1>Database Error</h1> Displays variables, including the cfcatch <cfoutput> ColdFusion basic error message, the error code <ul> and SQL state reported by the databases <li><b>Message:</b> #cfcatch.Message# system, and the detailed error message. <li><b>Native error code:</b>...
  • Page 308 Catching and displaying thrown errors tag catches a custom exception when you use any of the following values for the cfcatch attribute: cfcatch type • The custom exception type specified in the tag. cfthrow • A custom exception type that hierarchically matches the initial portion of the type specified in tag.
  • Page 309: Using The Cfrethrow Tag

    For example, on a form action page or custom tag used to set a password, the application can determine whether the password entered is a minimum length, or contains both letters and number, and throw an error with a message that indicates the password rule that was broken. The block handles the error and tells the user how to correct the problem.
  • Page 310 • The custom tag finds all records in the CompanyInfo database with a matching last name, and returns the results in a Caller variable. If it fails to connect with the main database, it tries a backup database. The calling page The calling page represents a section from a larger application page.
  • Page 311 <!--- Try to query the main database and set a caller variable to the result - --> <cfquery Name = "getUser" DataSource="CompanyInfo"> SELECT * FROM Employee WHERE LastName = ’#attributes.EmpName#’ </cfquery> <cfset caller.getEmpsResult = getuser> <!--- If the query failed with a database error, check the error type to see if the database was found --->...
  • Page 312 </cfoutput> <cfexit method = "exittag"> </cfcatch> </cftry> </cfif> Reviewing the code The following table describes the code: Code Description Makes sure the calling page specified an <cfif NOT IsDefined("attributes.EmpName")> <cfthrow Type="myApp.getUser.noEmpName" attribute. If not, throws a custom error EmpName message = "Last Name was not supplied to that indicates the problem and exits the tag.
  • Page 313 Code Description <cfcatch type = "Any"> In the second try block, catches any errors other <cfrethrow> exceptions and rethrows them up to the </cfcatch> outermost try block. </cftry> Ends the second try block. In the outermost try block, handles any <cfcatch Type = "Any">...
  • Page 314 Chapter 14: Handling Errors...
  • Page 315: Chapter 15: Using Persistent Data And Locking

    CHAPTER 15 Using Persistent Data and Locking ColdFusion MX provides several variable scopes in which data persists past the life of a single request. These are the Client, Application, Session, and Server scopes. These scopes let you save data over time and share data between pages and even applications. (This chapter refers to these scopes as persistent scopes.) In particular, you can use the Client and Session scopes to maintain information about a user across multiple requests.
  • Page 316: About Persistent Scope Variables

    About persistent scope variables ColdFusion MX provides four variable scopes, described in the following table, that let you maintain data that must be available to multiple applications or users or must last beyond the scope of the current request. Variable scope Description Client Contains variables that are available for a single client browser over multiple...
  • Page 317: Coldfusion Persistent Variable Issues

    Note: Although you can use the StructClear function to clear your data from the Server scope, the function does not delete the names of the variables, only their values, and it does not delete the contents of the Server.os and Server.ColdFusion structures. Using the function to clear StructClear the Session, or Application scope clears the entire scope, including the built-in variables.
  • Page 318: Managing The Client State

    Managing the client state Because the web is a stateless system, each connection that a browser makes to a web server is unique to the web server. However, many applications must keep track of users as they move through the pages within the application. This is the definition of client state management. ColdFusion provides tools to maintain the client state by seamlessly tracking variables associated with a browser as the user moves from page to page within the application.
  • Page 319: Maintaining Client Identity

    Maintaining client identity Because the web is a stateless system, client management requires some method for maintaining knowledge of the client between requests. Normally you do this using cookies, but you can also do it by passing information between application pages. The following sections describe how ColdFusion maintains client identity in a variety of configurations and environments, and discuss issues that can arise with client state management.
  • Page 320 To use ColdFusion client or session variables without using cookies, each page must pass the CFID values to any page that it calls as part of the request URL. If a page contains any CFToken HTML links, tags, tags, or tags the tags must pass the href a= cflocation...
  • Page 321: Configuring And Using Client Variables

    CFID CFToken variables used to identify the client to ColdFusion are stored at the domain level (for example, .macromedia.com). If variable combinations already exist on each host in the CFID CFToken cluster, ColdFusion migrates the host-level variables on each cluster member to the single, common domain-level variable.
  • Page 322 If your database does not support SQL creation of tables, or if you are using the ODBC socket [Macromedia] driver to access your database, you must use your database tool to create the client variable tables. Create the CDATA and CGLOBAL tables.
  • Page 323: Using Client Variables

    The CDATA table must have the following columns: Column Data type cfid CHAR(64), TEXT, VARCHAR, or any data type capable of taking variable length strings up to 64 characters CHAR(64), TEXT, VARCHAR, or any data type capable of taking variable length strings up to 64 characters data MEMO, LONGTEXT, LONG VARCHAR, CLOB, or any data type capable of...
  • Page 324 Creating a client variable To create a client variable and set its value, use the tag and use the Client scope cfset cfparam identifier as a variable prefix; for example: <cfset Client.FavoriteColor="Red"> After you set a client variable this way, it is available for use within any page in your application that is accessed by the client for whom the variable is set.
  • Page 325 You use the , and variables if your application Client.CFID Client.CFToken Client.URLToken supports browsers that do not allow cookies. For more information on supporting browsers that do not allow cookies, see “Using client and session variables without cookies” on page 319.
  • Page 326: Configuring And Using Session Variables

    The system Registry lets you export and import Registry entries. To export your client variable database from the Registry in Windows: Open the Registry editor. Find and select the following key: HKEY_LOCAL_MACHINE\SOFTWARE\Macromedia\ColdFusion\CurrentVersion\ Clients On the Registry menu, click Export Registry File. Enter a name for the Registry file.
  • Page 327: Configuring And Enabling Session Variables

    ColdFusion and J2EE session management The ColdFusion server can use either of the following types of session management: • ColdFusion session management • J2EE servlet session management ColdFusion session management uses the same client identification method as ColdFusion client management. J2EE session management provides the following advantages over ColdFusion session management: •...
  • Page 328: Storing Session Data In Session Variables

    Enabling session variables in your application You must also enable session variables in the tag in your Application.cfm file. Do cfapplication the following in the Application.cfm file to enable session variables: • sessionManagement="Yes" • Use the attribute to specify the application's name. name •...
  • Page 329: Getting A List Of Session Variables

    <cflock timeout=20 scope="Session" type="Exclusive"> <cfset StructDelete(Session, "ShoppingCartItems")> </cflock> Note: If you set session variables on a CFML template that uses the tag, ColdFusion cflocation might not set the variables. For more information, see Macromedia TechNote 22712 at www.macromedia.com/v1/Handlers/index.cfm?ID=22712&Method=Full. Configuring and using session variables...
  • Page 330: Accessing And Changing Session Variables

    Accessing and changing session variables You use the same syntax to access a session variable as for other types of variables. However, you must lock any code that accesses or changes session variables. For example, to display the number of items in a user’s shopping cart, use favorite color that has been set for a specific user, for example, use the following code: <cflock timeout=20 scope="Session"...
  • Page 331: Configuring And Enabling Application Variables

    Configuring and enabling application variables To use application variables, do the following: • Ensure that they are enabled in the ColdFusion MX Administrator. (They are enabled by default.) • Specify the application name in the tag for the current page. cfapplication Note: ColdFusion supports unnamed applications for compatibility with J2EE applications.
  • Page 332: Using Server Variables

    Because each Application scope variable is shared in memory by all requests in the application, these variables can become bottlenecks if used inappropriately. Whenever a request is reading or writing an Application scope variable, any other requests that use the variable must wait until the code accessing the variable completes.
  • Page 333: Locking Code With Cflock

    Variable Description Server.ColdFusion.SerialNumber The serial number assigned to this server installation. Server.ColdFusion.SupportedLocales The locales, such as English (US) and Spanish (Standard), supported by the server. Server.OS.AdditionalInformation Additional information provided by the operating system, such as the Service Pack number. Server.OS.arch The processor architecture, such as x86 for Intel Pentium processors.
  • Page 334: Sample Locking Scenarios

    Sample locking scenarios The following examples present scenarios in which you need to lock ColdFusion code. These scenarios show only two of the circumstances where locking is vital. Reading and writing a shared variable If you have an application-wide value, such as a counter of the total number of tickets sold, you might have code such as the following on a login page: <cfset Application.totalTicketsSold = Application.totalTicketsSold + ticketOrder>...
  • Page 335: Using The Cflock Tag With Write-Once Variables

    Order 2 exits the lock tag, which frees the Application scope lock. ColdFusion can process another order. The resulting Application.totalTickesSold value is now correct. Ensuring consistency of multiple variables Often an application sets multiple shared scope variables at one time, such as a number of values submitted by a user on a form.
  • Page 336 Lock types tag offers two modes of locking, specified by the attribute: cflock type • Exclusive locks (the default lock type) Allow only one request to process the locked code. No other requests can run code inside the tag while a request has an exclusive lock. Enclose all code that creates or modifies session,application, or server variables in exclusive tags.
  • Page 337 If multiple code sections share a lock, the following rules apply: • When code is running in a tag block with the attribute set to , code in cflock type Exclusive tag blocks with the same attribute is not allowed to run. They wait until the cflock scope code with the exclusive lock completes.
  • Page 338: Considering Lock Granularity

    <cflock scope="Session" timeout="5" type="exclusive"> <cfset Session.qUser = Variables.qUser> </cflock> Considering lock granularity When you design your locking strategy, consider whether you should have multiple locks containing small amounts of code or few locks with larger blocks of code. There is no simple rule for making such a decision, and you might do performance testing with different options to help make your decision.
  • Page 339 Note: You can skip any pair of lock and unlock steps in the preceding list if you do not need to lock a particular scope. For example, you can omit steps 3 and 4 if you do not need to lock the Server scope.
  • Page 340: Examples Of Cflock

    <!--- Do initializations ---> <cfset APPLICATION.varible1 = someValue > <!--- Set the Application scope initialization flag ---> <cfset APPLICATION.initialized = "yes"> </cfif> </cflock> </cfif> Examples of cflock The following examples show how to use blocks in a variety of situations. cflock Example with application, server, and session variables This example shows how you can use...
  • Page 341 <!--- Always display the number of turtlenecks sold ---> <cflock scope="Application" timeout="10" type ="ReadOnly"> <cfoutput> E-Turtleneck is proud to say that we have sold #Application.number# turtlenecks to date. </cfoutput> </cflock> The remaining sample code could appear inside the application page where customers place orders: <html>...
  • Page 342 <table cellspacing="2" cellpadding="2" border="0"> <tr> <td>Select a color.</td> <td><select type="Text" name="color"> <option>red <option>white <option>blue <option>turquoise <option>black <option>forest green </select> </td> </tr> <tr> <td>Select a size.</td> <td><select type="Text" name="size"> <option>small <option>medium <option>large <option>xlarge </select> </td> </tr> <tr> <td></td> <td><input type="Submit" name="submit" value="Submit"> </td>...
  • Page 343 Example of protecting ColdFusion extensions The following example shows how you can build a custom tag wrapper around a CFX tag that is not thread-safe. The wrapper forwards attributes to the non-thread-safe CFX tag that is used inside a tag. cflock <cfparam name="Attributes.AttributeOne"...
  • Page 344 Chapter 15: Using Persistent Data and Locking...
  • Page 345: Chapter 16: Securing Applications

    CHAPTER 16 Securing Applications ColdFusion MX has two major security features: • Sandbox security (ColdFusion MX Enterprise) or resource security (ColdFusion MX Standard), where security restricts access to specific resources, such as tags and files. • User security, which depends on a user identity. This chapter provides an overview of ColdFusion security.
  • Page 346: Coldfusion Security Features

    • Development ColdFusion MX Administrator is protected by a password. Additionally, you can specify a password for access to data sources from Macromedia Dreamweaver MX. For more information on configuring Administrator security passwords, see the ColdFusion MX Administrator online Help.
  • Page 347: Resource Control

    Resource control ColdFusion lets you control access to the following resources: Resource Description Data sources Enables access to specified data sources. CF tags Prevents pages from using CFML tags that access external resources. You can prevent pages in the directory from using any or all of the following tags: cfcollection, cfcontent, cfcookie, cfdirectory, cfexecute, cffile, cfftp, cfgridupdate, cfhttp, cfhttpparam, cfindex, cfinsert, cfinvoke, cfldap, cflog, cfmail, cfobject, cfobjectcache, cfpop, cfquery,...
  • Page 348: About User Security

    About user security User security lets your application use security rules to determine what it displays. It has two elements: • Authentication Ensures that a valid user is logged-in, based on an ID and password provided by the user. ColdFusion (or, in some cases if you use web server authentication, the web server) maintains the user ID information while the user is logged-in.
  • Page 349 About user security...
  • Page 350: Authenticating Users

    If you do not use SSL (Secure Sockets Layer) for all page transactions, the user ID and password are not protected from unauthorized access. Note: Macromedia DreamWeaver MX and Studio MX do not support NTLM security with RDS. Therefore, you cannot use RDS with these applications if the ColdFusion RDS servlet (cf_root/ CFIDE/main/ide.cfm) is in a directory that is protected using NTLM security.
  • Page 351 About application authentication With application authentication, you do not rely on the web server to enforce application security. The application performs all user authentication and authorization. The application displays a login page, checks the user’s identity and login against its own authorization store, such as an LDAP directory or database, and logs the user into ColdFusion using the tag.
  • Page 352: Using Coldfusion Security Tags And Functions

    If you do not enable the Session scope, the authentication information is not kept in a persistent scope. Instead, the detailed login information is put in a memory-only cookie (CFAUTHORIZATION_applicationName) with a base64-encoded string that contains the user name, password, and application name. The client sends this cookie to the web server each time it makes a page request while the user is logged-in.
  • Page 353: Using The Cflogin Tag

    Submission of a form that contains input fields with the names j_username j_password • A message from the Macromedia Flash Remoting gatewayConnection object that has the method set. setCredentials • A request that uses CFHTTP Basic authentication, and therefore includes an Authorization header with the username and password.
  • Page 354: Logging A User In Using Flash Remoting

    Logging a user in using Flash Remoting If you are developing a Rich Internet Application with Macromedia Flash, you use the ActionScript method to send login information to ColdFusion. Your Flash...
  • Page 355: Security Scenarios

    Security scenarios The following sections provide two detailed security scenarios. The first scenario uses the web server to perform the authentication against its user and password database. The second scenario uses ColdFusion for all authentication and authorization. A web server authentication security scenario An application that uses web server authentication might work as follows.
  • Page 356: An Application Authentication Security Scenario

    An application authentication security scenario An application that does its own authentication might work as follows. The example in “Application-based user security example” on page 360 implements this scenario. Whenever ColdFusion receives a request for a ColdFusion page, it runs the contents of the Application.cfm page before it runs the requested page.
  • Page 357 Security scenarios...
  • Page 358: Implementing User Security

    Implementing user security The following sections provide several examples of ways to implement security using basic authentication and application authentication. Web-server–based authentication user security example The example in this section shows how you might implement user security using web-server– based basic authentication and two roles, user and administrator. This example has two ColdFusion pages: •...
  • Page 359 The following table describes the CFML code in Application.cfm and its function: Code Description Identifies the application. The login information on <cfapplication name="Orders" this page only applies to this application. Executes if there is no logged-in user. <cflogin> <cfif IsDefined( "cflogin" )> Makes sure the user is correctly logged-in by the <cfif cflogin.name eq "admin">...
  • Page 360: Application-Based User Security Example

    Reviewing the code The following table describes the securitytest.cfm page CFML code and its function: Code Description User is already logged-in by <cfoutput> <h2>Welcome #GetAuthUser()#!</h2> Application.cfm. Displays a welcome </cfoutput> message that includes the user’s login ID. ALL Logged-in Users see this message.<br> Displays this message in all cases.
  • Page 361 Example: Application.cfm The Application.cfm page consists of the following: <cfapplication name="Orders" sessionmanagement="Yes" loginStorage=”Session”> <cfif IsDefined("Form.logout")> <cflogout> </cfif> <cflogin> <cfif NOT IsDefined("cflogin")> <cfinclude template="loginform.cfm"> <cfabort> <cfelse> <cfif cflogin.name IS "" OR cflogin.password IS ""> <cfoutput> <H2>You must enter text in both the User Name and Password fields</H2> </cfoutput>...
  • Page 362 The following table describes the CFML code in Application.cfm and its function: Code Description Identifies the application, enables the <cfapplication name="Orders" sessionmanagement="Yes" Session scope, and enables storing login > loginStorage=”Session” information in the Session scope. If the user just submitted the logout form, <cfif IsDefined("Form.logout")>...
  • Page 363 Code Description </cfif> Ends the loginquery.Roles test code. </cfif> Ends the form entry empty value test. </cfif> Ends the form entry existence test. </cflogin> Ends the tag body. cflogin If a user is logged-in, displays the Logout <cfif GetAuthUser() NEQ ""> <cfoutput>...
  • Page 364 Reviewing the code The following table describes the loginform.cfm page CFML code and its function: Code Description Displays the login form. <H2>Please Log In</H2> <cfoutput> <form Constructs the form attribute from CGI action action="#CGI.script_name#?#CGI. variables, with a ? character preceding the query query_string#"...
  • Page 365 if (IsUserInRole("Contractor")) WriteOutput("Contractors see this message.<br><br>"); </cfscript> </body> </html> Reviewing the code The following table describes the securitytest.cfm page CFML code and its function: Code Description Displays a welcome message that <cfoutput> <h2>Welcome #GetAuthUser()#!</h2> includes the user’s login ID. </cfoutput> ALL Logged-in Users see this message.<br>...
  • Page 366: Using An Ldap Directory For Security Information

    Using an LDAP Directory for security information LDAP directories are often used to store security information. The following example of an Application.cfm page with a tag checks an LDAP directory to authenticate the user and cflogin retrieve the user’s roles. This example queries the LDAP directory twice, first as the directory manager, then with the user’s identity: •...
  • Page 367 <cfoutput> <script> alert("UID for #cflogin.name# not found"); </script> </cfoutput> <cfabort> </cfif> <!--- Pass the user's DN and password to see if the user authenticates, and get the user’s roles ---> <cftry> <cfldap action="QUERY" name="auth" attributes="cn" start="ou=Product Support,dc=Allaire,dc=com" scope="SUBTREE" server="#LDAP_server#" port="#LDAP_port#" filter="(&(objectClass=groupOfUniqueNames)(uniquemember= #userSearch.dn#))"...
  • Page 368 Reviewing the code The following table describes the code and its function. Comments and some tab characters have been removed for brevity. Code Description <cflogin> Starts the cflogin tag body. Sets several of <cfif isDefined("cflogin")> the values used as attributes in the cfldap <cfset LDAP_root = "o=mycompany.com">...
  • Page 369 Code Description <cfcatch type="any"> Catches any exceptions. <cfif FindNoCase("Invalid credentials", Tests to see if the error information includes cfcatch.detail)> the string "invalid credentials", which indicates <cfoutput> that either the dn or password is invalid. If so, <script>alert("User ID or Password displays a dialog box with an error message invalid for user: #cflogin.name#") indicating the problem.
  • Page 370 Chapter 16: Securing Applications...
  • Page 371: Chapter 17: Developing Globalized Applications

    CHAPTER 17 Developing Globalized Applications ColdFusion MX lets you develop dynamic applications for the Internet. Many ColdFusion applications are accessed by users from different countries and geographical areas. One design detail that you must consider is the globalization of your application so that you can best serve customers in different areas.
  • Page 372: Introduction To Globalization

    Introduction to globalization Globalization lets you create applications for all of your customers in all the languages that you support. In some cases, globalization can let you accept data input using a different character set than the one you used to implement your application. For example, you can create a website in English that lets customers submit form data in Japanese.
  • Page 373: Importance Of Globalization In Coldfusion Applications

    Importance of globalization in ColdFusion applications The Internet has no country boundaries. Customers can access websites from anywhere in the world, at any time, or on any date. Unless you want to lock your customers into using a single language, such as English, to access your site, you should consider globalization issues. One reason to globalize your applications is to avoid errors and confusion for your customers.
  • Page 374: About Character Encodings

    A locale identifies the exact language and cultural settings for a user. The locale controls how dates and currencies are formatted, how to display time, and how to display numeric data. For example, the locale English (US) determines that a currency value displays as: $100,000.00 while a locale of Portuguese (Brazilian) displays the currency as: R$ 100.000...
  • Page 375: The Java Unicode Character Encoding

    Computers often must convert between character encodings. In particular, the character encodings most commonly used on the Internet are not used by Java or Windows. Character sets used on the Internet are typically single-byte or multiple-byte (including DBCS character sets that allow single-byte characters).
  • Page 376: Locales

    Similar issues can arise if you convert between other character encodings; for example, if you read files encoded in the Japanese Windows default encoding and display them using Shift-JIS. To prevent these problems, ensure that the display encoding is the same as the input encoding. Locales A locale identifies the exact language and cultural settings to use for a user.
  • Page 377: Processing A Request In Coldfusion

    The current locale has two effects: • When ColdFusion formats date, time, currency, or numeric output, it determines how to format the output. You can change the locale multiple times on a ColdFusion page to format information according to different locale conventions. This enables you to output a page that properly formats different currency values, for example.
  • Page 378: Determining The Character Encoding Of A Coldfusion Page

    To insert a BOM character in a CFML page easily, your editor must support BOM characters. Many web page development tools support insertion of these characters, including Macromedia Dreamweaver MX, which automatically sets the BOM based on the Page Properties Document Encoding selection.
  • Page 379: Determining The Page Encoding Of Server Output

    Determining the page encoding of server output Before ColdFusion can return a response to the client, it must determine the encoding to use for the data in the response. By default, ColdFusion returns character data using the Unicode UTF-8 format. ColdFusion pages (.cfm pages) default to using the Unicode UTF-8 format for the response, even if you include the HTML tag in the page.
  • Page 380: Tags And Functions For Controlling Character Encoding

    Tags and functions for controlling character encoding The following tags and functions let you specify the character encoding of text that ColdFusion generates and interprets: Attribute or Tag or function parameter cfprocessingdirective pageencoding Specifies the encoding of a ColdFusion page so ColdFusion can parse it.
  • Page 381: Functions For Controlling And Using Locales

    Functions for controlling and using locales ColdFusion MX provides the following functions that let you specify and identify the locale and format text based on the locale: Tag or function GetLocale Returns the current locale setting. LSCurrencyFormat Converts numbers into a string in a locale-specific currency format. For countries that use the euro, the result depends on the JVM version.
  • Page 382: Additional Globalization Tags And Functions

    <body> <h3>LSDateFormat Example</h3> <p>Format the date part of a date/time value using the locale convention. <!--- loop through a list of locales; show date values for Now()---> <cfloop list = "#Server.Coldfusion.SupportedLocales#" index = "locale" delimiters = ","> <cfset oldlocale = SetLocale(locale)> <cfoutput><p><B><I>#locale#</I></B><br>...
  • Page 383: General Character Encoding Issues

    General character encoding issues Applications developed for earlier versions of ColdFusion that assumed that the character length of a string was the same as the byte length might produce errors in ColdFusion MX. The byte length of a string depends on the character encoding. Locale-specific content The following sections provide information on how to handle locale-specific content in pages that support multiple locales, and how to handle euro values.
  • Page 384 Handling URL strings URL requests to a server often contain name/value pairs as part of the request. For example, the following URL contains name/value pairs as part of the URL: http://company.com/prod_page.cfm?name=Stephen;ID=7645 As discussed previously, URL characters entered using any character encoding other than US- ASCII are URL-encoded in a hexadecimal format.
  • Page 385: File Data

    To work around this issue, use the function to specify the character encoding of SetEncoding input form text. The function takes two parameters: the first specifies the variable SetEncoding scope and the second specifies the character encoding used by the scope. Since ColdFusion writes form parameters to the Form scope, you specify "Form"...
  • Page 386: E-Mail

    Database administrators configure data sources and usually are required to specify the character encodings for character column data. Many of the major vendors, such as Oracle, Sybase, and Informix, support storing character data in many character encodings, including Unicode UTF-8 and UTF-16.
  • Page 387: Searching And Indexing

    As long as you are using CORBA later than version 2.0, which includes support for the IDL types wchar and wstring, which map to Java types char and string respectively, you do not have to do anything to support double-byte characters. However, if you are using a version of CORBA that does not support wchar and wstring, the server uses char and string data types, which assume a single-byte representation of text.
  • Page 388 Chapter 17: Developing Globalized Applications...
  • Page 389: Chapter 18: Debugging And Troubleshooting Applications

    Note: Macromedia Dreamweaver MX provides integrated tools for displaying and using ColdFusion debugging output. For information on using these tools, see the Dreamweaver MX online Help.
  • Page 390: Configuring Debugging In The Coldfusion Mx Administrator

    Configuring debugging in the ColdFusion MX Administrator ColdFusion can provide important debugging information for every application page requested by a browser. The ColdFusion MX Administrator lets you specify which debugging information to make available and how to display it. The following sections briefly describe the Administrator settings.
  • Page 391 Option Description Variables Enables the display of ColdFusion variable values. When this option is cleared, disables display of all ColdFusion variables in the debugging output. (Selected by default.) When enabled, ColdFusion displays the values of variables in the selected scopes. You can select to display the contents of any of the ColdFusion scopes except Variables, Attributes, Caller, and ThisTag.
  • Page 392: Debugging Ip Addresses Page

    Debugging IP addresses page By default, when you enable debugging output, the output is visible only to local users (that is, via IP address 127.0.0.1). You can specify additional IP addresses whose users can see debugging output, or even disable output to local users. In the Administrator, use the Debugging IPs page to specify the addresses that can receive debugging messages.
  • Page 393: General Debugging Information

    General debugging information ColdFusion displays general debugging information. In the classic.cfm output format, the information is at the top of the debugging output. In the dockable.cfm output format, it looks like the following figure: (In the classic.cfm output format, the section is first in the debugging output and has no heading.) The general debugging information includes the following values.
  • Page 394: Execution Time

    Execution Time The Execution Time section displays the time required to process the request. It displays information about the time required to process all pages required for the request, including the Application.cfm and OnRequestEnd.cfm pages, if used, and any CFML custom tags, pages included by the tag, and any ColdFusion component (CFC) pages.
  • Page 395 The next to last line of the output displays the time that ColdFusion took to parse, compile, and load pages, and to start and end page processing. This figure is not included in the individual page execution times. The last line shows the sum of all the time it took to process the request. Tree execution time format The tree execution time format is a hierarchical, detailed view of how ColdFusion processes each page.
  • Page 396: Database Activity

    • ColdFusion took 125 ms for processing that was not associated with a specific page. • The total processing time was 328 milliseconds, the sum of 125 + 203. Database Activity In the Administrator, when Database Activity is selected on the Debugging Settings page, the debugging output includes information about database access.
  • Page 397: Exceptions

    Stored Procedures The stored procedures section displays information about the results of using the cfstoredproc tag to execute a stored procedure in a database management system. The Stored Procedures section looks as follows in the classic.cfm output format: The output displays the following information: •...
  • Page 398: Trace Points

    The exception information includes information about any application exceptions that are caught and handled by your application code or by ColdFusion MX. Exceptions represent events that disrupt the normal flow of an application. You should catch and, whenever possible, recover from forseeable exceptions in your application, as described in Chapter 14, “Handling Errors,”...
  • Page 399: Using The Dockable.cfm Output Format

    Using the dockable.cfm output format The dockable.cfm output format has several features that are not included in the classic.cfm debugging display, as shown in the following figure of a docked debug pane: Application page selections ColdFusion displays two buttons at the bottom of each page, as described in the following table: Button Description Debug This page...
  • Page 400: Controlling Debugging Information In Cfml

    Controlling debugging information in CFML The following sections describe how you can use CFML tags and functions to display or hide debugging and tracing information. Generating debugging information for an individual query In the Administrator, the attribute overrides the Database Activity setting on cfquery debug the Debugging Settings page.
  • Page 401: Using The Cftrace Tag To Trace Execution

    You can use the function to selectively log information only when debugging is IsDebugMode enabled. Because you control the log output, you have the flexibility of silently logging information without displaying trace information in the browser. For example, the following code logs the application page, the current time, and the values of two variables to the log file MyAppSilentTrace.log when debugging is enabled: <cfquery name="MyDBQuery"...
  • Page 402 • In-line in your application page When you specify the attribute in a tag, inline cftrace ColdFusion displays the trace output on the page at the tag location An inline cftrace tag does not display any output if it is inside a tag block.) cftrace cfsilent...
  • Page 403: Using Tracing

    The following table lists the contents of the trace message and the log entries. For more information on the log file format, see Chapter 14, “Logging errors with the cflog tag,” on page 297. Entry Meaning Information The Severity specified in the call.
  • Page 404: Calling The Cftrace Tag

    • If a page has many nested tags you can put tags in each cfif cfelseif cftrace conditional block to trace the execution flow. When you do this, you should use the condition variable in the message or attribute. • If you find that the ColdFusion server is hanging, and you suspect a particular block of code (or call to a cfx tag, COM object, or other third-party component), you can put a cftrace...
  • Page 405: Using The Code Compatibility Analyzer

    Attribute Purpose type A ColdFusion logging severity type. The inline trace display and dockable.cfm output format show a symbol for each type. The default debugging output shows the type name, which is also used in the log file. The type name must be one of the following: Information (default) Warning...
  • Page 406: Troubleshooting Common Problems

    This section describes a few common problems that you might encounter and ways to resolve them. For more information on troubleshooting ColdFusion, see the Macromedia ColdFusion Support Center Testing and Troubleshooting page at http://www.macromedia.com/support/coldfusion/ troubleshoot.html. For common tuning and precautionary measurements that can help you prevent technical problems and improve application performance, see the ColdFusion tech tips article, TechNote number 13810.
  • Page 407: Data Source Access And Queries

    Problem : You suspect that there are problems with the structure or contents of a complex data variable, such as a structure, array, query object, or WDDX-encoded variable. Use the tag to generate a table-formatted display of the variable’s structure and contents. cfdump For example, to dump a structure named , use the following line.
  • Page 408 Chapter 18: Debugging and Troubleshooting Applications...
  • Page 409 PART IV Accessing and Using Data This part describes how to access and use sources of data, including SQL (Structured Query Language) databases, LDAP (Lightweight Directory Access Protocol) directories, and Verity document collections. It provides an introduction to the SQL language, describes how to query and update SQL data sources, and how to use record sets and the ColdFusion query of queries mechanism to manipulate record sets.
  • Page 411: Chapter 19: Introduction To Databases And Sql

    CHAPTER 19 Introduction to Databases and SQL ColdFusion MX lets you create dynamic applications to access and modify data stored in a database. You do not need a thorough knowledge of databases to develop ColdFusion applications, but you must know some basic concepts and techniques. This chapter contains an overview of many important database and SQL concepts.
  • Page 412: What Is A Database

    What is a database? A database defines a structure for storing information. Databases are typically organized into tables, which are collections of related items. You can think of a table as a grid of columns and rows. ColdFusion MX works primarily with relational databases, such as Oracle, DB2, and SQL Server.
  • Page 413: Using Multiple Database Tables

    To access the table to read or modify table data, you use the SQL programming language. For example, the following SQL statement returns all rows from the table where the department ID is 3: SELECT * FROM employees WHERE DEPTID=3 Note: In this chapter, SQL keywords and syntax are always represented by uppercase letters.
  • Page 414: Database Permissions

    Database permissions In many database environments, a database administrator defines the access privileges for users accessing the database, usually through username and password. When a person attempts to connect to a database, the database ensures that the username and password are valid and then imposes access requirements on the user.
  • Page 415: Database Design Guidelines

    Database design guidelines From this basic description, the following database design rules emerge: • Each record should contain a unique identifier as the primary key such as an employee ID, a part number, or a customer number. The primary key is typically the column used to maintain each record's unique identity among the tables in a relational database.
  • Page 416: Basic Sql Syntax Elements

    You interpret this statement as "Select the columns FirstName and LastName from the table employees where the DeptID is 3". In addition to with reading data from a table, you can write data to a table using the SQL INSERT statement. The following statement adds a new row to the employees table: INSERT INTO employees(EmpID, LastName, Firstname) VALUES(51, 'Doe', 'John') Basic SQL syntax elements...
  • Page 417 Operator Description <> Not equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to Addition Subtraction Division Multiplication Case sensitivity with databases ColdFusion MX is a case-insensitive programming environment. Case insensitivity means the following statements are equivalent: <cfset foo="bar">...
  • Page 418: Reading Data From A Database

    Reading data from a database You use the SQL SELECT statement to read data from a database. The SQL statement has the following general syntax: SELECT column_names FROM table_names [ WHERE search_condition ] [ GROUP BY group_expression ] [HAVING condition] [ ORDER BY order_condition [ ASC | DESC ] ] The statements in square brackets are optional.
  • Page 419 Filtering results The SELECT statement lets you filter the results of a query to return only those records that meet specific criteria. For example, if you want to access all database records for employees in department 3, you use the following query: SELECT * FROM employees WHERE DeptID=3 You can combine multiple conditions using the WHERE clause.
  • Page 420: Modifying A Database

    Accessing multiple tables In a database, you can have multiple tables containing related information. You can extract information from multiple tables as part of a query. In this case, you specify multiple table names in the SELECT statement, as follows: SELECT LastName, FirstName, Street, City, State, Zip FROM employees, addresses WHERE employees.EmpID = addresses.EmpID...
  • Page 421 where: • column_names specifies a comma-separated list of columns. • value_list specifies a comma-separated list of values. The order of values has to correspond to the order that you specified column names. Note: There are additional options to INSERT depending on your database. For a complete syntax description for INSERT, see the product documentation.
  • Page 422: Writing Queries Using An Editor

    Deleting data from a database The DELETE statement removes rows from a table. The DELETE statement has the following syntax: DELETE FROM table_name [ WHERE search_condition ] Note: There are additional options to DELETE depending on your database. For a complete syntax description for DELETE, see the product documentation.
  • Page 423 The Simple Recordset dialog box appears: Complete the dialog box. Click the Test button to execute the query and ensure that it retrieves the information you intended. If you defined a filter that uses parameters input by users, the Test button displays the Test Value dialog box.
  • Page 424: Writing Queries Using Macromedia Homesite

    Click OK to add the record set to the list of available content sources in the Data Bindings panel. Writing queries using Macromedia HomeSite+ Macromedia HomeSite+ includes the combined features of HomeSite 5 and ColdFusion Studio 5, with additional support for new ColdFusion MX tags. HomeSite+ supports SQL Builder for writing queries.
  • Page 425 The SQL Builder interface The following figure shows the SQL Builder interface: The SQL Builder is divided into the following four sections: Section Toolbar Contains buttons for SQL keywords and commands. Table pane Provides a view of the tables in your query and allows you to create joins between tables.
  • Page 426 Chapter 19: Introduction to Databases and SQL...
  • Page 427: Chapter 20: Accessing And Retrieving Data

    CHAPTER 20 Accessing and Retrieving Data This chapter describes how to retrieve data from a database and work with query data. This chapter also shows how to use the tag to query a data source, and use the cfquery cfoutput to output the query results to a web page.
  • Page 428: Working With Dynamic Data

    Working with dynamic data A web application page is different from a static web page because it can publish data dynamically. This can involve querying databases, connecting to LDAP or mail servers, and leveraging COM, DCOM, CORBA, or Java objects to retrieve, update, insert, and delete data at runtime—as your users interact with pages in their browsers.
  • Page 429: The Cfquery Tag

    The cfquery tag tag is one of the most frequently used CFML tags. You use it with the cfquery cfoutput to retrieve and reference the data returned from a query. When ColdFusion encounters a cfquery tag on a page, it does the following: •...
  • Page 430: Building Queries

    Building queries As discussed earlier in this chapter, you build queries using the tag and SQL. cfquery Note: This and many subsequent procedures use the CompanyInfo data source that connects to the company.mdb database. This data source is installed by default. For information on adding or configuring a data source, see Configuring and Administering ColdFusion MX.
  • Page 431: Outputting Query Data

    ColdFusion creates the EmpList data set, but only HTML and text return to the browser. When you view the page’s source, you see only HTML tags and the heading “Employee List.” To display the data set on the page, you must code tags and variables to output the data. Reviewing the code The query you just created retrieves data from the CompanyInfo database.
  • Page 432 <cfoutput query="EmpList"> #EmpList.FirstName#, #EmpList.LastName#, #EmpList.Salary#, #EmpList.Contract#<br> </cfoutput> </body> </html> Save the file and view it in your web browser: A list of employees appears in the browser, with each line displaying one row of data. Note: You might need to refresh your browser to see your changes. You created a ColdFusion application page that retrieves and displays data from a database.
  • Page 433: Query Output Notes And Considerations

    Query output notes and considerations When outputting query results, keep the following guidelines in mind: • must precede the that references its results. Both must be on the same cfquery cfoutput page (unless you use the tag; for more information, see “Including pages with the cfinclude cfinclude tag”...
  • Page 434: Query Variable Notes And Considerations

    <cfoutput> The query returned #EmpList.RecordCount# records. </cfoutput> </body> </html> Save the file and view it in your web browser: The number of employees now appears below the list of employees. You might have to refresh your browser and scroll to see the RecordCount output. Note: The variable contains the amount of time, in milliseconds, it took for cfquery.executionTime...
  • Page 435: Enhancing Security With Cfqueryparam

    • Do not use the attribute when you output the cfoutput query RecordCount property. If you do, you get one copy of the output for each row. Instead, prefix ColumnList the variable with the name of the query. Enhancing security with cfqueryparam Some DBMSs let you send multiple SQL statements in a single query.
  • Page 436 tag checks that the value of Emp_ID is an integer data type. If anything else cfqueryparam in the query string is not an integer, such as a SQL statement to delete a table, the cfquery does not execute. Instead, the tag returns the following error message: cfqueryparam Invalid data '7 DELETE FROM Employee' for CFSQLTYPE 'CF_SQL_INTEGER'.
  • Page 437: Chapter 21: Updating Your Database

    CHAPTER 21 Updating Your Database This chapter describes how to use ColdFusion to insert, update, and delete information in a database. Contents About updating your dataSbase ..........438 Inserting data .
  • Page 438: About Updating Your Datasbase

    About updating your dataSbase ColdFusion was originally developed as a way to readily interact with databases. You can quickly insert, update, and delete the contents of your database by using ColdFusion forms, which are typically a pair of pages. One page displays the form with which your end user will enter values; the other page performs the action (insert, update or delete).
  • Page 439 To create an insert form: Create a ColdFusion page with the following content: <html> <head> <title>Insert Data Form</title> </head> <body> <h2>Insert Data Form</h2> <table> <!--- begin html form; put action page in the "action" attribute of the form tag ---> <form action="insert_action.cfm"...
  • Page 440: Data Entry Form Notes And Considerations

    Data entry form notes and considerations If you use the tag in the action page to insert the data into the database, you should cfinsert follow these rules for creating the form page: • You only need to create HTML form fields for the database columns into which you will insert data.
  • Page 441 Reviewing the code The following table describes the code and its function: Code Description Sets the value of Form.Contract to No if it is not <cfif not isdefined("Form.Contract")> <cfset Form.Contract = "No"> defined. If the Contractor check box is unchecked, </cfif>...
  • Page 442: Updating Data

    </cfoutput> </body> </html> Save the page. View insert_form.cfm in your web browser and enter values. Click Submit. ColdFusion inserts your values into the Employee table and displays a confirmation message. Reviewing the code The following table describes the highlighted code and its function: Code Description Inserts a new row into the Employee table of the CompanyInfo...
  • Page 443: Creating An Update Form

    Creating an update form The following are the key differences between an update form and an insert form: • An update form contains a reference to the primary key of the record that is being updated. A primary key is a field(s) in a database table that uniquely identifies each record. For example, in a table of employee names and addresses, only the Emp_ID is unique to each record.
  • Page 444 <cfelse> <input type="checkbox" name="Contract">Yes </cfif></td> </tr> <tr> <td>&nbsp;</td> <td><input type="Submit" value="Update Information"></td> </tr> </form> </table> </cfoutput> </body> </html> Save the file as update_form.cfm. View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following: http://localhost/myapps/update_form.cfm?Emp_ID=3 Note: Although you can view an employee’s information, you must code an action page before you can update the database.
  • Page 445: Creating An Action Page To Update Data

    Code Description First Name: Populates the fields of the update form. <input type="text" name="FirstName" This example does not use ColdFusion value="#FirstName#"><br> formatting functions. As a result, start Last Name: dates look like 1985-03-12 00:00:00 <input type="text" name="LastName" and salaries do not have dollar signs or value="#LastName#"><br>...
  • Page 446 <cfupdate datasource="CompanyInfo" tablename="Employee"> <h1>Employee Updated</h1> <cfoutput> You have updated the information for #Form.FirstName# #Form.LastName# in the employee database. </cfoutput> </body> </html> Save the page as update_action.cfm. View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, enter the following: http://localhost/myapps/update_form.cfm?Emp_ID=3 The current information for that record appears:...
  • Page 447 Reviewing the code The following table describes the code and its function: Code Description Sets the value of Form.Contract to No if it is not <cfif not isdefined("Form.Contract")> <cfset Form.contract = "No"> defined, or to Yes if it is defined. If the Contractor <cfelse>...
  • Page 448: Deleting Data

    You have updated the information for #Form.FirstName# #Form.LastName# in the employee database. </cfoutput> </body> </html> Save the page. View update_form.cfm in your web browser by specifying the page URL and an Employee ID; for example, type the following: http://localhost/myapps/update_form.cfm?Emp_ID=3. Enter new values in any of the fields, and click Update Information. ColdFusion updates the record in the Employee table with your new values and displays a confirmation message.
  • Page 449 To delete one record from a database: In update_form.cfm, change the title to “Delete Form” and the text on the submit button to “Delete Record”. Change the tag so that it appears as follows: form <form action="delete_action.cfm" method="Post"> Save the modified file as delete_form.cfm. Create a ColdFusion page with the following content: <html>...
  • Page 450: Deleting Multiple Records

    Deleting multiple records You can use a SQL condition to delete several records. The following example deletes the records for everyone in the Sales department (which has Dept_ID number 4) from the Employee table: DELETE FROM Employee WHERE Dept_ID = 4 To delete all the records from the Employee table, use the following code: DELETE FROM Employee Caution: Deleting records from a database is not reversible.
  • Page 451: Chapter 22: Using Query Of Queries

    CHAPTER 22 Using Query of Queries A query that retrieves data from a record set is called a Query of Queries. After you generate a record set, you can interact with its results as if they were database tables by using Query of Queries.
  • Page 452: About Record Sets

    About record sets Query of Queries is based on manipulating the record set, which you can create using the tag and other ways. cfquery When you execute a database query, ColdFusion retrieves the data in a record set. In addition to presenting record set data to the user, you can manipulate this record set to improve your application’s performance.
  • Page 453: Creating A Record Set With A Function

    Creating a record set with a function In addition to creating a record set by using a or other CFML tags, you can create it with cfquery function. QueryNew() To create a record set with the QueryNew() function: Create a ColdFusion page with the following content: <html>...
  • Page 454: About Query Of Queries

    The following figure shows how the output appears: Note: When you create a record set, you can store in it complex objects, such as arrays and structures. However, you cannot use Query Of Queries on a record set that contains complex objects. For more information on Query of Queries, see “About Query of Queries”...
  • Page 455: Performing A Query Of Queries

    • You can obtain drill-down, master-detail information for which you do not access the database for the details. For example, you can select information about departments and employees in a query, and cache the results. You can then display the employees’ names. When users select an employee, the application displays the employee’s details by selecting information from the cached query, without accessing the database.
  • Page 456 <!--- output the detail query results ---> <p>Output using a query of query:</p> <cfoutput query=detail> #Emp_ID#: #FirstName# #LastName#<br> </cfoutput> <br> <p>Columns in the master query:</p> <cfoutput> #master.columnlist#<br> </cfoutput> <br> <p>Columns in the detail query:</p> <cfoutput> #detail.columnlist#<br> </cfoutput> </body> Save the page as query_of_query.cfm in the myapps directory under the web_root. In your browser, enter the following URL to display the queryresults: http://127.0.0.1/myapps/query_of_query.cfm The following figure shows how the output appears:...
  • Page 457 Reviewing the code The master query retrieves the entire Employee table from the CompanyInfo data source (the CompanyInfo database). The detail query selects only the three columns to display for employees with the specified last name. The following table describes the code and its function: Code Description Sets the last name to use in the detail query.
  • Page 458 <!--- master query: retrieve all info from Employee table ---> <cfquery name = "GetSals" datasource = "CompanyInfo"> SELECT * FROM Employee ORDER BY LastName </cfquery> <!--- detail query: select 3 fields from the master query ---> <cfquery name = "GetSals2" dbtype = "query"> SELECT FirstName, LastName, Salary FROM...
  • Page 459 <tr> <td colspan = 4> <cfif (startrow + maxrows) lte getsals2.recordcount> <a href="qoq_next_row.cfm?startrow=<cfoutput>#Evaluate(StartRow + MaxRows)#</cfoutput>">See next <cfoutput>#MaxRows#</cfoutput> rows</a> </cfif> </td> </tr> </table> </body> </html> Save the page as qoq_next_row.cfm in the myapps directory under the web_root In your web browser, enter the following URL to display the query results: http://127.0.0.1/myapps/qoq_next_row.cfm The following figure shows how the output appears: Using the cfdump tag with query results...
  • Page 460 To use Query of Queries with a Verity record set: Create a ColdFusion page with the following content: <html> <head> <title>QoQ and Verity</title> </head> <body> <!--- master query: retrieve all documents from the bbb collection that contain ’film’ (or its stemmed variants); change values for collection and criteria as needed for your Verity collection --->...
  • Page 461 The first tag shows the master query, which retrieves all records. The second cfdump cfdump shows the Query of Queries results. Tip: Adjust the score criterion of the detail query to reflect the contents of your collection. The next example shows how a Query of Queries combines record sets from a tag, cfdirectory which is limited to retrieval of one file type per use.
  • Page 462: Query Of Queries User Guide

    The following figure shows how the output appears: Query of Queries user guide The following sections discuss Query of Queries functionality. If you know SQL or have interacted with databases, you might be familiar with some of these features. Using dot notation ColdFusion supports using dot notation in table names.
  • Page 463: Using Unions

    ColdFusion supports INNER JOINs between two tables, as the following example shows. This operation is the most common type of join. SELECT Dog_ID, Breed_ID FROM Dogs, Breed WHERE Dogs.Dog_ID = Breed.Dog_ID; Using unions The UNION operator lets you combine the results of two or more SELECT expressions into a single record set.
  • Page 464 The UNION statement produces the following result (UNION) table: Result table Type(int) Name(varchar) Tennis Baseball Football Volleyball PingPong Using aliases for column names The column names of a UNION table are the column names in the result set of the first SELECT statement in the UNION operation;...
  • Page 465: Using Conditional Operators

    UNION SELECT * FROM TableC In the first statement, there are no duplicates in the union between TableB and TableC. Then, in the union between that set and TableA, the ALL keyword includes the duplicates. In the second statement, duplicates are included in the union between TableA and TableB but are eliminated in the subsequent union with TableC.
  • Page 466 Comparison conditional This conditional lets you compare an expression against another expression of the same data type (Numeric, String, Date, or Boolean). You can use it to selectively retrieve only the relevant rows of a record set. Syntax comparison_cond ::= expression [> | >= | <> | != | < | <=] expression Example The following example uses a comparison conditional to retrieve only those dogs whose IQ is at least 150:...
  • Page 467 LIKE conditional This conditional lets you perform wildcard searches, in which you compare your data to search patterns. This strategy differs from other conditionals, such as BETWEEN or IN, because the LIKE conditional compares your data to a value that is partially unknown. Syntax like_cond ::= left_string_exp [NOT] LIKE right_string_exp [ESCAPE escape_char] The left_string_exp can be either a constant string, or a column reference to a string column.
  • Page 468: Using Aggregate Functions

    The following example is not case-sensitive; it uses the function to treat 'Sylvester', LOWER() 'sylvester', 'SYLVESTER', and so on as all lowercase, and matches them with the all lowercase string, ‘sylvester’: SELECT dog_name FROM Dogs WHERE LOWER(dog_name) LIKE 'sylvester'; If you use a variable on the right side of the LIKE conditional and want to ensure that the comparison is not case-sensitive, use the function to force the variable text to be LCase...
  • Page 469: Using Group By And Having Expressions

    Example The following example uses the function to retrieve the average IQ of all terriers: AVG() SELECT dog_name, AVG(dog_IQ) AS avg_IQ FROM Dogs WHERE breed LIKE '%Terrier'; Arbitrary expressions in aggregate functions ColdFusion supports aggregate functions of any arbitrary expression, as follows: SELECT lorange, count(lorange+hirange) FROM roysched GROUP BY lorange;...
  • Page 470: Using Aliases

    Examples The following example shows a simple sort using an ORDER BY clause: SELECT acetylcholine_levels, dopamine_levels FROM results ORDER BY dopamine_levels The following example shows a more complex sort; results are first sorted by ascending levels of dopamine, then by descending levels of acetylcholine. The ASC keyword is unnecessary, and is used only for legibility.
  • Page 471: Handling Null Values

    HAVING example <cfquery name="having" dbtype="query"> SELECT (lorange+hirange)/2 AS x, COUNT(*) FROM roysched GROUP BY x HAVING x > 10000 </cfquery> Handling null values ColdFusion uses Boolean logic to handle conditional expressions. Proper handling of NULL values requires the use of ternary logic. The clause works correctly in IS [NOT] NULL ColdFusion.
  • Page 472 The following table lists ColdFusion reserved keywords: ABSOLUTE ACTION ALLOCATE ALTER ASSERTION AUTHORIZATION BEGIN BETWEEN BIT_LENGTH BOTH CASCADE CASCADED CASE CAST CATALOG CHAR CHARACTER CHARACTER_ CHAR_LENGTH LENGTH CHECK CLOSE COALESCE COLLATE COLLATION COLUMN COMMIT CONNECT CONNECTION CONSTRAINT CONSTRAINTS CONTINUE CONVERT CORRESPONDING COUNT CREATE...
  • Page 473: Using Queries Of Queries With Numeric Dates

    PRIOR PRIVILEGES PROCEDURE PUBLIC READ REAL REFERENCES RELATIVE RESTRICT REVOKE RIGHT ROLLBACK ROWS SCHEMA SCROLL SECOND SECTION SELECT SESSION SESSION_USER SIZE SMALLINT SOME SPACE SQLCODE SQLERROR SQLSTATE SUBSTRING SYSTEM_USER TABLE TEMPORARY THEN TIME TIMESTAMP TIMEZONE_HOUR TIMEZONE_MINUTE TO TRAILING TRANSACTION TRANSLATE TRANSLATION TRIM TRUE...
  • Page 474: Bnf For Query Of Queries

    When working with a query resulting from a SQL join, Query of Queries performs as follows: • Query of Queries is very efficient for simple joins in which there is only one equality between two column references; for example: SELECT T1.a, b, c, d FROM T1, T2 WHERE T1.a = T2.a •...
  • Page 475 null_cond ::= row_constructor <IS> ( <NOT> )? <NULL> comparison_cond ::= row_constructor comparison_operator row_constructor between_cond ::= row_constructor ( <NOT> )? <BETWEEN> row_constructor <AND> row_constructor in_cond ::= row_constructor ( <NOT> )? <IN> <OPENPAREN> ( expression_list ) <CLOSEPAREN> row_constructor ::= expression comparison_operator ::= <LESSEQUAL> | <GREATEREQUAL>...
  • Page 476 Chapter 22: Using Query of Queries...
  • Page 477: Chapter 23: Managing Ldap Directories

    CHAPTER 23 Managing LDAP Directories CFML applications use the tag to access and manage LDAP (Lightweight Directory cfldap Access Protocol) directories. This chapter provides information on how to use this tag to view, query, and update LDAP directories. This chapter teaches you how to query and update an LDAP database. It does not assume that you are familiar with LDAP, and provides an introduction to LDAP directories and the LDAP protocol.
  • Page 478: About Ldap

    About LDAP The LDAP protocol enables organizations to arrange and access directory information in a hierarchy. In this context, directory refers to a collection of information, such as a telephone directory, not a collection of files in a folder on a disk drive. LDAP originated in the mid-1990s as a response to the need to access ISO X.500 directories from personal computers that had limited processing power.
  • Page 479: The Ldap Information Structure

    The following figure show such an asymmetric directory: In this directory structure, the second level of the tree divides the directory into two organizational units: people and groups. The third level contains entries with information that is specific to the organizational unit. Each person’s entry includes a name, e-mail address, and telephone number.
  • Page 480: Entry

    Entry The basic information object of LDAP is the entry. An entry is composed of one or more attributes. Entries are subject to content rules defined by the directory schema (see “Schema” on page 481). Each node, not just the terminal nodes, of an LDAP directory is an entry. In the preceding figures, each item is an entry.
  • Page 481: Schema

    (+). In the sample directories, individuals could have complex RDNs consisting of their common name and their e-mail address; for example, “cn=Robert Boyd + mail=rjboyd@macromedia.com”. Schema The concepts of schemas and object classes are central to a thorough understanding of LDAP.
  • Page 482: Using Ldap With Coldfusion

    Attribute type A schema’s attribute type specification defines the following properties: • The attribute type name • A unique object ID that identifies the attribute type • (Optional) An indication of whether the type is single-valued or multivalued (the default is multivalued) •...
  • Page 483: Querying An Ldap Directory

    Matches (mail=*) All entries that contain a mail attribute. (o=macromedia) Entries in which the organization name is macromedia. (sn~=Hansen) Entries with a surname that approximates Hansen. The matching rules for approximate matches vary among directory vendors, but anything that "sounds like" the search string should be matched.
  • Page 484 Operator Example Matches & (&(o=macromedia) Entries in which the organization name is "macromedia" and the (co=usa)) country is "usa". (|(o=macromedia) Entries in which the organization name is "macromedia" or the (sn=macromedia) surname is "macromedia", or the common name is (cn=macromedia)) "macromedia".
  • Page 485: Getting All The Attributes Of An Entry

    • If you use filter operators to construct sophisticated search criteria, performance might degrade if the LDAP server is slow to process the synchronous search routines that supports. cfldap You can use the attributes to control the apparent cfldap timeout maxRows performance of pages that perform queries, by limiting the number of entries and by exiting the query if the server does not respond in a specified time.
  • Page 486 <p>Enter a full name, first name, last name, or name fragment.</p> <form action="cfldap.cfm" method="POST"> <input type="text" name="name"><br><br> <input type="submit" value="Search"> </form> <!--- make the LDAP query ---> <!-- Note that some search text is required. A search filter of cn=** would cause an error --> <cfif (isdefined("form.name") AND (form.name IS NOT ""))>...
  • Page 487 Reviewing the code The following table describes the code: Code Description Uses a form to get the name or name fragment <form action="cfldap.cfm" method="POST"> <input type="text" name="name"> to search for. <br><br> <input type="submit" value="Search"> </form> <cfif (isdefined("form.name") Ensures that the user has submitted the form. AND (form.name IS NOT ""))>...
  • Page 488: Updating An Ldap Directory

    This search shows the use of a logical AND statement in a filter. It returns one attribute, the surname, that is used only for sorting the results. In this query, the attribute value consists of two values in a comma-delimited list. One is the department name.
  • Page 489: Adding A Directory Entry

    Adding a directory entry When you add an entry to an LDAP directory, you specify the DN, all the required attributes, including the entry’s object class, and any optional attributes. The following example builds a form that adds an entry to an LDAP directory. To add an entry: Create a file that looks like the following: <!--- set the LDAP server ID, user name, and password as variables...
  • Page 490 <cfform action="update_ldap.cfm" method="post"> <table> <tr><td>Full Name:</td> <td><cfinput type="Text" name="fullName" value=#fullNameValue# size="20" maxlength="30" tabindex="1"></td> </tr> <tr><td>Surname:</td> <td><cfinput type="Text" name="surname" Value= "#surnameValue#" size="20" maxlength="20" tabindex="2"></td> </tr> <tr> <td>E-mail Address:</td> <td><cfinput type="Text" name="email" value="#emailValue#" size="20" maxlength="20" tabindex="3"></td> </tr> <tr> <td>Telephone Number:</td> <td><cfinput type="Text" name="phone"...
  • Page 491 action="query" attributes="cn,sn,mail,telephonenumber,uid" start="o=Airius.com" scope="subtree" filter="ou=Human Resources" sort="sn,cn" sortControl="asc, nocase"> <table border="1"> <tr> <th>Full Name</th> <th>Surname</th> <th>Mail</th> <th>Phone</th> <th>UID</th> </tr> <cfoutput query="GetList"> <tr> <td>#GetList.cn#</td> <td>#GetList.sn#</td> <td>#GetList.mail#</td> <td>#GetList.telephonenumber#</td> <td>#GetList.uid#</td> </tr> </cfoutput> </table> </body> </html> At the top of the file, change the myServer, myUserName, and myPassword variable assignments to values that are valid for your LDAP server.
  • Page 492 Code Description <cfif Trim(Form.fullName) is "" If any field in the submitted form is blank, display a OR Trim(Form.surname) is "" message and set the other form fields to display OR Trim(Form.email) is "" data that the user submitted. OR Trim(Form.phone) is ""> <h2>You must enter a value in every field.</h2>...
  • Page 493: Deleting A Directory Entry

    Code Description <cfldap name="GetList" Queries the directory and gets the common name, server=#myServer# surname, e-mail address, telephone number, and action="query" user ID from the matching entries. attributes="cn,sn,mail, Searches the subtree from the entry with the DN of telephonenumber,uid" o=Airius.com, and selects all entries in which the start="o=Airius.com"...
  • Page 494 username=#myUserName# password=#myPassword#> <cfoutput><h3>Entry for User ID #Form.UID# has been deleted </h3></cfoutput> At the end of the code for the Add button (the tag with at the bottom of the input Value=Add form , delete the end tag. </td> After the end of the Add button tag, add the following code: input &nbsp...
  • Page 495: Updating A Directory Entry

    Updating a directory entry tag lets you change the values of entry attributes. To do so, you specify the entry DN cfldap in the attribute, and list the attributes to change and their new values in the attributes attribute. The following example builds on the code that adds and deletes an entry. It can update one or more of an entry’s attributes.
  • Page 496: Adding And Deleting Attributes Of A Directory Entry

    Reviewing the code The following table describes the code: Code Description If the user clicks Update, sets the attribute list <cfelseif Form.action is "Update"> <cfset attributelist="cn=#Trim to the form field values and replaces the (form.FullName)#; attributes for the entry with the specified UID. sn=#Trim(Form.surname)#;...
  • Page 497: Changing A Directory Entry's Dn

    Changing a directory entry’s DN To change the DN of an entry, you must provide the following information in the tag: cfldap dn="original DN" action="modifyDN" attributes="dn=new DN" For example: <cfldap action="modifyDN" dn="#old_UID#, ou=People, o=Airius.com" attributes="uid=#newUID#" server=#myServer# username=#myUserName# password=#myPassword#> The new DN and the entry attributes must conform to the directory schema; therefore, you cannot move entries arbitrarily in a directory tree.
  • Page 498: Using Cfldap Output

    Using cfldap output You can create a searchable Verity collection from LDAP data. For an example of building a Verity collection using an LDAP directory, see Chapter 24, “Indexing cfldap query results,” on page 530. The ability to generate queries from other queries is very useful when queries return cfldap complex data.
  • Page 499 <!--- Only one record is returned, so query loop is not required ---> <h2>Object Classes</h2> <table border="1"> <tr> <th>Name</th> <th>Superior class</th> <th>Must have</th> <th>May have</th> </tr> <cfloop index = "thisElement" list = #Entrylist2.objectclasses#> <cfscript> thiselement = Trim(thisElement); nameloc = Find("NAME", thisElement); descloc = Find("DESC", thisElement);...
  • Page 500 endloc = Len(thisElement); </cfscript> <tr> <td><cfoutput>#Mid(thisElement, nameloc+6, descloc-nameloc-8)# </cfoutput></td> <td><cfoutput>#Mid(thisElement, descloc+6, syntaxloc-descloc-8)# </cfoutput></td> <cfif #singleloc# EQ 0> <td><cfoutput>Yes</cfoutput></td> <cfelse> <td><cfoutput>No</cfoutput></td> </cfif> </tr> </cfloop> </table> </body> </html> Change the server from to your LDAP server. You might also need to ldap.mycorp.com specify a user ID and password in the tag.
  • Page 501 Code Description <h2>Object Classes</h2> Displays the object class name, superior <table border="1"> class, required attributes, and optional <tr> attributes for each object class in a table. <th>Name</th> The schema contains the definitions of all <th>Superior class</th> object classes in a comma delimited list, so <th>Must have</th>...
  • Page 502: Referrals

    Code Description <h2>Attribute Types</h2> Does the same types of calculations for the <table border="1" > attribute types as for the object classes. <tr> <th>Name</th> <th>Description</th> <th>Multivalued?</th> </tr> The attribute type field can contain the text ", <cfloop index = "thisElement" list = alias for..".
  • Page 503: Managing Ldap Security

    Managing LDAP security When you consider how to implement LDAP security, you must consider server security and application security. Server security tag supports secure socket layer (SSL) v2 security. This security provides certificate- cfldap based validation of the LDAP server. It also encrypts data transferred between the ColdFusion server and the LDAP server, including the user password, and ensures the integrity of data passed between the servers.
  • Page 504 attribute specifies the server port used for secure LDAP communications, which is 636 port by default. If you do not specify a port, ColdFusion attempts to connect to the default, nonsecure, LDAP port 389. Application security To ensure application security, you must prevent outsiders from gaining access to the passwords that you use in tags.
  • Page 505: Chapter 24: Building A Search Interface

    CHAPTER 24 Building a Search Interface You can provide a full-text search capability for documents and data sources on a ColdFusion site by enabling the Verity search engine. This chapter describes how to build a Verity search interface with which users can perform powerful searches on your application.
  • Page 506: About Verity

    About Verity To efficiently search through paragraphs of text or files of varying types, you need full-text search capabilities. ColdFusion includes the Verity search engine, which provides full-text indexing and searching. The Verity engine performs searches against collections, not against the actual documents. A collection is a special database created by Verity that contains metadata that describes the documents that you have indexed.
  • Page 507: Advantages Of Using Verity

    Advantages of using Verity Verity can index the output from queries so that you or a user can search against the record sets. Searching query results has a clear advantage over using SQL to search a database directly in speed of execution because metadata from the record sets are stored in a Verity index that is optimized for searching.
  • Page 508 • Microsoft Works (v1.0, 2.0, 3.0, 4.0) • Microsoft Write (v1.0, 2.0, 3.0) • PDF (Verity PDF Filter) • Text files (Verity Text Filter) • Unicode Text (All versions) • WordPerfect (v5.x, 6, 7, 8) • WordPerfect Mac (v2, 3) •...
  • Page 509: Support For International Languages

    • Microsoft Windows Metafile (WMF) • PC PaintBrush (PCX) • Portable Network Graphics (PNG) • Sun Raster SGI RGB • Truevision Targa • TIFF • WordPerfect Graphics (WPG) v1, 2 Multimedia formats • Audio Interchange File Format (AIFF) • Microsoft Sound (WAV) •...
  • Page 510 Language Language attribute Localization technology Dutch dutch LinguistX English english LinguistX Finnish finnish LinguistX French french LinguistX German german LinguistX Greek greek Hebrew hebrew Hungarian hungarian Italian italian LinguistX Japanese japanese Korean korean Norwegian norwegian LinguistX Norwegian (Bokmal) bokmal LinguistX Norwegian (Nynorsk) nynorsk LinguistX...
  • Page 511: Creating A Search Tool For Coldfusion Applications

    Creating a search tool for ColdFusion applications There are three main tasks in creating a search tool for your ColdFusion application: Create a collection. Index the collection. Design a search interface. You can perform each task programmatically—that is, by writing CFML code. Alternatively, you can use the ColdFusion MX Administrator to create and index the collection.
  • Page 512: Creating A Collection With The Coldfusion Mx Administrator

    Creating a collection with the ColdFusion MX Administrator Use the following procedure to quickly create a collection with the ColdFusion MX Administrator: To create a collection with the ColdFusion MX Administrator: In the ColdFusion MX Administrator, select Data & Services > Verity Collections. The Verity Collections page appears: Enter a name for the collection;...
  • Page 513: About Indexing A Collection

    Note: You can map a collection currently available on your network or local disk by creating a local reference (an alias) for that collection. In this procedure, enter the collection alias as the collection name, and enter a UNC (Universal Naming Convention) path to the folder for the collection. You have successfully created a collection, DemoDocs, that currently has no data.
  • Page 514: Indexing And Building A Search Interface With The Verity Wizard

    Indexing and building a search interface with the Verity Wizard If you have HomeSite+, you can use the Verity Wizard to generate a basic search and index interface. Use the following procedure to quickly create a search application for a collection. This procedure assumes the following: •...
  • Page 515 Click Next. The Select Collection window appears: Enter the following information: Field Description Example Collection The name of the collection you created in the ColdFusion DemoDocs Name MX Administrator (or by using the tag). cfcollection Language The language used to create the collection (English is the english default).
  • Page 516 Enter the following information: Field Description Example Directory Path The directory that contains the documents C:\CFusionMX\wwwroot\cfdocs to be indexed. Recursively Index (Optional) Extends the indexing operation enabled (default) Subdirectories to all directories below the selected path. File Extensions The type(s) of files to index. Use a comma .htm, .html, .xml to separate multiple file types.
  • Page 517 Click the web browser’s back button to return to the search form. Enter your search term(s); for example, Verity AND data source. Tip: For more information on the Verity search syntax, see “Using Verity Search Expressions” on page 535. Click Search. The following compilation error might display: Invalid parser construct found on line 46 at position 49.
  • Page 518: Creating A Coldfusion Search Tool Programmatically

    Creating a ColdFusion search tool programmatically You can create a Verity search tool for your ColdFusion application in CFML. Although writing CFML code can take more development time than using these tools, there are situations in which writing code is the preferred development method. Creating a collection with the cfcollection tag The following are cases in which you might prefer using the tag rather than the...
  • Page 519 name="CollectionAction" value="Repair">Repair<br> <input type="radio" name="CollectionAction" value="Optimize">Optimize<br> <input type="submit" name="submit" value="Submit"> </form> </body> </html> Save the file as collection_create_form.cfm in the myapps directory under the web root directory Note: The form will not work until you write an action page for it, which is the next procedure. To create a collection action page: Create a ColdFusion page with the following content: <html>...
  • Page 520 Save the file as collection_create_action.cfm in the myapps directory under the web root directory In the web browser, enter the following URL to display the form page: http://127.0.0.1/myapps/collection_create_form.cfm The following figure shows how the output appears: Enter a collection name; for example, CodeColl. Verify that Create is selected and submit the form.
  • Page 521 You can use form and action pages similar to the following examples to select and index a collection. To select which collection to index: Create a ColdFusion page with the following content: <html> <head> <title>Select the Collection to Index</title> </head> <body>...
  • Page 522 The following figure shows how the output appears: Enter a collection name; for example, CodeColl. Enter a file location; for example, C:\CFusionMX\wwwroot\vw_files. Click Index. A confirmation message appears upon successful completion. Note: For information about using the cfindex tag with a database to index a collection, see “Using database-directed indexing”...
  • Page 523: Using The Cfsearch Tag

    This interface lets you easily build a very specific index based on the file extension and path information you enter. In most cases, you do not need to change your server file structures to accommodate the generation of indices. Using the cfsearch tag You use the tag to search an indexed collection.
  • Page 524 <p>Enter search term(s) in the box below. You can use AND, OR, NOT, and parentheses. Surround an exact phrase with quotation marks.</p> <p><input type="text" name="criteria" size="50" maxLength="50"> </p> <input type="submit" value="Search"> </form> </body> </html> Save the file as collection_search_form.cfm. Enter a search target word(s) in this form, which passes this as the variable to the action criteria page, which displays the search results.
  • Page 525 View collection_search_form.cfm in the web browser: Enter a target word(s) and click Search. The following figure shows how the output appears: Note: As part of the indexing process, Verity automatically produces a summary of every document file or every query record set that gets indexed. The default summary selects the best sentences, based on internal rules, up to a maximum of 500 characters.
  • Page 526: Working With Record Sets

    Working with record sets , and tags return the results of a database query in a record set. In cfquery cfldap cfpop some cases, you might want to search the record set. This section describes the reasons and procedures for indexing the results of database, LDAP, and pop queries. It also describes how a database can direct the indexing process, using different values for the attribute of the type...
  • Page 527 To index a ColdFusion query: Create a ColdFusion page with the following content: <html> <head> <title>Adding Query Data to an Index</title> </head> <body> <!--- retrieve data from the table ---> <cfquery name="getEmps" datasource="CompanyInfo"> SELECT * FROM EMPLOYEE </cfquery> <!--- update the collection with the above query results ---> <cfindex query="getEmps"...
  • Page 528 The resulting record set appears: Using the tag for indexing tabular data is similar to indexing documents, with the cfindex following exceptions: • You set the attribute to when indexing tabular data. type custom • You refer to column names from the in the attribute.
  • Page 529 Save the file as collection_db_search_form.cfm in the myapps directory under the web_root. This file is similar to collection_search_form.cfm, except the form uses collection_db_results.cfm, which you create in the next step, as its action page. Create another ColdFusion page with the following content: <html>...
  • Page 530: Indexing Cfldap Query Results

    The following figure shows how the output appears: Indexing cfldap query results The widespread use of the Lightweight Directory Access Protocol (LDAP) to build searchable directory structures, internally and across the web, gives you opportunities to add value to the sites that you create.
  • Page 531: Indexing Cfpop Query Results

    start="c=US"> <!--- Output query record set ---> <cfoutput query="OrgList"> DN: #dn# <br> O: #o# <br> TELEPHONENUMBER: #telephonenumber# <br> MAIL: #mail# <br> =============================<br> </cfoutput> <!--- Index the record set ---> <cfindex action="update" collection="ldap_query" key="dn" type="custom" title="o" query="OrgList" body="telephonenumber"> <!--- Search the collection ---> <!--- Use the wildcard * to contain the search string --->...
  • Page 532: Using Database-Directed Indexing

    </cfoutput> <!--- Index record set ---> <cfindex action="update" collection="pop_query" key="messagenumber" type="custom" title="subject" query="p_messages" body="body"> <!--- Search messages for the word "action" ---> <cfsearch collection="pop_query" name="s_messages" criteria="action"> <!--- Output search record set ---> <cfoutput query="s_messages"> #key#, #title# <br> </cfoutput> Using database-directed indexing You can use the tag with a database that contains information on how to construct, or cfindex...
  • Page 533 <cfindex collection="snippets" action="update" type="file" query="bookquery" key="description" urlpath="url"> </cfoutput> </body> </html> Use the following code to search the snippets collection and display the results: <cfsearch name="mySearch" collection="snippets" criteria="*.,.*"> <cfdump var="#mySearch#"> The following code shows how to populate the snippets collection with paths that are specified in the description column of the database: <html>...
  • Page 534 Chapter 24: Building a Search Interface...
  • Page 535: Chapter 25: Using Verity Search Expressions

    CHAPTER 25 Using Verity Search Expressions This chapter describes Verity search expressions and how you can refine your searches to yield the most accurate results. Contents About Verity query types ........... . 536 Using simple queries .
  • Page 536: About Verity Query Types

    About Verity query types When you search a Verity collection, you can use either a simple or explicit query. The following table compares the two types: Use of operators Query type Content and modifiers CFML example Simple One or more Uses STEM operator <cfsearch name = "band_search"...
  • Page 537: Stemming In Simple Queries

    Stemming in simple queries By default, Verity interprets words in a simple query as if you entered the STEM operator (and MANY modifier). The STEM operator searches for words that derive from a common stem. For example, a search for instructional returns files that contain instruct, instructs, instructions, and so on.
  • Page 538: Preventing Stemming

    The results of this search show the effects of the STEM operator and MANY modifier: In CFML, enter your search term(s) in the attribute of the tag: criteria cfsearch <cfsearch name="search_name" collection="bbb" type="simple" criteria="instructional"> Preventing stemming When entering text on a search form, you can prevent Verity from implicitly adding the STEM operator by doing one of the following: •...
  • Page 539: Using Explicit Queries

    Using explicit queries In an explicit query, the Verity search engine literally interprets your search terms. The following are two ways to perform an explicit query: • On a search form, use quotation marks around your search term(s). • In CFML, use ”...
  • Page 540: Using Wildcards And Special Characters

    The following table gives examples of searches and their results: Search term Returns files that contain doctorate AND nausea both doctorate and nausea doctorate “and” nausea the phrase doctorate and nausea “doctorate and nausea” the phrase doctorate and nausea masters OR doctorate AND nausea masters, or the combination of doctorate and nausea masters OR (doctorate AND nausea) masters, or the combination of doctorate and nausea...
  • Page 541 To search for a wildcard character as a literal, place a backslash character before it; for example: • To match a question mark or other wildcard character, precede the ? with one backslash. For example, type the following in a search form: Checkers\? •...
  • Page 542: Composing Search Expressions

    You can use paired backquotes or backslashes to escape special characters. There is no functional difference between the two. For example, you can query for the term: <DDA> using \<DDA\> as your search term. `<DDA>` Composing search expressions The following rules apply to the composition of search expressions. Case sensitivity Verity searches are case-sensitive only when the search term is entered in mixed case.
  • Page 543: Precedence Rules

    Precedence rules Expressions are read from left to right. The AND operator takes precedence over the OR operator; however, terms enclosed in parentheses are evaluated first. When the search engine encounters nested parentheses, it starts with the innermost term. Example Search result Moses AND Larry OR Jerome documents that contain Moses and Larry, or Jerome...
  • Page 544 The following operator types are available: Operator type Purpose Concept Identifies a concept in a document by combining the meanings of search elements. Relational Searches fields in a collection. Evidence Specifies basic and intelligent word searches. Proximity Specifies the relative location of words in a document. Score Manipulates the score returned by a search element.
  • Page 545 Operator Description Selects documents that contain all of the search elements that you specify. A score of 1.00 is assigned to each retrieved document. ALL and AND retrieve the same results, but queries using ALL are always assigned a score of 1.00. Selects documents that contain at least one of the search elements that you specify.
  • Page 546 The following relational operators compare text and match words and parts of words: Operator Description Example CONTAINS Selects documents by matching the word or • In a document field named phrase that you specify with the values stored in TITLE, to retrieve documents a specific document field.
  • Page 547 To locate documents whose source is Computer, Computerworld, Computer Currents, and PC Computing, enter the following: SOURCE <MATCHES> *comput* For an example of ColdFusion code that uses the CONTAINS relational operator, see “Field searches” on page 553. You can use the SUBSTRING operator to match a character string with data stored in a specified data source.
  • Page 548 Search Results -- should be 1 row <br> <cfoutput query="GetText_Search"> #GetText_Search.TITLE# <br> </cfoutput> Evidence operators Evidence operators let you specify a basic word search or an intelligent word search. A basic word search finds documents that contain only the word or words specified in the query. An intelligent word search expands the query terms to create an expanded word list so that the search returns documents that contain variations of the query terms.
  • Page 549 The following example uses an evidence operator: <cfsearch name = "quick_search" collection="bbb" type = "explicit" criteria="<WORD>film"> Proximity operators Proximity operators specify the relative location of specific words in the document. To retrieve a document, the specified words must be in the same phrase, paragraph, or sentence. In the case of NEAR and NEAR/N operators, retrieved documents are ranked by relevance based on the proximity of the specified words.
  • Page 550 The following example uses a proximity operator: <cfsearch name = "quick_search" collection="bbb" type = "explicit" criteria="red<near>socks"> For an example using the IN proximity operator to search XML documents , see “Zone searches” on page 552. Score operators Score operators control how the search engine calculates scores for retrieved documents. The maximum score that a returned search element can have is 1.000.
  • Page 551 Modifiers You combine modifiers with operators to change the standard behavior of an operator in some way. The following table describes the available modifiers: Modifier Description Example CASE Specifies a case-sensitive search. Normally, <CASE>Java OR <CASE>java retrieves Verity searches are case-insensitive for search documents that contain Java or java, text entered in all uppercase or all lowercase, but not JAVA.
  • Page 552: Refining Your Searches With Zones And Fields

    Refining your searches with zones and fields One of the strengths of Verity is its ability to perform full-text searches on documents of many formats. However, there are often times when you want to restrict a search to certain portions of a document, to improve search relevance.
  • Page 553 The above search for Pete returns this XML file because this search target is in the COMMENT_A field. In contrast, Pete is the lead guitarist in the following XML file: <band.xml> <Lead_Guitar>Pete</Lead_Guitar> <Rhythm_Guitar>Roger</Rhythm_Guitar> <Bass_Guitar>John</Bass_Guitar> <Drums>Kenny</Drums> <COMMENT_A>Who knows who's better than this band?</COMMENT_A> <COMMENT_B>Ticket prices correlated with decibels.</COMMENT_B>...
  • Page 554 You can specify the values for the attributes TITLE, KEY, URL, and CUSTOM as cfindex document fields for use with relational operators in the attribute. (The SCORE and criteria SUMMARY attributes are automatically returned by a ; these attributes are different for cfsearch each record of a collection as the search criteria changes.) Text comparison operators can reference the following document fields:...
  • Page 555 The following code shows the tag for indexing the collection (the attribute is set to cfindex type custom for tablular data): <cfindex query = "Calls" collection = "training" action = "UPDATE" type = "CUSTOM" title = "Short_Description" key = "Call_ID" body = "Problem_Description"...
  • Page 556 Chapter 25: Using Verity Search Expressions...
  • Page 557 HTML form tag, CFML cfform tag, and other ColdFusion tags to request data from users; how to use the cfchart tag to graphically display data; and how to use the Flash Remoting service to provide information to Macromedia Flash applications for display.
  • Page 559: Chapter 26: Retrieving And Formatting Data

    CHAPTER 26 Retrieving and Formatting Data This chapter explains how to use HTML forms to control the data displayed by a dynamic web page. It also describes how to populate an HTML table with query results and how to use ColdFusion functions to format and manipulate data.
  • Page 560: Using Forms To Specify The Data To Retrieve

    Using forms to specify the data to retrieve In the examples in previous chapters, you retrieved all of the records from a database table using a SQL query. However, there are many instances when you want to retrieve data based on certain criteria.
  • Page 561: Form Controls

    Form controls Within the form, you describe the form controls needed to gather and submit user input. There are a variety of form controls types available. You select form control input types based on the type input you want to user to provide. The following figure shows an example form containing different form controls: The following table shows the format of form control tags: Control...
  • Page 562 <!--- define the action page in the form tag. The form variables will pass to this page when the form is submitted ---> <form action="actionpage.cfm" method="post"> <!-- text box --> <p> First Name: <input type="Text" name="FirstName" size="20" maxlength="35"><br> Last Name: <input type="Text" name="LastName" size="20" maxlength="35"><br> Salary: <input type="Text"...
  • Page 563: Form Notes And Considerations

    Reviewing the code The following table describes the highlighted code and its function: Code Description Gathers the information from this form using the <form action="actionpage.cfm" method="post"> Post method, and do something with it on the page actionpage.cfm. Creates a text box called FirstName where users can <input type="Text"...
  • Page 564: Working With Action Pages

    • Check boxes, radio buttons, and multiple select boxes do not pass to action pages unless they are selected on a form. If you try to reference these variables on the action page, you receive an error if they are not present. For information on how to determine if a variable exists on the action page, see “Testing for a variable's existence”...
  • Page 565: Creating Action Pages

    However, instead of putting the LastName directly in the SQL WHERE clause, you can use the text that the user entered in the form for comparison: <cfquery name="GetEmployees" datasource="CompanyInfo"> SELECT FirstName, LastName, Salary FROM Employee WHERE LastName=<cfqueryparam value="#Form.LastName#" CFSQLType="CF_SQL_VARCHAR"> </cfquery> For security, this example encapsulates the form variable within the tag to ensure cfqueryparam...
  • Page 566: Testing For A Variable's Existence

    Reviewing the code The following table describes the highlighted code and its function: Code Description Queries the data source CompanyInfo and names the <cfquery name="GetEmployees" datasource="CompanyInfo"> query GetEmployees. SELECT FirstName, LastName, Salary Retrieves the FirstName, LastName, and Salary fields FROM Employee from the Employee table, but only if the value of the WHERE LastName=<cfqueryparam LastName field matches what the user entered in the...
  • Page 567: Form Variable Notes And Considerations

    To require entry in an input field, use a hidden field that has a attribute composed of the name field name and the suffix "_required." For example, to require that the user enter a value in the FirstName field, use the following syntax: <input type="hidden"...
  • Page 568 <body> <cfquery name="GetEmployees" datasource="CompanyInfo"> SELECT FirstName, LastName, Salary FROM Employee WHERE LastName=<cfqueryparam value="#Form.LastName#" CFSQLType="CF_SQL_VARCHAR"> </cfquery> <h4>Employee Data Based on Criteria from Form</h4> <table> <tr> <th>First Name</th> <th>Last Name</th> <th>Salary</th> </tr> <cfoutput query="GetEmployees"> <tr> <td>#FirstName#</td> <td>#LastName#</td> <td>#Salary#</td> </tr> </cfoutput> </table> <br> <cfif IsDefined("Form.Contractor")>...
  • Page 569: Formatting Individual Data Items

    Formatting individual data items You can format individual data items. For example, you can format the Salary field as a monetary value. To format the Salary using the dollar format, you use the CFML expression DollarFormat(number) To change the format of the Salary: Open the file actionpage.cfm in your editor.
  • Page 570: Returning Results To The User

    <tr> <th>First Name</th> <th>Last Name</th> <th>Salary</th> </tr> <cfoutput query="GetEmployees"> <tr> <td>#FirstName#</td> <td>#LastName#</td> <td>#Salary#</td> </tr> </cfoutput> </table> </body> </html> Save the file. View formpage.cfm in your browser. Select a department, optionally enter a last name, and submit the form. Reviewing the code The following table describes the highlighted code and its function: Code Description...
  • Page 571: Handling No Query Results

    Handling no query results Your code must accommodate the cases where a query does not return any records. To determine whether a search has retrieved records, use the query variable. You can use the RecordCount variable in a conditional logic expression that determines how to display search results appropriately to users.
  • Page 572: Returning Results Incrementally

    <table> <tr> <th>First Name</th> <th>Last Name</th> <th>Salary</th> </tr> <cfoutput query="GetEmployees"> <tr> <td>#FirstName#</td> <td>#LastName#</td> <td>#Salary#</td> </tr> </cfoutput> </cfif> </table> </body> </html> Save the file. Return to the form, enter search criteria, and submit the form. If no records match the criteria you specified, the message appears. Returning results incrementally You can use the tag to incrementally output long-running requests to the browser before...
  • Page 573 The following example uses the tag and the random number generating function to cfloop Rand artificially delay the generation of data for display. It simulates a situation in which it takes time to retrieve the first data and additional information becomes available slowly. <html>...
  • Page 574: Dynamically Populating List Boxes

    Code Description <cfloop index="Myindex" from="1" Generates and displays 10 random numbers. This to="10" step="1"> code uses two loops. The outer loop repeats ten <cfloop index="randomindex" times, once for each number to display. The inner from="1" to="100000" step="1"> loop uses the function to create another delay Rand <cfset random=rand()>...
  • Page 575 <select name="City"> <cfoutput query="GetDepartments"> <option value="#GetDepartments.Location#"> #GetDepartments.Location# </option> </cfoutput> </select> <!-- radio buttons --> <p> Department:<br> <input type="radio" name="Department" value="Training">Training<br> <input type="radio" name="Department" value="Sales">Sales<br> <input type="radio" name="Department" value="Marketing">Marketing<br> <input type="radio" name="Department" value="HR">HR<br> </p> <!-- check box --> <p> Contractor? <input type="checkbox" name="Contractor" value="Yes" checked>Yes </p>...
  • Page 576: Creating Dynamic Check Boxes And Multiple-Selection List Boxes

    Creating dynamic check boxes and multiple-selection list boxes When an HTML form contains either a list of check boxes with the same name or a multiple- selection list box (that is, where users can select multiple items from the list), the user's entries are made available as a comma-delimited list with the selected values.
  • Page 577 The ColdFusion server sends the following statement to the database: SELECT * FROM Departmt WHERE Dept_ID IN ( 2,4 ) Handling string values To search for a database field containing string values (instead of numeric), you must modify the syntax. checkbox cfquery The first example searched for department information based on a numeric primary key field...
  • Page 578: Multiple Selection Lists

    Multiple selection lists ColdFusion treats the result when a user selects multiple choices from a list box (HTML input type with attribute ) just like results of selecting multiple check boxes. The data select multiple made available to your page from any multiple selection list box is a comma-delimited list of the entries selected by the user;...
  • Page 579: Validating Form Field Data Types

    The following statement is sent to the database: SELECT * FROM Departmt WHERE Dept_Name IN ('Marketing','Sales') Validating form field data types One limitation of standard HTML forms is that you cannot validate that users input the type or range of data you expect. ColdFusion enables you to do several types of data validation by adding hidden fields to forms.
  • Page 580 To validate the data that users enter in the insert form: Create a new page with the following text: <html> <head> <title>Simple Data Form</title> </head> <body> <h2>Simple Data Form</h2> <!--- Form part ---> <form action="datatest.cfm" method="Post"> <input type="hidden" name="StartDate_required" value="You must enter a start date."> <input type="hidden"...
  • Page 581 Because numeric values often contain commas and dollar signs, these characters are automatically deleted from fields with , or rules before the form field is validated and _integer _float _range the data is passed to the form's action page. Reviewing the code The following table describes the code and its function: Code Description...
  • Page 582 Chapter 26: Retrieving and Formatting Data...
  • Page 583: Chapter 27: Building Dynamic Forms

    CHAPTER 27 Building Dynamic Forms This chapter describes how to use the tag to enrich your HTML forms with sophisticated cfform graphical controls, including several Java applet-based controls. You can use these controls without writing a line of Java code. Contents Creating forms with the cfform tag .
  • Page 584: Creating Forms With The Cfform Tag

    Creating forms with the cfform tag You already learned how to use HTML forms to gather user input (see Chapter 26, “Retrieving and Formatting Data,” on page 559). This chapter shows you how to use the tag to create cfform dynamic forms in CFML.
  • Page 585: Preserving Input Data With Preservedata

    Control Description For more information cfselect Drop-down list box not a Java applet). “Building drop-down list boxes” Equivalent to the HTML select tag with the on page 593. addition of input validation and data binding. cfapplet Embed your own Java applets in the form. “Embedding Java applets”...
  • Page 586: Building Tree Controls With Cftree

    Because Java is handled by the plug-in and not directly by the browser, disabling Java execution in the browser does not affect the operation of the controls. If for some other reason, however, the browser is unable to render the controls as requested, a "notsupported" message appears in place of the control.
  • Page 587: Grouping Output From A Query

    The following figure shows the output of this code: Reviewing the code The following table describes the highlighted code and its function: Code Description Creates a tree and name it tree1. <cftree name="tree1" Specifies that a user must select an item in the tree. required="Yes"...
  • Page 588 To organize the tree based on ordered results of a query: Create a ColdFusion page named tree2.cfm with the following content: <!--- CFQUERY with an ORDER BY clause ---> <cfquery name="deptquery" datasource="CompanyInfo"> SELECT Dept_ID, FirstName + ' ' + LastName AS FullName FROM Employee ORDER BY Dept_ID...
  • Page 589: The Cftree Form Variables

    Reviewing the code The following table describes the highlighted code and its function Code Description Order the query results by department. ORDER BY Dept_ID Populate the tree with the Department ID, and under each <cftreeitem value="Dept_ID,FullName" department, the Full Name for each employee in the department.
  • Page 590: Structuring Tree Controls

    Structuring tree controls Tree controls built with can be very complex. Knowing how to specify the relationship cftree between multiple entries helps you handle the most complex of constructs. cftreeitem cftree Creating a one-level tree control The following example consists of a single root and a number of individual items: <cfquery name="deptquery"...
  • Page 591: Image Names In A Cftree

    The following code populates the tree directly, not from a query: <cfform name="form2" action="cfform_submit.cfm"> <cftree name="tree1" hscroll="No" vscroll="No" border="No"> <cftreeitem value="Divisions"> <cftreeitem value="Development" parent="Divisions" img="folder"> <cftreeitem value="Product One" parent="Development"> <cftreeitem value="Product Two" parent="Development"> <cftreeitem value="GUI" parent="Product Two" img="document"> <cftreeitem value="Kernel" parent="Product Two"...
  • Page 592: Embedding Urls In A Cftree

    <cftree name="oak" highlighthref="Yes" height="100" width="200" hspace="100" vspace="6" hscroll="No" vscroll="No" border="No"> <cftreeitem value="Important Links"> <cftreeitem value="Macromedia Home" parent="Important Links" img="document" href="http://www.macromedia.com"> <cftreeitem value="ColdFusion Home" parent="Important Links" img="document" href="http://www.coldfusion.com"> </cftree> </cfform> Save the page and view it in your browser. The following figure shows the output of this code:...
  • Page 593: Specifying The Tree Item In The Url

    The following table describes the highlighted code and its function: Code Description href="http:// Makes the node of the tree a link. www.macromedia.com"> href="http:// Makes the node of the tree a link. www.coldfusion.com"> Although this example does not show it, href can refer to the name of a column in a query if that query populates the tree item.
  • Page 594: Building Text Input Boxes

    size="8"> </cfselect> <br><input type="Submit" value="Submit"> </cfform> Save the file as selectbox.cfm and view it in your browser. The following figure shows the output of this code: Because the tag includes the attribute, the user can select multiple entries in the list multiple box.
  • Page 595: Building Slider Bar Controls

    Save the file as textentry.cfm and view it in your browser. The following figure shows the output of this code: To get the value of the input text in the action page, use the variable Form.textinput_name; in this case, Form.entertext. Building slider bar controls You can use the control in a...
  • Page 596: Working With A Data Grid And Entering Data

    You can also do the following tasks with cfgrid • Sort data in the grid alphanumerically • Update, insert, and delete data • Display images in the grid Users can sort the grid entries in ascending order by double-clicking any column header. Double- clicking again sorts the grid in descending order.
  • Page 597 Action Procedure Editing a grid cell Double-click the cell. You must press Return when you finish entering the data. Deleting a row Click any cell in the row and click the Delete button. Inserting a row Click the Insert button. An empty row appears at the bottom of the grid.
  • Page 598 Reviewing the code The following table describes the highlighted code and its function: Code Description Create a grid named "employee_grid" and populate it with the <cfgrid name="employee_grid" query="empdata" results of the query "empdata". If you specify a cfgrid tag with a attribute defined and query no corresponding...
  • Page 599: Creating An Editable Grid

    Creating an editable grid You can build grids to allow users to edit data within them. Users can edit individual cell data, as well as insert, update, or delete rows. To enable grid editing, you specify selectmode="edit" tag. cfgrid To let users add or delete grid rows, you also have to set the attributes in insert delete...
  • Page 600 How user edits are returned ColdFusion creates the following arrays as Form variables to return edits to grid rows and cells: Array reference Description gridname.colname[change_index] Stores the new value of an edited cell. gridname.Original.colname Stores the original value of the edited grid cell. [change_index] gridname.RowStatus.Action Stores the edit type made to the edited grid row: D for...
  • Page 601 Editing data in cfgrid To enable grid editing, specify the attribute. When enabled, a user can edit selectmode="edit" cell data and insert or delete grid rows. When the user submits a tag containing a cfform cfgrid tag, data about changes to grid cells gets returned in the one-dimensional arrays described in the preceding section.
  • Page 602 The following figure shows the output of this code: The following sections describe how to write handle_grid.cfm to process user edits to the grid. Reviewing the code The following table describes the code and its function: Code Description Populates a control with data from the empdata query.
  • Page 603 Updating the database with cfgridupdate tag provides a simple mechanism for updating the database, including cfgridupdate inserting and deleting records. It can add, update, and delete records simultaneously. It is particularly convenient because it automatically handles collecting the changes from the cfgrid various form variables and generates appropriate SQL statements to update your data source.
  • Page 604 To update the data source with cfquery: Create a ColdFusion page with the following content: <html> <head> <title>Catch submitted grid values</title> </head> <body> <h3>Grid values for Form.employee_grid row updates</h3> <cfif isdefined("Form.employee_grid.rowstatus.action")> <cfloop index = "Counter" from = "1" to = #arraylen(Form.employee_grid.rowstatus.action)#>...
  • Page 605 VALUES (<cfqueryparam value="#Form.employee_grid.LastName[Counter]#" CFSQLType="CF_SQL_VARCHAR" >, <cfqueryparam value="#Form.employee_grid.Dept_ID[Counter]#" CFSQLType="CF_SQL_INTEGER" >) </cfquery> </cfif> </cfloop> </cfif> Click <a href="grid2.cfm">here</a> to display updated grid. </body> </html> Rename your existing handle_grid.cfm file as handle_grid2.cfm to save it, then save this file as handle_grid.cfm. View grid2.cfm in your browser, make changes to the grid, and then submit them. Reviewing the code The following table describes the code and its function: Code...
  • Page 606: Embedding Java Applets

    Code Description <cfelseif Otherwise, if the action is to insert a row, Form.employee_grid.rowstatus.action[counter] is generates a SQL INSERT query to "I"> insert the employee’s last name and department ID from the grid row into the <cfquery name="InsertNewEmployee" database. The INSERT assumes that datasource="CompanyInfo">...
  • Page 607 The Java Applets page appears. Click the Register New Applet button. The Add/Registered Java Applet page appears. Enter options for the following settings: Setting Description Applet Name Applet name. Code Name of the file that contains the applet subclass. Must be relative to the code base URL.
  • Page 608: Using Cfapplet To Embed An Applet

    Field Description Height Enter a measurement in pixels for the vertical space for the applet. Width Enter a measurement in pixels for the horizontal space for the applet. Vspace Enter a measurement in pixels for the space above and below the applet. Hspace Enter a measurement in pixels for the space on each side of the applet.
  • Page 609: Handling Form Variables From An Applet

    Handling form variables from an applet tag requires you to specify a form variable name for the applet. This variable, cfapplet referenced like other ColdFusion form variables, holds the value the applet Form.variable_name method returns when it is executed in the cfform Not all Java applets return values.
  • Page 610: Validating With Regular Expressions

    When you specify an input type in the attribute, ColdFusion tests for the specified validate input type when you submit the form, and submits form data only on a successful match. A successful form submission returns the value True and returns the value False if validation fails. Validating with regular expressions You can use regular expressions to match and validate the text that users enter in cfinput...
  • Page 611 • You can make regular expressions case insensitive by substituting individual characters with character sets, for example, [Nn][Ii][Cc][Kk]. • You can use the following escape sequences to match specific characters or character classes: Escape Escape Matches Meaning [\b] Backspace Any of the following white space characters: space, tab, form feed, and line feed.
  • Page 612 • The dollar sign ($) at the end of a regular expression matches the end of the field. • The concatenation of regular expressions creates a regular expression that matches the corresponding concatenation of strings. For example, [A-Z][a-z]* matches any capitalized word.
  • Page 613: Input Validation With Javascript

    Exact and partial matches Entered data is normally valid if any of it matches the regular expression pattern. Often you might ensure that the entire entry matches the pattern. If so, you must “anchor” it to the beginning and end of the field as follows: •...
  • Page 614: Handling Failed Validation

    ColdFusion passes the following arguments to the JavaScript function you specify in the attribute: onvalidate • The form object • The JavaScript input object corresponding to the tag whose value is being validated • The value of the control to validate For example, if you code the tag as the following: cfinput...
  • Page 615: Example: Validating An E-Mail Address

    Example: validating an e-mail address The following example validates an e-mail entry. If the string is invalid, it displays a message box. If the address is valid, it redisplays the page. To be valid, the e-mail address must not be an empty string, contain an at sign (@) that is at least the second character, and contain a period (.) that is at least the fourth character.
  • Page 616 Reviewing the code The following table describes the highlighted code and its function: Code Description JavaScript code that tests for valid entry in <script> <!-- the text box. The if statement checks to function testbox(form) { making sure that the field is not empty and Ctrl = Form.inputbox1;...
  • Page 617: Chapter 28: Charting And Graphing Data

    CHAPTER 28 Charting and Graphing Data This chapter explains how to use the tag to display charts and graphs. It describes ways cfchart that you can chart data and gives you the tools you need to create effective charts. Contents Creating a chart .
  • Page 618: Creating A Chart

    Creating a chart The ability to display data in a chart or graph can make data interpretation much easier. Rather than present a simple table of numeric data, you can display a bar, pie, line, or other applicable type of chart using colors, captions, and a two-dimensional or three-dimensional representation of your data.
  • Page 619: Creating A Basic Chart

    Creating a basic chart To create a chart, you use the tag along with at least one tag. You can cfchart cfchartseries optionally include one or more tags within a tag. The following cfchartdata cfchartseries table describes these tags: Description cfchart Specifies the container in which the chart appears.
  • Page 620: Administering Charts

    In this example, the data from the query column AvgByDept supplies the data for the y-axis, and the query column Dept_Name provides the data for the x-axis. The resulting chart looks like the following: Administering charts Use the ColdFusion MX Administrator to administer charts. In the Administrator, you can choose to save cached charts in memory or to disk.
  • Page 621: Charting Data

    Charting data One of the most important considerations when you chart data is the way you supply the data to tag. You can supply data in the following ways: cfchart • Provide all the data in a single query using tags.
  • Page 622 To chart a query of queries: Create a new ColdFusion page with the following content: <!-- Get the raw data from the database. --> <cfquery name="GetSalaries" datasource="CompanyInfo"> SELECT Departmt.Dept_Name, Employee.Salary FROM Departmt, Employee WHERE Departmt.Dept_ID = Employee.Dept_ID </cfquery> <!-- Generate a query with statistical data for each department. --> <cfquery dbtype = "query"...
  • Page 623 Save the page as chartdata.cfm in myapps under the web root directory. For example, the directory path on Windows might be C:\Inetpub\wwwroot\myapps. Return to your browser and enter the following URL to view chartdata.cfm: http://127.0.0.1/myapps/chartdata.cfm The following figure appears: Note: If a query contains two rows with the same value for the itemColumn, ColdFusion graphs the last row in the query for that value.
  • Page 624: Charting Individual Data Points

    Code Description <cfloop index="i" from="1" Loop through all the rows in DeptSalaries query and to="#DeptSalaries.RecordCount#"> round the salary data to the nearest thousand. This <cfset DeptSalaries.AvgByDept[i]= loop uses the query variable RecordCount to get the Round(DeptSalaries.AvgByDept[i] number of rows and changes the contents of the /1000)*1000>...
  • Page 625: Combining A Query And Data Points

    tag lets you specify the following information about a data point: cfchartdata Attribute Description value The data value to be charted. This attribute is required. item (Optional) The description for this data point. The item appears on the horizontal axis of bar and line charts, on the vertical axis of horizontal bar charts, and in the legend in pie charts.
  • Page 626 The following figure shows these options for combining two bar charts: clustered stacked percent You can also combine chart types. The following is a combination bar and line chart: The only chart type that you cannot mix with others is the pie chart. If you define one of the data series to use a pie chart, no other chart will appear.
  • Page 627: Writing A Chart To A Variable

    <cfchartseries type="bar" query="DeptSalaries" valueColumn="AvgByDept" itemColumn="Dept_Name" seriesColor="gray" paintStyle="plain" seriesLabel="Dept. Average Salaries" /> </cfchart> Save the page as chart2queries.cfm in myapps under the web root directory. For example, the directory path on Windows might be C:\Inetpub\wwwroot\myapps. Return to your browser and enter the following URL to view chart2queries.cfm: http://127.0.0.1/myapps/chart2queries.cfm Writing a chart to a variable In some cases, your application might have charts that are static or charts that, because of the...
  • Page 628 <cffile action="WRITE" charset="ISO-8859-1" file="c:\inetpub\wwwroot\charts\vehicle.jpg" output="#myChart#"> <img src="/charts/vehicle.jpg" height=240 width=320> Save the page as chartToFile.cfm in myapps under the web root directory. Return to your browser and enter the following URL to view chartToFile.cfm: http://127.0.0.1/myapps/chartToFile.cfm The chart is saved to disk as c:\inetpub\wwwroot\charts\vehicle.jpg Reviewing the code The following table describes the highlighted code and its function: Code...
  • Page 629: Controlling Chart Appearance

    Controlling chart appearance Use the tags to customize the appearance of your charts. cfchart cfchartseries Common chart characteristics You can optionally specify the following characteristics to on all types of charts: cfchart Chart characteristic Attributes used Description File type format Whether to send the chart to the user as a JPG, PNG, or Flash Movie (.swf) file.
  • Page 630 Chart characteristic Attributes used Description Multiple series showLegend specifies to display the chart’s legend showLegend seriesPlacement when the chart contains more than one series of data. Default is yes. specifies the location of each series seriesPlacement relative to the others. By default, ColdFusion determines the best placement based on the graph type of each series.
  • Page 631: Setting X-Axis And Y-Axis Characteristics

    Setting x-axis and y-axis characteristics You can specify the following additional characteristics to control the look of the x-axis and y-axis of charts, except for pie charts: Chart characteristic Attributes used Description Value axis scaleFrom The minimum and maximum points on the data axis. scaleTo By default the minimum is 0 or the lowest negative chart data value, and the maximum is the largest data value.
  • Page 632: Setting Pie Chart Characteristics

    valueColumn="AvgByDept" itemColumn="Dept_Name" /> </cfchart> Save the file. Return to your browser and enter the following URL to view chartdata.cfm: http://127.0.0.1/myapps/chartdata.cfm Reviewing the code The following table describes the highlighted code and its function: Code Description Set the maximum value of the vertical axis to 100000. The minimum value scaleTo = 100000 is the default, 0.
  • Page 633 GROUP BY Dept_Name </cfquery> <!--- Reformat the generated numbers to show only thousands ---> <cfloop index="i" from="1" to="#DeptSalaries.RecordCount#"> <cfset DeptSalaries.SumByDept[i]=Round(DeptSalaries.SumByDept[i]/ 1000)*1000> <cfset DeptSalaries.AvgByDept[i]=Round(DeptSalaries.AvgByDept[i]/ 1000)*1000> </cfloop> Add the following tag: cfchart <!--- Pie chart, from DeptSalaries Query of Queries ---> <cfchart tipStyle="mousedown"...
  • Page 634: Creating An Area Chart

    Reviewing the code The following table describes the highlighted code and its function: Code Description In the DeptSalaries query, add a SUM aggregation SUM(Salary) AS SumByDept, function to get the sum of all salaries per department. In the cfloop tag, round the salary sums to the <cfset DeptSalaries.SumByDept[i]= Round(DeptSalaries.SumByDept[i]/ nearest thousand.
  • Page 635 <!--- Query of Queries for average salary by start year ---> <cfquery dbtype = "query" name = "HireSalaries"> SELECT StartDate, AVG(Salary) AS AvgByStart FROM GetSalaries GROUP BY StartDate </cfquery> <!--- Round average salaries to thousands ---> <cfloop index="i" from="1" to="#HireSalaries.RecordCount#"> <cfset HireSalaries.AvgByStart[i]=Round(HireSalaries.AvgByStart[i]/ 1000)*1000>...
  • Page 636: Setting Curve Chart Characteristics

    Code Description <cfloop index="i" from="1" Round the salaries to the nearest thousand. to="#HireSalaries.RecordCount#"> <cfset HireSalaries.AvgByStart[i] =Round(HireSalaries.AvgByStart[i] /1000)*1000> </cfloop> Create a line chart using the HireSalaries query. <cfchart chartWidth=400 Chart the average salaries against the start date. BackgroundColor="##FFFF00" Limit the chart width to 400 pixels, show the chart in show3D="yes"...
  • Page 637: Dynamically Linking From A Pie Chart

    For example, to let users click on the graph to open the page moreinfo.cfm, and pass all three values to the page, you code the attribute as follows: url="moreinfo.cfm?Series=$SERIESLABEL$&Item=$ITEMLABEL$&Value=$VALUE$" The variables are not enclosed in # signs like ordinary ColdFusion variables. They are enclosed in dollar signs.
  • Page 638 <td>#FirstName# #LastName#</td> <td>#dateFormat(StartDate, "mm/dd/yyyy")#</td> <td>#numberFormat(Salary, "$999,999")#</td> <td>#Contract#</td> </tr> </cfoutput> </table> </body> </html> Save the page as Salary_details.cfm in myapps under the web root directory. Reviewing the code The following table describes the code and its function: Code Description Get the salary data for the department <cfquery name="GetSalaryDetails"...
  • Page 639: Linking To Javascript From A Pie Chart

    Part 2: making the chart dynamic Open chartdata.cfm in your editor. Edit the tag for the pie chart so it appears as follows: cfchart <cfchart font="Times" fontBold="yes" backgroundColor="##CCFFFF" show3D="yes" url="Salary_Details.cfm?Item=$ITEMLABEL$" > <cfchartseries type="pie" query="DeptSalaries" valueColumn="SumByDept" itemColumn="Dept_Name" colorlist="##6666FF,##66FF66,##FF6666,##66CCCC" /> </cfchart> Save the file. Return to your browser and enter the following URL to view chartdata.cfm: http://127.0.0.1/myapps/chartdata.cfm Click the slices of the pie chart to request Salary_details.cfm and pass in the department name...
  • Page 640 <cfchart xAxisTitle="Department" yAxisTitle="Salary Average" tipstyle=none url="javascript:Chart_OnClick('$SERIESLABEL$','$ITEMLABEL$','$VALUE$');" > <cfchartseries type="bar" seriesLabel="Average Salaries by Department"> <cfchartData item="Finance" value="75000"> <cfchartData item="Sales" value="120000"> <cfchartData item="IT" value="83000"> <cfchartData item="Facilities" value="45000"> </cfchartseries> </cfchart> Save the page as chartdata_withJS.cfm in myapps under the web root directory. Return to your browser and enter the following URL to view chartdata_withJS.cfm: http://127.0.0.1/myapps/chartdata_withJS.cfm Click the slices of the pie chart to display the pop-up window.
  • Page 641: Chapter 29: Using The Flash Remoting Service

    CHAPTER 29 Using the Flash Remoting Service Using the Macromedia Flash Remoting service of Macromedia ColdFusion MX, ColdFusion developers can work together with Macromedia Flash MX designers to build dynamic Flash user interfaces for ColdFusion applications. Contents About using the Flash Remoting service with ColdFusion ......642 Using the Flash Remoting service with ColdFusion pages .
  • Page 642: About Using The Flash Remoting Service With Coldfusion

    Using the Flash Remoting service of ColdFusion MX, ColdFusion developers can work together with Macromedia Flash MX designers to build Flash user interfaces (UIs) for ColdFusion applications. Building Flash UIs requires the separation of UI code from business logic code. User interface controls are built in Flash MX, while business logic is built in ColdFusion MX.
  • Page 643: Using The Flash Remoting Service With Coldfusion Pages

    Using the Flash Remoting service with ColdFusion pages When building a ColdFusion page that interacts with Flash movies, the directory name that contains the ColdFusion pages translates to the Flash service name in ActionScript. The individual ColdFusion page names contained in that directory translate to service functions in ActionScript.
  • Page 644 Accessing parameters passed from Flash To access variables passed from Flash movies, you append the parameter name to the Flash scope or use the array. Depending on how the values were passed from Flash, you refer Flash.Params to array values using ordered array syntax or structure name syntax. Only ActionScript objects can pass named parameters.
  • Page 645 In this example, the query results are filtered by the value of , which references Flash.paramName the first parameter in the array. If the parameters were passed as an ordered array from Flash, you use standard structure name syntax; for example: <cfset flash.result = "Variable 1:#Flash.params[1]#, Variable 2: #Flash.params[2]#">...
  • Page 646: Using Flash With Coldfusion Components

    To create a ColdFusion page that returns a incremental record set to Flash: Create a ColdFusion page, and save it as getData.cfm in the helloExamples directory. Modify getData.cfm so that the code appears as follows: <cfparam name="pagesize" default="10"> <cfif IsDefined("Flash.Params")> <cfset pagesize = Flash.Params[1]>...
  • Page 647 To create a ColdFusion component that interacts with a Flash movie: Create a ColdFusion component, and save it as flashComponent.cfc in the helloExamples directory. Modify the code in flashComponent.cfc so that it appears as follows: <cfcomponent name="flashComponent"> <cffunction name="helloWorld" access="remote" returnType="Struct"> <cfset tempStruct = StructNew()>...
  • Page 648: Using The Flash Remoting Service With Server-Side Actionscript

    In this example, the attribute of the tag supplies a short text description cffunction description of the component method. Save the file. Open the Flash MX authoring environment, and open the Service Browser. If not already present, add your Flash Remoting service URL, such as http://localhost:8500/ flashservices/gateway.
  • Page 649: Using The Flash Remoting Service With Coldfusion Java Objects

    For example, the following server-side ActionScript function definition returns a RecordSet object: function basicQuery() mydata = CF.query({datasource:"customers", sql:"SELECT * FROM myTable"}); return mydata; Note: For more information, see Chapter 30, “Using Server-Side ActionScript,” on page 651. Using the Flash Remoting service with ColdFusion Java objects You can run various kinds of Java objects with ColdFusion MX, including JavaBeans, Java classes, and Enterprise JavaBeans.
  • Page 650: Handling Errors With Coldfusion And Flash

    Handling errors with ColdFusion and Flash To help with debugging, use the tags to return error messages to the Flash cftry cfcatch Player, as in the following example: <cftry> <cfset Flash.Result = undefinedVar> <cfcatch> <cfset Flash.Result="Failed"> </cfcatch> </cftry> In this example, the first tag fails to assign the value into because of an cfset...
  • Page 651: Chapter 30: Using Server-Side Actionscript

    Using Server-Side ActionScript Macromedia ColdFusion MX server configuration includes the Macromedia Flash Remoting service, a module that lets Macromedia Flash MX developers create server-side ActionScript. These ActionScript files can directly access Macromedia ColdFusion MX query and HTTP features through two new ActionScript functions: CF.query...
  • Page 652: About Server-Side Actionscript

    Macromedia ColdFusion MX includes a module called the Macromedia Flash Remoting service that acts as a broker for interactions between Macromedia Flash MX and ColdFusion MX. Flash Remoting supports a range of object types, and lets you reference an ActionScript file that lives on a ColdFusion server.
  • Page 653: Server-Side Requirements

    Macromedia Flash MX • Macromedia ColdFusion MX • Flash Remoting Components For more information about these products, go to www.macromedia.com. Location of server-side ActionScript files You can place ActionScript files ( ) on the server anywhere below the web server’s root *.asr directory.
  • Page 654: What To Do Next

    Connecting to the Flash Remoting service Before you can use functions defined in your server-side ActionScript files, you must connect the Macromedia Flash MX movie to the server-side Flash Remoting service. To create a Flash Remoting service connection: Include the necessary ActionScript classes in the first frame of the Flash movie that will be using server-side ActionScript functions.
  • Page 655: Using Server-Side Actionscript Functions

    Since the Flash Remoting service serves as a broker for calls to server-side ActionScript functions, you must identify the Flash Remoting service URL as an argument in the function. For example: NetServices.setDefaultGatewayUrl NetServices.setDefaultGatewayURL("http://localhost:8500/flashservices") You must specify a server hostname. The default port number for the Flash Remoting service is 8500.
  • Page 656: Global And Request Scope Objects

    Using results returned by the CF.query function You use functions in the RecordSet ActionScript object to access the data returned in a CF.query record set; for example, how many records are in the record set and the names of the columns. You can also use the RecordSet functions to pull the query data out of the record set.
  • Page 657: About The Cf.query Function And Data Sources

    About the Cf.query function and data sources You use the function to populate Macromedia Flash MX movie elements with data CF.query retrieved from a Macromedia ColdFusion MX data source. To use the function you do CF.query the following: To pull data into your Flash MX movie from a ColdFusion MX data source: Create a server-side ActionScript file that performs queries against a ColdFusion MX data source.
  • Page 658: Using The Cf.query Function

    You use server-side ActionScript in ColdFusion MX to return record set data to a Flash MX client from a ColdFusion MX data source. You specify the ColdFusion MX data source name and the SQL statement you execute on the data source as arguments in the function in server- CF.query side ActionScript.
  • Page 659: About The Cf.query Record Set

    Using CF.query positional argument syntax Positional arguments support a subset of arguments, and you can create more efficient CF.query code. The following is the syntax for the positional argument style: // CF.query positional argument syntax CF.query(datasource, sql); CF.query(datasource, sql, maxrows); CF.query(datasource, sql, username, password);...
  • Page 660: Building A Simple Application

    These functions are available for every RecordSet object returned by the function to the CF.query Flash MX client. You invoke these functions as follows: objectName.functionName(); For example, in the result function that you create to handle record set data returned by the function, you can reference the database column names returned in the record set using CF.query RecordSet function:...
  • Page 661: Writing The Server-Side Actionscript Function

    Writing the server-side ActionScript function The example in this section creates a search function that performs a simple search operation against a ColdFusion MX data source. This function accepts two arguments, firstName and lastName, and returns any records found that match these parameters. To create a server-side ActionScript function: Create a server-side ActionScript file that contains the following code: //search takes firstName lastName arguments...
  • Page 662: Submitting User Data To The Flash Remoting Service

    Submitting user data to the Flash Remoting service To send data to server-side ActionScript, you must create a function that passes the data from the Flash movie to server-side ActionScript. The function, applied at the frame level, collects search the user-entered data from the firstName and lastName text boxes and passes the data as function arguments to the directoryService object, which is created when the Flash movie connects to the Flash Remoting service.
  • Page 663: Checking For A Flash Remoting Service Connection

    Reviewing the code The following table describes the code and its function: Code Description suffix tells the Flash Remoting service to function search_Result _Result (resultset) return the results of the search function to this function. dataView.setDataProvider Assigns the results returned by the Flash Remoting (resultset);...
  • Page 664: Using The Cf.http Function

    HTTP header announces that the character encoding is EUC-JP: Content-Type: text/html; charset=EUC-JP Header Raw response header. For example, macromedia.com returns the following header : HTTP/1.1 200 OK Date: Mon, 04 Mar 2002 17:27:44 GMT Server: Apache/1.3.22 (Unix) mod_perl/1.26 Set-Cookie: MM_cookie=207.22.48.162.4731015262864476;...
  • Page 665: Referencing Http Post Parameters In The Cf.http Function

    Property Description Statuscode HTTP error code and associated error string. Common HTTP status codes returned in the response header include the following: 400: Bad Request 401: Unauthorized 403: Forbidden 404: Not Found 405: Method Not Allowed Referencing HTTP Post parameters in the CF.http function To pass HTTP parameters in the function, you must construct an array of objects...
  • Page 666: Using The Cf.http Get Method

    // Returns content of URL defined in url variable // This example uses positional argument style function get() url = "http://www.macromedia.com/software/coldfusion/"; //Invoke with just the url argument. Get is the default. result = CF.http(url); return result.get("Filecontent"); For more information about function properties, see in CFML Reference.
  • Page 667: Part Vi: Using Web Elements And External Objects

    PART VI Using Web Elements and External Objects This part describes how you can use web elements such as XML, web services, Enterprise JavaBeans (EJBs), JSP pages, and Java servlets in ColdFusion applications. It also describes how to use external objects, including Java, Component Object Model (COM) and Common Object Request Broker Architecture (CORBA) objects in CFML applications.
  • Page 669: Chapter 31: Using Xml And Wddx

    CHAPTER 31 Using XML and WDDX This chapter describes how to use ColdFusion to create, use, and manipulate XML documents. This chapter also presents Web Distributed Data Exchange (WDDX), an XML dialect for transmitting structured data, and describes how to use it to transfer data between applications and between CFML and JavaScript.
  • Page 670: About Xml And Coldfusion

    About XML and ColdFusion In the last few years, XML has rapidly become the universal language for representing documents and data on the web. These documents can extend beyond the traditional concept of a paper document or its equivalent. For example, XML is often used to represent database or directory information.
  • Page 671: The Xml Document Object

    The XML document object ColdFusion represents an XML document as an object, called an XML document object, that is much like a standard ColdFusion structure. In fact, most ColdFusion structure functions, such as , work with XML document objects. For a full list of ColdFusion functions that StructInsert work on XML document objects, see “Functions for XML object management”...
  • Page 672: Dom Node View

    DOM node view The DOM node view presents the XML document object using the same format as the document’s XML Document Object Model (DOM). In fact, an XML document object is a representation of a DOM object. The DOM is a World Wide Web Consortium (W3C) recommendation (specification) for a platform- and language-neutral interface to dynamically access and update the content, structure, and style of documents.
  • Page 673: Xml Document Structures

    XML document structures An XML document object is a structure that contains a set of nested XML element structures. The following figure shows a section of the tag output for the document object for the cfdump XML in “A simple XML document” on page 671.
  • Page 674 The following code displays this output. It assumes that you save the code in a file under your web root, such as C:\Inetpub\wwwroot\testdocs\employeesimple.xml <cffile action="read" file="C:\Inetpub\wwwroot\testdocs\employeesimple.xml" variable="xmldoc"> <cfset mydoc = XmlParse(xmldoc)> <cfdump var="#mydoc#"> The document object structure At the top level, the XML document object has the following three entries: Entry name Type Description...
  • Page 675 XML DOM node structure The following table lists the contents of an XML DOM node structure: Entry name Type Description XmlName String The node name. For nodes such as Element or Attribute, the node name is the element or attribute name. XmlType String The node XML DOM type, such as Element or Text.
  • Page 676: Coldfusion Xml Tag And Functions

    ColdFusion XML tag and functions The following table lists the ColdFusion tag ( ) and functions that create and manipulate cfxml XML documents: Tag or function Description Creates a new ColdFusion XML document object consisting of the <cfxml variable="objectName" markup in the tag body. The tag can include XML and CFML tags. [caseSensitive="Boolean"]>...
  • Page 677: Using An Xml Object

    Tag or function Description XmlSearch(objectName, Uses an XPath expression to search an XML document object and "XPathExpression") returns an array of XML elements that match the search criteria. For more information on using the function, see XmlSearch “Extracting data with XPath” on page 692.
  • Page 678: Assigning Data To An Xml Object

    • Use associative array (bracket) notation to specify an element name that contains a period or colon; for example, myotherdoc.XmlRoot["Type1.Case1"] • You can use DOM methods in place of structure entry names. For example, the following variables all refer to the value “Almanzo”...
  • Page 679 • If the component name does not match an existing element, the element names on the left and right sides of the expression must match. ColdFusion creates a new element with the name of the element on the left of the expression. If the element names do not match, it generates an error.
  • Page 680: Creating And Saving An Xml Document Object

    The value when output using XmlText is: #MyDoc.myRoot.XmlChildren[1].XmlText#<br> </cfoutput> <br> The XML text representation of Mydoc is: <cfoutput><XMP>#tostring(MyDoc)#</XMP></cfoutput> Creating and saving an XML document object The following sections show the ways you can create and save an XML document object. The specific technique you use will depend on the application and your coding style.
  • Page 681: Creating An Xml Document Object From Existing Xml

    MyDoc.MyRoot.XmlChildren[i] = XmlElemNew(MyDoc,"childNode"); MyDoc.MyRoot.XmlChildren[i].XmlText = "This is Child node " & i &"."; </cfscript> <cfdump var=#MyDoc#> Creating an XML document object from existing XML function converts an XML document or document fragment represented as a text XmlParse string into a ColdFusion document object. If the XML document is already represented by a string variable, use the tag directly on XmlParse...
  • Page 682: Functions For Xml Object Management

    Functions for XML object management The following table lists the ColdFusion array and structure functions that you can use to manage XML document objects and their functions, and describes their common uses. In several cases you can use either an array function or a structure function for a purpose, such as for deleting all of an element’s attributes or children.
  • Page 683: Treating Elements With The Same Name As An Array

    Function StructAppend Appends a document fragment XML document object to another XML document object. Adds a new entry to an structure. StructInsert XmlAttributes StructUpdate Sets or replaces the value of a document object property such as XmlName or of a specified attribute in an structure.
  • Page 684 Adding Use the following techniques to add new information to an element: Type Using a function Using an assignment statement StructInsert Attribute (xmlElemPath.XmlAttributes, xmlElemPath.XmlAttributes.key = "key", "value") "value" xmlElemPath.XmlAttributes["key"] = "value" Child To append: To append: element ArrayAppend (xmlElempath.XmlChildren, xmlElemPath.XmlChildren[i] = newElem) newElem To insert:...
  • Page 685: Adding, Deleting, And Modifying Xml Elements

    Changing Use the following techniques to change the contents of an element: Type Using a function Using an assignment statement StructUpdate Property (xmlElemPath, xmlElemPath.propertyName = "propertyName", "value") "value" xmlElemPath["propertyName"] = "value" Attribute StructUpdate(xmlElemPath.XmlAttributes, xmlElemPath.XmlAttributes. "attributeName", "value") attributeName="value" xmlElemPath.XmlAttributes ["attributeName"] = "value" Child ArraySet Replace first or only child named...
  • Page 686 if (xmlElement.XmlChildren[i].XmlName IS nodeName) nodesFound = nodesFound + 1; return nodesFound; </cfscript> The following lines use this function to display the number of nodes named “name” in the mydoc.employee element: <cfoutput> Nodes Found: #NodeCount(mydoc.employee, "name")# </cfoutput> Determining the position of a child element with a common name function determines the location in the array of a specific XmlChildPos...
  • Page 687 If you have multiple child elements with the same name, and you want to insert a new element in a specific position, use the function to determine the location in the XmlChildPos XmlChildren array where you want to insert the new element. For example, the following code determines the location of mydoc.employee.name[1] and inserts a new name element as the second name element: <cfscript>...
  • Page 688 When you copy an element, the new element must have the same name as the existing element. If you specify the new element by name on the left side of an assignment, the element name must be the same as the name on the right side. For example, the following expression causes an error: <cfset mydoc.employee.name[2].telephne = mydoc.employee.name[1].phoneNumber>...
  • Page 689 Adding, changing, and deleting element attributes You modify an element’s attributes the same way you change the contents of any structure. For example, each of the following lines adds a Status attribute the second mydoc.employee.name element: <cfset mydoc.employee.name[2].XmlAttributes.Status="Inactive"> <cfset StructInsert(mydoc.employee.name[2].XmlAttributes, "Status", "Inactive")>...
  • Page 690: Using Xml And Coldfusion Queries

    To move an element, you must assign it to its new location, then delete it from its old location. For example, the following lines move the phoneNumber element from mydoc.employee.name[1] to mydoc.employee.name[2]: <cfset mydoc.employee.name[2].phoneNumber=mydoc.employee.name[1].phoneNumber> <cfset StructDelete(mydoc.employee.name[1], "phoneNumber")> Using XML and ColdFusion queries You can convert XML documents into ColdFusion query objects and manipulate them using queries of queries.
  • Page 691: Transforming Documents With Xslt

    Converting a query object to XML The following example shows how to convert a query object to XML. It uses to get a list cfquery of employees from the CompanyInfo database and saves the information as an XML document. <!--- Query the database and get the names in the employee table ---> <cfquery name="myQuery"...
  • Page 692: Extracting Data With Xpath

    Extracting data with XPath XPath is a language for addressing parts of an XML document. Like XSL, XPath is a W3C specification. One of the major uses of XPath is in XSL transformations. However, XPath has more general uses. In particular, it can extract data from XML documents, such as complex data set representations.
  • Page 693 The XML document The order.xml document has the following structure: • The root element is named order and has one attribute, id. • There is one customer element with firstname, lastname, and accountnum attributes. The customer element does not have a body •...
  • Page 694 The ColdFusion page The ColdFusion page looks like the following: <!--- Convert file to XML document object ---> <cffile action="read" file="C:\Neo\wwwroot\examples\order.xml" variable="myxml"> <cfset mydoc = XmlParse(myxml)> <!--- Extract account number ---> <cfset accountNum=#mydoc.order.customer.XmlAttributes.accountNum#> <!--- Display Order Information ---> <cfoutput> <b>Name=</b>#mydoc.order.customer.XmlAttributes.firstname# #mydoc.order.customer.XmlAttributes.lastname# <br>...
  • Page 695 AS totalPrice FROM orderquery </cfquery> <cfset discountPrice = priceQuery.totalPrice * (1 - drate/100)> <!--- Display the full price and discounted price ---> <cfoutput> <b>Full Price=</b> #priceQuery.totalPrice#<br> <b>Discount Price=</b> #discountPrice# </cfoutput> <br><br> <!---Generate an XML Receipt ---> <cfxml variable="receiptxml"> <receipt num = "34"> <cfoutput>...
  • Page 696 Reviewing the code The following table describes the CFML code and its function. For the sake of brevity, it does not include code that displays the processing results. Code Description <cffile action="read" Reads the XML from a file and convert it to an file="C:\Neo\wwwroot\examples\order.xml"...
  • Page 697: Moving Complex Data Across The Web With Wddx

    HTTP to move the data between different application server platforms and between application servers and browsers. Target platforms for WDDX include ColdFusion, Active Server Pages (ASP), JavaScript, Perl, Java, Python, COM, Macromedia Flash, and PHP. The WDDX XML vocabulary consists of a document type definition (DTD) that describes the...
  • Page 698: Uses Of Wddx

    WDDX offers the following advantages: • It can be used by lightweight clients, such as browsers or the Macromedia Flash player. • It can be used to store complex data structures in files and databases.
  • Page 699: How Wddx Works

    Applications that take advantage of WDDX can continue to do so if they start to use web services. These applications could also be converted to use web services standards exclusively; only the service and data interchange formats—not the application model—must change. How WDDX works The following example shows how WDDX works.
  • Page 700 WDDX data type support The following sections describe the data types that WDDX supports. This information is a distillation of the description in the WDDX DTD. For more detailed information, see the DTD at www.openwddx.org. Basic data types WDDX can represent the following basic data types: Data type Description Null...
  • Page 701 Data type comparisons The following table compares the basic WDDX data types with the data types to which they correspond in the languages and technologies commonly used on the web: ECMAScript/ WDDX CFML Schema Java JavaScript null null null VT_NULL boolean Boolean boolean...
  • Page 702: Using Wddx

    Using WDDX The following sections describe how you can use WDDX in ColdFusion applications. The first two sections describe the tools that ColdFusion provides for creating and converting WDDX. The remaining sections show how you use these tools for common application uses. Using the cfwddx tag tag can do the following conversions: cfwddx...
  • Page 703: Converting Cfml Data To A Javascript Object

    Converting CFML data to a JavaScript object The following example demonstrates the transfer of a recordset from a ColdFusion page cfquery executing on the server to a JavaScript object that is processed by the browser. The application consists of four principal sections: •...
  • Page 704 Click Serialize to serialize the resulting data. The resulting WDDX packet appears in the WDDX packet display box. This step is intended only for test purposes. Real applications handle the serialization automatically. Click Submit to submit the data. The WDDX packet is transferred to the server-side processing code, which deserializes it and displays the information.
  • Page 705 <!--- Data collection form ---> <form action="#cgi.script_name#" method="Post" name="personForm"> <!--- Input fields ---> Personal information<br> First name: <input type=text name=firstName><br> Last name: <input type=text name=lastName><br> <br> <!--- Navigation & submission bar ---> <input type="button" value="Next" onclick="doNext()"> <input type="button" value="Serialize" onclick="serializeData(personInfo, document.personForm.wddxPacket)"> <input type="submit"...
  • Page 706: Storing Complex Data In A String

    Storing complex data in a string The following simple example uses WDDX to store complex data, a data structure that contains arrays as a string in a client variable. It uses the tag to display the contents of the structure cfdump before serialization and after deserialization.
  • Page 707: Chapter 32: Using Web Services

    CHAPTER 32 Using Web Services Web services let you publish and consume remote application functionality over the Internet. When you consume web services, you access remote functionality to perform an application task. When you publish a web service, you let remote users access your application functionality to build it into their own applications.
  • Page 708: Web Services

    Web services Since its inception, the Internet has allowed people to access content stored on remote computers. This content can be static, such as a document represented by an HTML file, or dynamic, such as content returned from a ColdFusion page or CGI script. Web services are a new technology that lets you access application functionality, which resides on remote computers, that someone created and made available.
  • Page 709: Basic Web Service Concepts

    translationmode="en_es" sourcedata="Hello World" returnVariable='foo'> <cfoutput>#foo#</cfoutput> For more information on consuming web services, see “Consuming web services” on page 713. Basic web service concepts You must be familiar with the underlying architecture of a web service provider in order to fully understand how web services work.
  • Page 710: Working With Wsdl Files

    Describing web services with WSDL A WSDL document is an XML file that describes a web service’s purpose, where it is located, and how to access it. The WSDL document describes the operations that you can invoke and their associated data types. ColdFusion MX can generate a WSDL document from a web service, and you can publish the WSDL document at a URL to provide information to potential clients.
  • Page 711: Viewing A Wsdl File Using Dreamweaver Mx

    Viewing a WSDL file using Dreamweaver MX Dreamweaver MX contains a utility to view web services, including operation names, parameter names, and parameter data types. The following figure shows a WSDL file for the BabelFish web service: This figure shows that the web service method babelFish returns a string, and that it takes string parameters named sourcedata and translationmode as input.
  • Page 712 <portType name="BabelFishPortType"> <operation name="BabelFish"> <input message="tns:BabelFishRequest" /> <output message="tns:BabelFishResponse" /> </operation> </portType> <binding name="BabelFishBinding" type="tns:BabelFishPortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/ http" /> <operation name="BabelFish"> <soap:operation soapAction="urn:xmethodsBabelFish#BabelFish" /> <input> <soap:body use="encoded" namespace="urn:xmethodsBabelFish" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </input> <output> <soap:body use="encoded" namespace="urn:xmethodsBabelFish" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </output> </operation> </binding>...
  • Page 713: Consuming Web Services

    Consuming web services ColdFusion MX provides two methods for consuming web services. The method that you choose depends on your ColdFusion programming style and application. The following table describes these methods: Method CFML operator Description CFScript CreateObject() Consumes a web service from within a CFScript block CFML tag cfinvoke Consumes a web service from within a block of CFML code...
  • Page 714: Handling Return Values From A Web Service

    <message name="BabelFishResponse"> <part name="return" type="xsd:string" /> </message> <portType name="BabelFishPortType"> <operation name="BabelFish"> <input message="tns:BabelFishRequest" /> <output message="tns:BabelFishResponse" /> </operation> </portType> The operation name used in the examples in this section is BabelFish. This operation takes a single input parameter defined as a message of type BabelFishRequest. You can see that the message BabelFishRequest contains two string parameters: .
  • Page 715 where: • specifies the URL to the WSDL file for the web service. webservice • specifies the operation of the web service to invoke. method • specifies an input parameter passed to the operation. inputParamN • specifies the name of the variable that contains any results returned from the returnVariable web service.
  • Page 716: Using Cfscript To Consume A Web Service

    <cfinvoke webservice = "http://www.xmethods.net/sd/2001/BabelFishService.wsdl" method = "BabelFish" argumentCollection = "#stArgs#" returnVariable = "varName" > <cfoutput>#varName#</cfoutput> In this example, you create the structure in a CFScript block, but you can use any ColdFusion method to create the structure. Using CFScript to consume a web service The example in this section uses CFScript to consume a web service.
  • Page 717: Consuming Web Services That Are Not Generated By Coldfusion Mx

    Consuming web services that are not generated by ColdFusion MX To consume a web service that is implemented in a technology other than ColdFusion MX, the web service must have one of the following sets of options: • rpc as the SOAP binding style and encoding as the encodingStyle •...
  • Page 718: Handling Inout And Out Parameters

    Handling inout and out parameters Some web services define inout and out parameters. You use out parameters to pass a placeholder for a return value to a web service. The web service then returns its result by writing it to the out parameter.
  • Page 719: Data Conversions Between Coldfusion And Wsdl Data Types

    Data conversions between ColdFusion and WSDL data types A WSDL file defines the input and return parameters of an operation, including data types. For example, the BabelFish web service contains the following definition of input and return parameters: <message name="BabelFishRequest"> <part name="translationmode"...
  • Page 720 The following example shows a ColdFusion component that takes a query as input and echoes the query back to the caller: <cfcomponent> <cffunction name='echoQuery' returnType='query' access='remote'> <cfargument name='input' type='query'> <cfreturn #arguments.input#> </cffunction> </cfcomponent> If you add this web service in Dreamweaver MX, you see a description of it in the Components tab of the Application panel.
  • Page 721: Publishing Web Services

    Publishing web services To publish web services for consumption by remote applications, you create the web service using ColdFusion components. For more information on components, see Chapter 11, “Building and Using ColdFusion Components,” on page 219. Creating components for web services ColdFusion components encapsulate application functionality and provide a standard interface for client access to that functionality.
  • Page 722: Producing Wsdl Files

    As part of publishing the component for access as a web service, ColdFusion generates the WSDL file that defines the component where the WSDL file includes definitions for how ColdFusion data types map to WSDL data types. The following table shows this mapping: ColdFusion data type WSDL data type numeric...
  • Page 723 </cffunction> </cfcomponent> If you register the component in Dreamweaver MX, it appears in the Components tab of the Application panel. Requesting the WSDL file returns the following: <?xml version="1.0" encoding="UTF-8" ?> <wsdl:definitions targetNamespace="http://webservices" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:intf="http://webservices" xmlns:impl="http://webservices-impl" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <wsdl:message name="echoStringResponse">...
  • Page 724: Using Coldfusion Components To Define Data Types For Web Services

    <cfreturn #arguments.input#> </cffunction> </cfcomponent> Save this file as echo.cfc in your web root directory. Create a ColdFusion page with the following content: <cfinvoke webservice ="http://localhost/echo.cfc?wsdl" method ="echoString" input = "hello" returnVariable="foo"> <cfoutput>#foo#</cfoutput> Save this file as echoclient.cfm in your web root directory. Request echoclient.cfm in your browser.
  • Page 725 </cffunction> </cfcomponent> Note: If the component files are not in a directory under your web root, you must create a ColdFusion mapping to the directory containing them. If you register the component in Dreamweaver MX, it appears in the Components tab of the Application panel, as the following figure shows: The WSDL file for the web service contains data definitions for the complex types name and address.
  • Page 726: Securing Your Web Services

    Securing your web services You can restrict access to your published web services to control the users allowed to invoke them. You can use your web server to control access to the directories containing your web services, or you can use ColdFusion security in the same way that you would to control access to any ColdFusion page.
  • Page 727 Using ColdFusion to control access Instead of letting the web server control access to your web services, you can handle the username/password string in your Application.cfm file as part of your own security mechanism. In this case, you use the tag to retrieve the username/password information from the cflogin header, decode the binary string, and extract the username and password, as the...
  • Page 728: Best Practices For Publishing Web Services

    Using programmatic security You can implement your own security within the a function to protect resources. For example you can use the ColdFusion function to determine if a user is in particular role, as the IsUserInRole following example shows: <cffunction name="foo"> <cfif IsUserInRole("admin")>...
  • Page 729 ColdFusion data type WSDL data type void (operation returns nothing) struct* complex type This table shows that complex data types map to ColdFusion structures. ColdFusion structures offer a flexible way to represent data. You can create structures that contain single-dimension arrays, multi-dimensional arrays, and other structures.
  • Page 730 To call the updateEmployeeInfo operation, you create a ColdFusion structure, initialize six fields of the structure that correspond to the six elements of Employee, then call the operation, as the following code shows: <!--- Create a structure using CFScript, then call the web service. ---> <cfscript>...
  • Page 731: Publishing Web Services That Use Complex Data Types

    <!--- Output the returned values. ---> <cfoutput> <br> <br>Name of employee is: #myReturnVar.fname# #myReturnVar.lname# <br>Active status: #myReturnVar.active# <br>Age: #myReturnVar.age# <br>Hire Date: #myReturnVar.hiredate# <br>Favorite Number: #myReturnVar.number# </cfoutput> You access elements of the variable myReturnVar using the dot notation in the same way you access structure fields.
  • Page 732 Publishing structures A ColdFusion structure can hold an unlimited number of key-value pairs where the values can be of any ColdFusion data type. While it is a very useful and powerful way to represent data, it cannot be directly mapped to any XML data types defined in the SOAP 1.1 encoding and XML Schema specification.
  • Page 733 The following table describes the elements of QueryBean: Element name Description ColumnList String array that contains column names data 2-dimensional array that contains query data The WSDL file for a QueryBean defines these elements as follows: <complexType name="ArrayOf_SOAP-ENC_Array"> <complexContent> <restriction base="SOAP-ENC:Array"> <attribute ref="SOAP-ENC:arrayType"...
  • Page 734 Chapter 32: Using Web Services...
  • Page 735: Chapter 33: Integrating J2Ee And Java Elements In Cfml Applications

    CHAPTER 33 Integrating J2EE and Java Elements in CFML Applications This chapter describes how to integrate J2EE elements, including the following, into your ColdFusion application: • JSP pages and servlets • JSP tags • Java objects, including Enterprise JavaBeans (EJBs) It does not explain J2EE concepts or how to program using Java or JSP.
  • Page 736: About Coldfusion, Java, And J2Ee

    About ColdFusion, Java, and J2EE ColdFusion MX is built on a J2EE-compliant Java technology platform. This lets ColdFusion applications take advantage of, and integrate with, J2EE elements. ColdFusion pages can do any of the following: • Include JavaScript and client-side Java applets on the page. •...
  • Page 737: About Coldfusion And Servlets

    • JSP comments Instead, you use CFML comments. (ColdFusion ignores JSP comments and passes them to the browser.) • Standard JSP tags Such as jsp:plugin, unless your J2EE server provides access to these tags in a JAR file. Instead, you use ColdFusion tags and the PageContext object. About ColdFusion and Servlets Some Java servlets are not exposed as JSP pages;...
  • Page 738: About Cfml Variables And Java Variables

    To disable automatic class loading of your classes, put the classes in the JVM classpath. Classes located on the JVM classpath are loaded once per server lifetime. To reload these classes, stop and restart ColdFusion MX. Note: Because you put tag libraries in the web_root/WEB-INF/lib directory, ColdFusion automatically reloads these libraries if necessary when you import the library.
  • Page 739: Using Jsp Tags And Tag Libraries

    Using JSP tags and tag libraries You can use JSP tags from any JSP tag library. For example, you can use any of the custom tags in the open-source Apache Jakarta Project Taglibs project tag libraries, located at http:// jakarta.apache.org/taglibs/index.html. This project consists of a number of individual JSP custom tag libraries for purposes ranging from JNDI access to generating random text strings.
  • Page 740: Example: Using The Random Tag Library

    Example: using the random tag library The following example uses the random tag library from the Apache Jakarta Taglibs project and calls the library’s tag, which initializes a random number generator that uses a secure number algorithm to generate a six-digit random number. You get a new random number each time you reference the variable randPass.random.
  • Page 741 For example, you might want to integrate an existing JSP customer response component into a new ColdFusion order processing application. The order processing application provides the order number, total cost, and expected shipping date, and the customer response component sends the response to the e-mail address on file for the particular customer number. The ColdFusion application might use the following CFScript code to call the response JSP page: urlParams = "UID=#order.uid#&cost=#order.total#&orderNo=#order.orderNo# &shipDate=#order.shipDateNo#"...
  • Page 742: Examples: Using Jsp With Cfml

    Accessing ColdFusion application and session variables in JSP pages ColdFusion MX runs as a J2EE application on the J2EE application server. The J2EE application ServletContext is a data structure that stores objects as attributes. A ColdFusion Application scope is represented as an attribute named by the Application scope name. The attribute contains the scope values as a hash table.
  • Page 743 Reviewing the code The following table describes the CFML code and its function: Code Description Specifies the application name as myApp and enables <cfapplication name="myApp" sessionmanagement="yes"> session management. In most applications, this tag is in the Application.cfm page. Sets ColdFusion Request, Session, and Application, scope <cfscript>...
  • Page 744 Code Description <br>session.myVariable: Uses the method of the JSP session getAttribute <%= object to get the myApp object (the Application scope). ((Map)(session.getAttribute("myApp Casts this to a Java Map object and uses the get method "))). to obtain the myVariable value for display. get("myVariable")%>...
  • Page 745 Code Description <% ((Map)session.getAttribute("myApp")) Uses the method of the JSP session getAttribute .put("myVariable", "is a");%> object to get the myApp object (the Application scope). Casts this to a Java Map object and uses the method to set the myVariable value. CFML pages and JSP pages share Session variables independent of the variable name case.
  • Page 746: Using Java Objects

    Using Java objects You use the tag to create an instance of a Java object. You use other ColdFusion tags, cfobject such as , or CFScript to invoke properties (attributes), and methods cfset cfoutput (operations) on the object. Method arguments and return values can be any valid Java type; for example, simple arrays and objects.
  • Page 747 Using properties Use the following coding syntax to access properties if the object does either of the following actions: • Exposes the properties as public properties. • Does not make the properties public, but is a JavaBean that provides public getter and setter methods of the form getPropertyName() and setPropertyName(value).
  • Page 748: Creating And Using A Simple Java Class

    Note: You can use the direct reference method to get or set values in some classes that have getProperty and setProperty methods but do not conform fully to the JavaBean pattern. However, you cannot use this technique for all classes that have getProperty and setProperty methods. For example, you cannot directly reference any of the following standard Java classes, or classes derived from them: Date, Boolean, Short, Integer, Long, Float, Double, Char, Byte, String, List, Array.
  • Page 749 public Employee(String First, String Last, float salary, int grade) { FirstName = First; LastName = Last; Salary = salary; JobGrade = grade; public void SetSalary(float Dollars) { Salary = Dollars; public float GetSalary() { return Salary; public void SetJobGrade(int grade) { JobGrade = grade;...
  • Page 750 Reviewing the code The following table describes the CFML code and its function: Code Description Loads the Employee Java class and gives it an object name of <cfobject action=create type=java class=Employee emp. name=emp> Does not call a constructor. ColdFusion invokes the default <!--- <cfset emp.init()>...
  • Page 751: Java And Coldfusion Data Type Conversions

    In this example, the constructor takes four arguments: the first two are strings, the third is a float, and the fourth is an integer. Java and ColdFusion data type conversions ColdFusion does not use explicit types for variables, while Java is strongly typed. However, ColdFusion data does use a number of underlying types to represent data.
  • Page 752 CFML Java XML document object Not supported. ColdFusion component Not applicable. The following table lists how ColdFusion converts data returned by Java methods to ColdFusion data types: Java CFML boolean/Boolean Boolean byte/Byte String char/Char String short/Short Integer int/Integer Integer long/Long Integer float/Float Real Number...
  • Page 753: Handling Java Exceptions

    The ColdFusion function helps you resolve such issues by specifying the Java type of a JavaCast variable, as in the following line: <cfset emp.SetJobGrade(JavaCast(“int”, “1”))> function takes two parameters: a string representing the Java data type, and the JavaCast variable whose type you are setting. You can specify the following Java data types: boolean, int, long, float, double, and String.
  • Page 754: Examples: Using Java With Cfml

    // Return the address return address.getHostAddress(); </cfscript> <cfoutput>#gethostaddress("macromedia.com")#</cfoutput> Using an EJB ColdFusion MX can use EJBs that are served by JRun 4.0 servers. The JRun server jrun.jar file must have the same version as the jrun.jar file in ColdFusion.
  • Page 755 Name of the EJB, as registered with the naming service Install the EJB home and component interface compiled classes on your ColdFusion web server, either as class files in the web_root/WEB-INF/classes directory or packaged in a JAR file the web_root/WEB-INF/lib directory. Note: To use an EJB served by a JRUN server, your ColdFusion installation and the JRun server that hosts the EJB must have the same version of the jrun.jar file (located in cf_root\runtime\lib directory in ColdFusion).
  • Page 756 <!--- Create the Properties object and call an explicit constructor---> <CFOBJECT action=create name=prop type="JAVA" class="java.util.Properties"> <!--- Call the init method (provided by cfobject) to invoke the Properties object constructor. ---> <cfset prop.init()> <!--- Specify the properties These are required for a remote server only ---> <cfset prop.put(ctx.INITIAL_CONTEXT_FACTORY, "jrun.naming.JRunContextFactory")>...
  • Page 757 The Example class The following Java code defines the Example class. The Java class Example has one public integer member, . Its constructor initializes to 0 or an integer argument. The mPublicInt mPublicInt class has the following public methods: Method Description ReverseString Reverses the order of a string.
  • Page 758 static public int SumArray(int[] arr) { int sum=0; for (int i=0; i < arr.length; i++) { sum += arr[i]; return sum; static public Example SumObjArray(Example[] arr) { Example sum= new Example(); for (int i=0; i < arr.length; i++) { sum.mPublicInt += arr[i].mPublicInt; return sum;...
  • Page 759 after reverse element 1: #ra[1]#<br> after reverse element 2: #ra[2]#<br> after reverse element 3: #ra[3]#<br> <br> </cfoutput> <!--- Use the Java object to flip a Boolean value, reverse a string, add two integers, and add two float numbers ---> <cfset c=obj.Flip(true)> <cfset StringVal=obj.ReverseString("This is a test")>...
  • Page 760 Chapter 33: Integrating J2EE and Java Elements in CFML Applications...
  • Page 761: Chapter 34: Integrating Com And Corba Objects In Cfml Applications

    CHAPTER 34 Integrating COM and CORBA Objects in CFML Applications This chapter describes how to use the tag to invoke COM (Component Object Model) cfobject or DCOM (Distributed Component Object Model) and CORBA (Common Object Request Broker) objects. Contents About COM and CORBA........... 762 Creating and using objects .
  • Page 762: About Com And Corba

    About COM and CORBA This section provides some basic information on COM and CORBA objects supported in ColdFusion MX and provides resources for further inquiry. About objects COM and CORBA are two of the object technologies supported by ColdFusion MX. Other object technologies include Java and ColdFusion components.
  • Page 763: Creating And Using Objects

    Each CORBA object has an interface that is defined in the CORBA Interface Definition Language (IDL). The CORBA IDL describes the operations that can be performed on the object, and the parameters of those operations. Clients do not have to know anything about how the interface is implemented to make requests.
  • Page 764: Calling Methods

    Calling methods Object methods usually take zero or more arguments. You send In arguments, whose values are not returned to the caller by value. You send Out and In,Out arguments, whose values are returned to the caller, by reference. Arguments sent by reference usually have their value changed by the object.
  • Page 765: Com Requirements

    COM Requirements To use COM components in your ColdFusion application, you need at least the following items: • The COM objects (typically DLL or EXE files) that you want to use in your ColdFusion application pages. These components should allow late binding; that is, they should implement the IDispatch interface.
  • Page 766 Using the OLE/COM Object Viewer The OLE/COM Object Viewer installation installs the executable, by default, as \mstools\bin\oleview.exe. You use the Object Viewer to retrieve a COM object’s ProgID, as well as its methods and properties. To find an object in the Object Viewer, it must be registered, as described in “Registering the object”...
  • Page 767: Creating And Using Com Objects

    Right-click the object to view it, including the TypeInfo. If you view the TypeInfo, you see the object's methods and properties, as shown in the following figure. Some objects do not have access to the TypeInfo area, which is determined when an object is built and by the language used.
  • Page 768: Connecting To Com Objects

    The CDO for NTS NewMail component includes a number of methods and properties to perform a wide range of mail-handling tasks. (In the OLE/COM Object Viewer, methods and properties might be grouped together, so you could find it difficult to distinguish between them at first.) The CDO for NTS NewMail object includes the following properties: Body [ String ]...
  • Page 769: General Com Object Considerations

    <!--- Second, use the form variables from the user entry form to populate a number of properties necessary to create and send the message. ---> <cfset Mailer.From = "#Form.fromName#"> <cfset Mailer.To = "#Form.to#"> <cfset Mailer.Subject = "#Form.subject#"> <cfset Mailer.Importance = 2> <cfset Mailer.Body = "#Form.body#">...
  • Page 770 Ensuring correct threading Improper threading can cause serious problems when using a COM object in ColdFusion. Make sure that the object is thread-safe. An object is thread-safe if it can be called from many programming threads simultaneously, without causing errors. Visual Basic ActiveX DLLs are typically not thread-safe.
  • Page 771: Accessing Complex Com Objects Using Java Proxies

    Understanding common COM-related error messages The following table described some error messages you might encounter when using COM objects: Error Cause Error Diagnostic Information The COM object is not registered or does not exist. Error trying to create object specified in the tag. COM error 0x800401F3.
  • Page 772 This package will contain all the classes for the Java stubs for the COM object. Note: Macromedia uses a package name that starts with coldfusion.runtime.com.com2java for the packages that contain the preinstalled Java stubs for Microsoft Excel, Microsoft Word, and Microsoft Access.
  • Page 773 Ensure that the ColdFusion server is not running. To stop the ColdFusion server, open the Services control panel, select ColdFusion MX application server, and click Stop. (In Windows 98 or Windows ME, select Stop ColdFusion MX from the ColdFusion MX Programs item on the Start menu.) Add your .class files to the ColdFusion Microsoft application Java stubs file by doing the following:...
  • Page 774: Using The Application Scope To Improve Com Performance

    Using the Application Scope to improve COM performance The Java call to create a new COM object instance can take substantial time. As a result, creating COM objects in ColdFusion MX can be substantially slower than in ColdFusion 5. For example, on some systems, creating a Microsoft Word application object could take over one second using ColdFusion MX, while on the same system, the overhead of creating the Word object might be about 200 milliseconds.
  • Page 775 <cffunction name="getFixedDriveSpace" returnType="struct" output=True> <!--- If the FileSystemObject does not exist in the Application scope, create it. ---> <!--- For information on the use of initialization variables and locking in this code, see “Locking application variables efficiently” in Chapter 15, “Using Persistent Data and Locking”...
  • Page 776 <cfset start = GetTickCount()> <!--- If necessary, create the Word.application object and put it in the Application scope ---> <cfset WordObj_is_initialized = False> <cflock scope="application" type="readonly" timeout=120> <cfset WordObj_is_initialized = StructKeyExists(application, "MyWordObj")> </cflock> <cfif not WordObj_is_initialized > <cflock scope="Application" type="exclusive" timeout="120"> <cfif not StructKeyExists(application, "MyWordObj")>...
  • Page 777: Getting Started With Corba

    If you set the context attribute to , The attribute must be a name NameService class delimited by forward slashes (/), such as MyCompany/Department/Dev. You can use period-delimited “kind” identifiers as part of the class attribute; for example, Macromedia.current/Eng.current/CF" Creating and using CORBA objects...
  • Page 778: Using Corba Objects In Coldfusion

    Attribute Description name Specifies the name (handle) that your application uses to call the object's interface. locale (Optional) Identifies the connector configuration. You can omit this option if ColdFusion MX Administrator has only one connector configuration, or if it has multiple connector configurations and you want to use the one that is currently selected in the Administrator.
  • Page 779 The following sections describe how to call CORBA methods correctly in ColdFusion. Method name case considerations Method names in IDL are case-sensitive. However, ColdFusion is case-insensitive. Therefore, do no use methods that differ only in case in IDL. For example, the following IDL method declarations correspond to two different methods: testCall(in string a);...
  • Page 780 Using methods with return values Use CORBA methods that return values as you would any ColdFusion function; for example: double method(out double a); CFML <cfset foo=3.1415> <cfset ret=handle.method("foo")> <cfoutput>#ret#</cfoutput> Using IDL types with ColdFusion variables The following sections describe how ColdFusion supports CORBA data types. They include a table of supported IDL types and information about how ColdFusion converts between CORBA types and ColdFusion data.
  • Page 781 CORBA IDL type General support As parameters As return value double unsigned short unsigned long longlong unsigned longlong void Data type conversion The following table lists IDL data types and the corresponding ColdFusion data types: IDL type ColdFusion type boolean Boolean char One-character string...
  • Page 782 Boolean data considerations ColdFusion treats any of the following as Boolean values: True "yes", "true", or 1 False "no", "false", or 0 You can use any of these values with CORBA methods that take Boolean parameters, as the following code shows: module Tester interface TManager void testBoolean(in boolean a);...
  • Page 783: Handling Exceptions

    In this example, the CORBA object gets called with the second ( first) entry in the enumerator, a. Double-byte character considerations If you are using an ORB that supports CORBA later than version 2.0, you do not have to do anything to support double-byte characters.
  • Page 784: Corba Example

    CORBA example The following code shows an example of using a LoanAnalyzer CORBA object. This simplified object determines whether an applicant is approved for a loan based on the information that is supplied. The LoanAnalyzer CORBA interface has one method, which takes the following two in arguments: •...
  • Page 785 Displays the value of the ret variable, Yes or No. struct Person long pid; string name; string middle; string last_name; struct Account Person person; short age; double income; double loanAmountl enum cardType {AMEX, VISA, MC, DISCOVER, DINERS}; typedef sequence<cardType> CreditCards; interface LoanAnalyzer boolean approve( in Account, in CreditCards);...
  • Page 786 Chapter 34: Integrating COM and CORBA Objects in CFML Applications...
  • Page 787 PART VII Using External Resources This part describes how you can use ColdFusion to access and use the following external services: mail servers, remote HTTP and FTP servers, and files and directories. The following chapters are included: Chapter 35: Sending and Receiving E-Mail ..... . . 789 Chapter 36: Interacting with Remote Servers .
  • Page 789: Chapter 35: Sending And Receiving E-Mail

    CHAPTER 35 Sending and Receiving E-Mail You can add interactive e-mail features to your ColdFusion applications using the cfmail tags. This complete two-way interface to mail servers makes the ColdFusion e-mail cfpop capability a vital link to your users. Contents Using ColdFusion with mail servers .
  • Page 790: Using Coldfusion With Mail Servers

    Using ColdFusion with mail servers Adding e-mail to your ColdFusion applications lets you respond automatically to user requests. You can use e-mail in your ColdFusion applications in many different ways, including the following: • Trigger e-mail messages based on users’ requests or orders. •...
  • Page 791: Sending Smtp E-Mail With Cfmail

    Sending SMTP e-mail with cfmail tag provides support for sending SMTP e-mail from within ColdFusion applications. cfmail tag is similar to the tag, except that outputs the generated text as cfmail cfoutput cfmail SMTP mail messages rather than to a page. The tag supports all the attributes and cfmail commands that you use with...
  • Page 792: Sample Uses Of Cfmail

    Sample uses of cfmail An application page containing the tag dynamically generates e-mail messages based on cfmail the tag’s settings. Some of the tasks that you can accomplish with include the following: cfmail • Sending a mail message in which the data the user enters in an HTML form determine the recipient and contents •...
  • Page 793: Sending E-Mail To Multiple Recipients

    Reviewing the code The following table describes the code: Code Description Presents a dynamic list embedded within a normal <cfoutput> #ProductRequests.FirstName# message, repeating for each row in the cfmail #ProductRequests.LastName# ProductRequests query. The forces a &##013; (#ProductRequests.Company#) - carriage return between output records. #ProductRequests.EMailAddress#&##013;...
  • Page 794: Customizing E-Mail For Multiple Recipients

    Customizing e-mail for multiple recipients In the following example, a query (GetCustomers) retrieves the contact information for a list of customers. The query then sends an e-mail to each customer to verify that the contact information is still valid: <cfquery name="GetCustomers" datasource="myDSN"> SELECT * FROM Customers </cfquery>...
  • Page 795: Using Cfmailparam

    Reviewing the code The following table describes the code and its function: Code Description Retrieves all data from the Customers table into a query <cfquery name="GetCustomers" datasource="myDSN"> named GetCustomers. SELECT * FROM Customers </cfquery> <cfmail query="GetCustomers" Uses the attribute of , the cfmail from="service@MyCompany.com"...
  • Page 796: Adding A Custom Header To A Message

    Adding a custom header to a message When the recipient of an e-mail message replies to the message, the reply is sent to the address specified in the From field of the original message. You can use to override the value cfmailparam in the From field and provide a Reply-To e-mail address.
  • Page 797: Error Logging And Undelivered Messages

    Error logging and undelivered messages ColdFusion logs all errors that occur during SMTP message processing to the file mail.log the ColdFusion log directory. The log entries contain the date and time of the error as well as diagnostic information about why the error occurred. If a message is not delivered because of an error, ColdFusion writes it to this directory: •...
  • Page 798: The Cfpop Query Variables

    Decide whether you must delete messages from the POP server after you retrieve them. Incorporate the tag in your application and create a user interface for accessing a mailbox. cfpop Build an application page to handle the output. Retrieved messages can include ASCII characters that do not display properly in the browser.
  • Page 799 To retrieve only the message header: Create a ColdFusion page with the following content: <html> <head> <title>POP Mail Message Header Example</title> </head> <body> <h2>This example retrieves message header information:</h2> <cfpop server="mail.company.com" username=#myusername# password=#mypassword# action="GetHeaderOnly" name="Sample"> <cfoutput query="Sample"> MessageNumber: #HTMLEditFormat(Sample.messageNumber)# <br> To: #HTMLEditFormat(Sample.to)# <br>...
  • Page 800 Save the file as header_only.cfm in the myapps directory under your web_root and view it in your web browser: This code retrieves the message headers and stores them in a record set called Sample. cfpop For more information about working with record set data, see Chapter 22, “Using Query of Queries,”...
  • Page 801 Retrieving a message When you use the tag with , ColdFusion returns the same columns as cfpop action="GetAll" with , plus two additional columns, getheaderonly body header To retrieve an entire message: Create a ColdFusion page with the following content: <html>...
  • Page 802 Save the file as header_body.cfm in the myapps directory under your web_root and view it in your web browser: This example does not use a CFML function to encode the body contents. As a result, the browser displays the formatted message as you would normally see it in a mail program that supports HTML messages.
  • Page 803 To retrieve all parts of a message, including attachments: Create a ColdFusion page with the following content: <html> <head> <title>POP Mail Message Attachment Example</title> </head> <body> <h2>This example retrieves message header, body, and all attachments:</h2> <cfpop server="mail.company.com" username=#myusername# password=#mypassword# action="GetAll" attachmentpath="c:\temp\attachments"...
  • Page 804 Save the file as header_body_att.cfm in the myapps directory under your web_root and view it in your web browser: Note: To avoid duplicate filenames when saving attachments, set the generateUniqueFilenames attribute of to Yes. cfpop Deleting messages By default, retrieved messages remain on the POP mail server. If you want to delete retrieved messages, you must set the attribute of the tag to Delete.
  • Page 805 messagenumber="1,2,3"> </body> </html> Edit the following lines so that they refer to valid values for your POP mail server, username, and password: <cfpop server="mail.company.com" username=#username# password=#password# Save the file as message_delete.cfm in the myapps directory under your web_root and view the file in your web browser.
  • Page 806 Chapter 35: Sending and Receiving E-Mail...
  • Page 807: Chapter 36: Interacting With Remote Servers

    CHAPTER 36 Interacting with Remote Servers This chapter describes how ColdFusion wraps the complexity of Hypertext Transfer Protocol (HTTP) and File Transfer Protocol (FTP) communications in a simplified tag syntax that lets you extend your site’s offerings across the web. Contents About interacting with remote servers .
  • Page 808: About Interacting With Remote Servers

    Get operations. To retrieve a file and store it in a variable: Create a ColdFusion page with the following content: <html> <head> <title>Use Get Method</title> </head> <body> <cfhttp method="Get" url="http://www.macromedia.com" resolveurl="Yes"> <cfoutput> #cfhttp.FileContent# <br> </cfoutput> Chapter 36: Interacting with Remote Servers...
  • Page 809 The following table describes the code and its function: Code Description Get the page specified in the URL and make the links <cfhttp method="Get" url="http://www.macromedia.com" absolute instead of relative so that they appear resolveurl="Yes"> properly. <cfoutput> Display the page, which is stored in the variable #cfhttp.FileContent# <br>...
  • Page 810 Description Get the page specified in the URL and save it in the file <cfhttp method = "Get" specified by the attributes. path file url="http://www.macromedia.com/ When you use the attributes, path file software" ColdFusion ignores any attribute. As a resolveurl path="c:\temp"...
  • Page 811: Creating A Query Object From A Text File

    Creating a query object from a text file You can create a query object from a delimited text file by using the tag and specifying cfhttp and the attribute. This is a powerful method for processing and handling method="Get" name text files.
  • Page 812: Using The Cfhttp Post Method

    <body> <h1>HTTP Post Test</h1> <cfhttp method="Post" url="http://127.0.0.1:8500/myapps/post_test_server.cfm"> <cfhttpparam type="Cookie" value="cookiemonster" name="mycookie6"> <cfhttpparam type="CGI" value="cgivar " name="mycgi"> <cfhttpparam type="URL" value="theurl" name="myurl"> <cfhttpparam type="Formfield" value="twriter@macromedia.com" name="emailaddress"> <cfhttpparam type="File" name="myfile" file="c:\pix\trees.gif"> </cfhttp> <cfoutput> File Content:<br> #cfhttp.filecontent#<br> Mime Type: #cfhttp.MimeType#<br> </cfoutput> </body> </html> Chapter 36: Interacting with Remote Servers...
  • Page 813 Send a URL in the request. <cfhttpparam type="URL" value="theurl" name="myurl"> <cfhttpparam type="Formfield" Send a Form field in the request. value="twriter@macromedia.com" name="emailaddress"> Send a file in the request. <cfhttpparam type="File" name="myfile" The </cfhttp> tag ends the http request. file="c"\pix\trees.gif"> <cfoutput>...
  • Page 814 MIME type and length of the response. The search.exe program must expect a “search” parameter. <cfhttp method="Post" url="http://www.my_favorite_site.com/search.exe" resolveurl="Yes"> <cfhttpparam type="Formfield" name="search" value="Macromedia ColdFusion"> </cfhttp> <cfoutput> Response Mime Type: #cfhttp.MimeType#<br> Response Length: #len(cfhttp.filecontent)# <br> Response Content: <br> #htmlcodeformat(cfhttp.filecontent)#<br>...
  • Page 815: Performing File Operations With Cfftp

    Performing file operations with cfftp tag lets you perform tasks on remote servers using File Transfer Protocol (FTP). You cfftp can use to cache connections for batch file transfers when uploading or downloading files. cfftp Note: To use cfftp, the Enable cfftp Tag option must be selected on the Tag Restrictions page of the Basic Security section of the ColdFusion MX Administrator Security tab.
  • Page 816 <cfcol header="<B>Path</b>" TEXT="#path#"> <cfcol header="<B>URL</b>" TEXT="#url#"> <cfcol header="<B>Length</b>" TEXT="#length#"> <cfcol header="<B>LastModified</b>" TEXT="#DateFormat(lastmodified)#"> <cfcol header="<B>IsDirectory</b>" TEXT="#isdirectory#"> </cftable> Change to the name of a server for which you have FTP permission. MyServer Change to a valid username and password. MyUserName MyPassword To establish an anonymous connection, enter “anonymous” as the username and an e-mail address (by convention) for the password.
  • Page 817: Caching Connections Across Multiple Pages

    Code Description <cftable query="dirlist" Display a table with the results of the ListDir FTP colheaders="yes" htmltable> command. <cfcol header="<B>Name</b>" TEXT="#name#"> <cfcol header="<B>Path</b>" TEXT="#path#"> <cfcol header="<B>URL</b>" TEXT="#url#"> <cfcol header="<B>Length</b>" TEXT="#length#"> <cfcol header="<B>LastModified</b>" TEXT="#DateFormat(lastmodified)#"> <cfcol header="<B>IsDirectory</b>" TEXT="#isdirectory#"> </cftable> After you establish a connection with , you can reuse the connection to perform additional cfftp FTP operations until either you or the server closes the connection.
  • Page 818: Connection Actions And Attributes

    Connection actions and attributes The following table shows the available actions and the attributes they require when you cfftp use a named (that is, cached) connection. If you do not specify an existing connection name, you must specify the , and attributes username password...
  • Page 819: Chapter 37: Managing Files On The Server

    CHAPTER 37 Managing Files on the Server , and tags handle browser and server file management cffile cfdirectory cfcontent tasks, such as uploading files from a client to the web server, viewing directory information, and changing the content type that is sent to the web browser. To perform server-to-server operations, use the tag, described in “Performing file operations with cfftp”...
  • Page 820: About File Management

    About file management ColdFusion lets you access and manage the files and directories on your ColdFusion server. The tag has several attributes for moving, copying, deleting, and renaming files. You use the cffile tag to list, create, delete, and rename directories. The tag lets you define cfdirectory cfcontent...
  • Page 821 Note: The form will not work until you write an action page for it (see the next procedure). Reviewing the code The following table describes the code and its function: Code Description Create a form that contains file selection fields for <form action="uploadfileaction.cfm"...
  • Page 822 Reviewing the code The following table describes the code and its function: Code Description Output the name and location of the uploaded file on <cffile action="upload" the client machine. destination="c:\temp\" Specify the destination of the file. If the file already exists, overwrite it. nameConflict="overwrite"...
  • Page 823 Note: Modern versions of Internet Explorer and Netscape support MIME type associations. Other browsers and older versions might ignore these associations. ColdFusion saves any uploaded file if you omit the attribute or specify "*/*". You can accept restrict the file types, as demonstrated in the following examples. The following tag saves an image file only if it is in the GIF format: cffile...
  • Page 824 • 1 = execute You enter permissions values in the attribute for each type of user: owner, group, and other mode in that order. For example, use the following code to assign read permissions for everyone: mode=444 To give a file or directory owner read/write/execute permissions and read only permissions for everyone else: mode=744 Evaluating the results of a file upload...
  • Page 825: Moving, Renaming, Copying, And Deleting Server Files

    Variable Description fileWasSaved Indicates (Yes or No) whether ColdFusion saved the uploaded file. oldFileSize Size of the file that was overwritten in the file upload operation. Empty if no file was overwritten. serverDirectory Directory where the file was saved on the server. serverFile Full name of the file saved on the server with the file extension;...
  • Page 826: Reading, Writing, And Appending To A Text File

    Reading, writing, and appending to a text file In addition to managing files on the server, you can use to read, create, and modify text cffile files. As a result, you can do the following things: • Create log files. (You can also use to create and write to log files.) cflog •...
  • Page 827 <form action="writetextfileaction.cfm" method="Post"> <p>Enter your name: <input type="text" name="Name" size="25"></p> <p>Enter the name of the file: <input type="text" name="FileName" size="25">.txt</p> <p>Enter your message: <textarea name="message"cols=45 rows=6></textarea> </p> <input type="submit" name="submit" value="Submit"> </form> </body> </html> Save the file as writetextfileform.cfm in the myapps directory under your web_root Note: The form will not work until you write an action page for it (see the next procedure).
  • Page 828: Using Cfdirectory

    View the file in the browser, enter values, and submit the form. The appended information displays at the end of the text file. Using cfdirectory Use the tag to return file information from a specified directory and to create, cfdirectory delete, and rename directories.
  • Page 829 <th>Type</th> <th>Modified</th> <th>Attributes</th> <th>Mode</th> </tr> <cfoutput query="mydirectory"> <tr> <td>#mydirectory.name#</td> <td>#mydirectory.size#</td> <td>#mydirectory.type#</td> <td>#mydirectory.dateLastModified#</td> <td>#mydirectory.attributes#</td> <td>#mydirectory.mode#</td> </tr> </cfoutput> </table> </body> </html> Modify the path C:\inetpub\wwwroot\mine so that it points to a directory on your server. Save the file as directoryinfo.cfm in the myapps directory under your web_root and view it in the browser: Using cfdirectory...
  • Page 830: Using Cfcontent

    Using cfcontent tag downloads files from the server to the client. You can use this tag to set the cfcontent MIME type of the content returned by a ColdFusion page and, optionally, define the filename of a file to be downloaded by the current page. By default, ColdFusion returns a MIME content type of text/html so that a web browser renders your template text as a web page.
  • Page 831 <cfcontent type = "text/html" file = "C:\CFusionMX\wwwroot\myapps\cfcontent_message.htm" deleteFile = "No"> </body> </html> If necessary, edit the line to point to your myapps directory. file = Save the file as cfcontent.cfm in the myapps directory under your web_root and view it in the browser.
  • Page 832 To create an Excel spreadsheet with cfcontent: Create a ColdFusion page with the following content: <!--- use cfsetting to block output of HTML outside of cfoutput tags ---> <cfsetting enablecfoutputonly="Yes"> <!--- get employee info ---> <cfquery name="GetEmps" datasource="CompanyInfo"> SELECT * FROM Employees </cfquery>...
  • Page 833: Index

    INDEX Application.cfm file application-level settings 272 access security, component 248 creating 272 accessing example 275 client variables 324, 330 processing 271 generated content 185 user-defined functions in 206 action pages 564 applications ActionScript, on ColdFusion server 32 Application.cfm 271 Active Server Pages 697 authentication 351 adding caching 277...
  • Page 834 applicationToken 353 Attributes scope 44, 73 area chart, example 634 authentication arguments application-based example 361 optional 199, 202 cookies and 351 passing 202 defined 348 user-defined function 202 digest 350 using function names 208 HTTP, basic 350 arguments. See parameters logout 354 Arguments scope Microsoft NTLM 350...
  • Page 835 requesting component pages with 233 cfassociate tag 188 transferring data to a server 703 cfbreak tag 48 building cfcache tag 277 components 235 cfcache tag, location of tag 278 drop-down list boxes 593 cfcase tag 48 queries 430 cfcatch tag 299, 300 search interfaces 569 cfchart tag slider bar controls 595...
  • Page 836 using 815 cfldap tag cffunction tag about 482 attributes 200 indexing queries 526 creating user-defined functions 193 output 498 security and 352 queries and 452, 498 web services, publishing 721 Verity and 498 cfgrid tag cflocation tag 325 browser considerations 585 cflock tag controlling cell contents 599 controlling time-outs 337...
  • Page 837 functions 31, 42 StructDelete 121 reserved words 51 StructIsEmpty 118 special characters 50 StructKeyExists 118 syntax errors 406 StructKeyList 118 tags 30, 40 StructNew 116 variables 44 syntax 88 CFML functions URLEncodedFormat 407 ArrayAppend 108 XmlChildPos 676 ArrayDeleteAt 109 XmlElemNew 676 ArrayInsertAt 108 XmlNew 676 ArrayNew 106...
  • Page 838 CFScript CFToken comments 130 Cookie 319 conditional processing 132 server-side variable 321 creating user-defined functions 193 cftrace tag description 31 attributes 404 differences from JavaScript 131 using 401 example 128, 140 cftree tag exception handling 139 browser considerations 585 expressions 129 description 584 function statement 198 form variables 589...
  • Page 839 character encodings class loading about 374 Java 256 conversion issues 375 mechanism 737 defined 373 class reloading, automatic 257 determining page 378 classes, debugging 260 files 385 classpath forms and 383, 384 configuring 253 processing data from various sources 385, 386 Java objects and 737 searching and indexing 387 client cookies 319...
  • Page 840 ColdFusion MX viewing objects 766 about 30 WDDX and 697 action pages, extension for 564 COM objects application services 32 Application scope, using 774 CFML 30 calling 764 CORBA type support 780 connecting to 768 dynamic evaluation 94 creating 767 error handling 290 displaying with cfdump 765 error types 287...
  • Page 841 introspecting 233 exception handling 783 invocation techniques 225 getting started 777 invoking directly 229 interface 763 invoking from Flash 232 interface methods 778 invoking methods dynamically 229 naming services 778 invoking methods transiently 226 parameter passing 779 invoking with forms 231 CreateObject CFML function invoking with URLs 230 about 716...
  • Page 842 children 186 in CFML 45 data access example 189 object 46, 55 data accessibility 187 simple 45, 55 data exchange 188 validating 80, 81 descendants 186 variables 55 downloading 177 See also complex data types encoding 181 data, charting data from query 621 encrypting 181 data-type conversions example 179...
  • Page 843 record delete 448 debugging output record sets 418 cfquery tag 400 records 412 cfsetting tag 400 retrieving data from 428 classic 390 rollbacks 414 database activity 396 rows 412 dockable 390, 399 SQL 415 exceptions 397 stored procedures 281 execution time 394 stored procedures, debugging 397 format 390 tables 412...
  • Page 844 directory structure, application 270, 271 character encodings 386 displaying checking for spooled 796 COM objects with cfdump 765 customizing 794 query results 431 deleting 804 query results, in tables 567 error logging 797 displaying, component output 239 for multiple recipients 794 distinguished name 480 form-based 792 Distributed Component Object Model.
  • Page 845 errors in CFScript 139 categories 287 in ColdFusion MX 299 causes 286 Java and 753 creating application pages 295 nesting cftry tags 309 custom pages 294 rules 300 input validation 297 tags 299 logging 297 exception types recovery 286 advanced 288 web services and 717 basic 288, 289 EUC-KR 374...
  • Page 846 file operations form controls cfftp actions 818 cfform 584 using cffile 820 description 561 using cfftp 815 form fields file scope 182 required 579 file types, supported for searching 507 validation errors 290 files Form scope 44, 72 appending 827 form tag, syntax 560 character encodings 385 form variables...
  • Page 847 function-only variables 203 functions handling built in 42 applet form variables 609 calling 200 exceptions 299 example custom 204 failed validation 614 for arrays 113 POP Mail 798 for components 222 hidden fields 579 GetMetaData 235 horizontal bar charts 631 introduction 42 HTML JavaScript, for validation 613...
  • Page 848 inserting data Java description 438 alternate constructor 750 with cfinsert 440 class loading mechanism 737 with cfquery 441 class reloading 257 instance data, custom tag 182 ColdFusion data and 751 instance data, of components 236 considerations 750 instance, invoking methods of a component 226 custom class 756 instantiating, components 225 customizing and configuring 253...
  • Page 849 JavaCast CFML function 752 querying directories 483 JavaScript referrals 502 differences from CFScript 131 schema 481 in charts 639 schema attribute type 482 validating with 613 scope 483 joins, queries of queries 462 search filters 483 JSP pages security 366 accessing 740 symmetrical directory structure 478 calling from ColdFusion 744...
  • Page 850 596 looping through structures 121 nested objects, calling 764 nested pound signs in expressions 91 nesting Macromedia Dreamweaver MX. See Dreamweaver MX cflock tags 338 Macromedia Flash Remoting. See Flash Remoting cfloops for arrays 111 Macromedia HomeSite+, SQL editor 424...
  • Page 851 OnRequestEnd.cfm 271 passing using cfinvoke 228 opening, SQL Builder 424 parent tags 186 operands 43 passing operators 43 arguments 202 alternative notation 86 arrays to user-defined functions 210 arithmetic 84 custom tag attributes 177, 178 Boolean 85 custom tag data 187 comparison 85 queries to user-defined functions 208 concept 544...
  • Page 852 proximity operators 549 Query CFX object 256 punctuation, searching 541 query columns 64 Python, WDDX and 697 query functions 452 Query object 256 query objects 62, 452 query properties, guidelines for 434 queries query results about 621 about 433 as function parameters 208 cfpop 531 as objects 452 columns in 433...
  • Page 853 registering resource security CFX tags 263 about 346 COM objects 765 resources 347 CORBA objects 778 resources, regular expressions 613 Java applets 606 Response object 255, 256 regular expressions results backreferences 152, 612 providing from components 239 basic syntax 145 returning from components 239 case sensitivity 147 returning incrementally 572...
  • Page 854 saving searching binary files 810 case sensitivity 542 components 241 cfsearch tag 523 web pages 809 character encodings 387 SBCS 374 collections 506 schema, LDAP directory 498 collections, creating 511 scopes creating index summaries 525 about 72 database records 526 Application 74, 270, 316, 330 external Verity collections 513 Arguments 74...
  • Page 855 tags 352 setting up types of 346 C++ development environment 261 user security 348 Java development environment 253 web servers and 350, 726 settings, application-level 269 web services 726, 727 SetVariable CFML functions 97 without cookies 352 Shift-JIS 374 See also login SHLIB_PATH See also sandbox security about 262...
  • Page 856 sorting 419 in dynamic expressions 94 statement clauses 416 listing keys in 118 statements 416 looping through 121 SUM function 634 notation for 114 syntax 416 passing tag arguments 180 text literals in 429 referencing 63 UPDATE statement 421, 442 scopes and 63, 77 use in cfquery 429 sorting keys 118...
  • Page 857 time zone processing, WDDX 701 user edits, returning 600 time, globalization functions 381 user ID, getting 353, 356 time-out attribute, cflock 337 user roles 348 ToString CFML function 677 user security. See security tracing 401 user-defined functions cftrace tag 401 argument naming 197 considerations for 403 arguments 202, 208...
  • Page 858 variable scopes locking example 340 about 44 naming 178 Application 45 naming rules 54 Arguments 45 numeric 56 Attributes 44 objects 55 Caller 44 passing 663, 808 CGI 45 persistent 316 Client 45 processing 560 Cookie 45 queries 62 Flash 45 real numbers 57 Form 44 Request scope 187...
  • Page 859 purpose of 697 web services, consuming storing data in strings 706 about 708 time zone processing 701 cfinvoke tag 713, 714 transferring data 703 CFScript for 716 ColdFusion MX 719 accessing with cfhttp 697, 808 ColdFusion MX Administrator 718 application framework 318 complex data types 728 web application servers CreateObject function 716...
  • Page 860 WSDL files XML elements components 712 adding 686 creating 710 attributes 689 defined child elements 685 described 710 children of 683 reading 711 copying 687 viewing in Dreamweaver MX 711 counting 685 web services, publishing 722 deleting 688 finding 685 properties, modifying 689 replacing 689 XmlAttributes 674...

This manual is also suitable for:

Coldfusion mx

Table of Contents