MACROMEDIA COLDFUSION 4.5-DEVELOPING WEB Develop Manual
MACROMEDIA COLDFUSION 4.5-DEVELOPING WEB Develop Manual

MACROMEDIA COLDFUSION 4.5-DEVELOPING WEB Develop Manual

Developing web applications with coldfusion
Table of Contents

Advertisement

Quick Links

Developing Web
Applications with
ColdFusion
ColdFusion 4.5
Allaire Corporation

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the COLDFUSION 4.5-DEVELOPING WEB and is the answer not in the manual?

Questions and answers

Summary of Contents for MACROMEDIA COLDFUSION 4.5-DEVELOPING WEB

  • Page 1 Developing Web Applications with ColdFusion ColdFusion 4.5 Allaire Corporation...
  • Page 2 Copyright Notice © 1999 Allaire Corporation. All rights reserved. This manual, as well as the software described in it, is furnished under license and may be used or copied only in accordance with the terms of such license. The content of this manual is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Allaire Corporation.
  • Page 3: Table Of Contents

    Contents Preface: Welcome to ColdFusion ..............xv Intended Audience.........................xvi Welcome to the ColdFusion 4.5 Web Application Server ............xvi Products and System Requirements ...................xvii New features in ColdFusion 4.5 ....................xviii New visual tools ........................xviii Enhancements to CFML ......................xix Better reliability ........................xix Improved performance......................xix Enterprise connectivity features ....................xx Security enhancements......................xx...
  • Page 4 Developing Web Applications with ColdFusion ColdFusion Server ........................6 ColdFusion Administrator......................6 Data sources ..........................7 How ColdFusion Server Works ......................7 Chapter 2: Writing Your First ColdFusion Application........9 The Development Process ......................10 Writing Code ...........................10 Saving Application Pages .......................11 Viewing Application Pages ......................11 Variables ............................13 Adding More Variables to the Application..................14 Development Considerations......................14...
  • Page 5 Contents Creating Table Joins........................40 Building Flexible Search Interfaces ....................40 Code Review ..........................41 Returning Query Results to the User.....................42 Chapter 5: Making Variables Dynamic ............45 Dynamically Populating Select Boxes ...................46 Creating Dynamic Checkboxes and Multiple Select Boxes............47 Checkboxes ..........................47 Multiple select lists........................49 Testing for a variable’s existence ....................51 Creating Default Variables with CFPARAM ..................51 Checking Query Parameters with CFQUERYPARAM ..............52...
  • Page 6 Developing Web Applications with ColdFusion Access to generated content....................84 Installing Custom Tags ........................85 Local tags..........................85 Shared tags..........................85 Managing Custom Tags........................85 Resolving file name conflicts....................85 Securing Custom Tags ......................86 Encoding Custom Tags ......................86 Chapter 8: Debugging and Error Handling ..........89 Debug Settings in the ColdFusion Administrator ................90 Generating debug information for an individual page ............90 Generating debug information for an individual query............90 Error messages.........................90...
  • Page 7 Contents Array Functions..........................111 About Structures ...........................113 Structure notation .........................113 Creating and Using Structures.....................114 Creating structures........................114 Adding data to structures .....................114 Finding information in structures ..................115 Getting information about structures .................115 Copying structures ........................116 Deleting structures........................116 Structure Example ........................117 Using Structures as Associative Arrays ..................119 Looping through structures....................119 Structure Functions ........................120 Chapter 10: Building Dynamic Forms............123...
  • Page 8 viii Developing Web Applications with ColdFusion Chapter 11: Indexing and Searching Data ..........149 Searching a ColdFusion Web Site....................150 Advantages of using Verity ....................150 Online Verity training ......................151 Supported File Types........................151 Support for International Languages ..................152 Steps in Creating a Searchable Data Source ................153 Creating a Collection ........................153 Using the ColdFusion Administrator to create a collection ..........154 Creating a collection with the CFCOLLECTION tag............154...
  • Page 9 Contents Choosing a client variable storage method.................189 Managing Client State in a Clustered Environment ..............190 Using Client State Management....................190 Creating a client variable ......................191 Using Client Variables ........................191 Standard client variables ......................191 Using client state management without cookies..............191 Getting a list of client variables ....................192 Deleting client variables .......................192 Exporting the client variable database ................193 Application and Session Variables ....................193...
  • Page 10 Developing Web Applications with ColdFusion Chapter 14: Managing Files on the Server ..........219 Using CFFILE ..........................220 Uploading Files ..........................220 Resolving conflicting file names ..................222 Controlling the type of file uploaded...................222 Setting File and Directory Attributes...................223 UNIX............................223 Windows..........................224 Evaluating the Results of a File Upload..................224 Moving, Renaming, Copying, and Deleting Server Files ............226 Reading, Writing, and Appending to a Text File.................227 Reading a text file ........................227...
  • Page 11 Contents Chapter 17: Application Security ..............263 ColdFusion Security Features......................264 Remote Development Services (RDS) Security ................264 Overview of User Security ......................265 Using Advanced Security in Application Pages................265 Using the CFAUTHENTICATE tag....................266 Authentication and Authorization Functions ................267 Using the IsAuthenticated Function..................267 Using the IsAuthorized Function..................267 Catching Security Exceptions ......................268 Using the CFIMPERSONATE Tag ....................269 Example of User Authentication and Authorization..............270...
  • Page 12 Developing Web Applications with ColdFusion CCFXQuery Class ..........................295 Class members........................295 CCFXQuery::AddRow......................296 CCFXQuery::GetColumns.....................296 CCFXQuery::GetData ......................297 CCFXQuery::GetName ......................297 CCFXQuery::GetRowCount ....................297 CCFXQuery::SetData......................298 CCFXQuery::SetQueryString ....................299 CCFXQuery::SetTotalTime ....................299 CCFXRequest Class........................299 Class Members ........................299 CCFXRequest::AddQuery......................300 CCFXRequest::AttributeExists....................301 CCFXRequest::CreateStringSet ....................301 CCFXRequest::Debug......................302 CCFXRequest::GetAttribute....................302 CCFXRequest::GetAttributeList ...................302 CCFXRequest::GetCustomData ...................303 CCFXRequest::GetQuery.......................303 CCFXRequest::GetSetting .....................304 CCFXRequest::ReThrowException ..................304 CCFXRequest::SetCustomData ....................305 CCFXRequest::SetVariable....................306...
  • Page 13 Contents xiii Invoking Component Objects......................327 Coding guidelines........................327 Calling methods ........................327 Calling nested objects ......................328 Getting Started with COM/DCOM ....................328 Requirements for COM......................328 Registering the object ......................328 Finding the component ProgID and methods..............329 Creating and Using COM Objects ....................331 Connecting to COM objects ....................331 Setting properties and invoking methods ................332 Getting Started with CORBA ......................332 Calling a CORBA Object .......................333...
  • Page 14 Developing Web Applications with ColdFusion...
  • Page 15 Welcome to ColdFusion Preface This manual describes the process of developing Web applications using ColdFusion. In the first six chapters, you can follow the instructions presented to learn how to create basic ColdFusion applications. Then, chapters seven through 17 cover various topics of interest in enhancing your applications. Finally, chapters 18 through 21 explain how to extend ColdFusion’s capabilities.
  • Page 16: Intended Audience

    Developing Web Applications with ColdFusion Intended Audience This manual is particularly useful for Web application developers who are new to ColdFusion. In particular, Chapters 1 through 6 provide instructions for creating a basic ColdFusion application. If you are somewhat familiar with ColdFusion, but want to learn more about a particular topic such as sending and receiving email, refer to Chapters 7 through 17.
  • Page 17: Products And System Requirements

    Preface xvii Products and System Requirements ColdFusion has been fully tested on the following platforms and with the following configurations. ColdFusion Server 4.5 Enterprise Edition for Windows Windows NT 4.0 SP4+ Intel Pentium or above 150 MB hard disk space 128 MB RAM (256 MB recommended for clustering) ColdFusion Server 4.5 Enterprise Edition for Solaris SPARC Solaris 2.5.1, 2.6, or 7 (patch 103582-1B or higher)
  • Page 18: New Features In Coldfusion 4.5

    xviii Developing Web Applications with ColdFusion ColdFusion Studio 4.5 Windows 95/98/NT4 Intel Pentium or above 35 MB hard disk space 32 MB RAM (64 MB recommended) New Features in ColdFusion 4.5 A wide range of new features are available in ColdFusion 4.5. New visual tools Universal File Browser —...
  • Page 19: Enhancements To Cfml

    Preface Enhancements to CFML Object Scripting — Instantiate and script objects using CFML script in addition to the CFOBJECT tag easier integration with distributed object middleware such as COM and CORBA. Structured Exception Handling — Exception handling now offers hierarchical exception handling that supports both greater customization and greater access to internal exceptions.
  • Page 20: Enterprise Connectivity Features

    Developing Web Applications with ColdFusion Scriptable Performance Metrics — Track key server metrics at run time through your own scripts for intelligent diagnosis of performance bottlenecks of stability problems in your applications. Performance Debugging Data — Access detailed debugging information on the performance of each individual page included in an application page that is being debugged.
  • Page 21: Developer Resources

    Preface OS Server Sandbox Security — Secure shared hosting environments more easily by creating Server Sandboxes with Windows NT security. OS Server Sandboxes process all requests under the privileges of a designated Windows NT user account (Enterprise Edition for Windows only). Enhanced Advanced Security —...
  • Page 22: About Coldfusion Documentation

    xxii Developing Web Applications with ColdFusion About ColdFusion Documentation ColdFusion documentation is designed to provide support for all components of the ColdFusion development system. Both the print and online versions are organized to allow you to quickly locate the information you need. In addition to the book set, the documentation is provided in two other formats: HTML —...
  • Page 23: Coldfusion Server Online Documentation

    Preface xxiii Using ColdFusion Studio Documents everything you need to know about using ColdFusion Studio, including features like projects, source control integration, as well as the Studio workspace and interface. ColdFusion Quick Reference Guide A valuable quick reference to CFML tags, functions, and variables. ColdFusion Server online documentation To view the HTML documentation, open the following URL: http://127.0.0.1/...
  • Page 24: Documentation Conventions

    xxiv Developing Web Applications with ColdFusion Documentation conventions When reading, please be aware of these formatting cues: Code samples, filenames, and URLs are set in a font monospaced Notes and tips are identified by bold type Bulleted lists present options and features Numbered steps indicate procedures Tool button icons are generally shown with procedure steps Menu levels are separated by the greater than (>) sign...
  • Page 25 Preface Technical support Telephone support is available Monday through Friday 8 A.M. to 8 P.M. Eastern time (except holidays) Toll Free: 888.939.2545 (U.S. and Canada) Tel: 617.761.2100 (outside U.S. and Canada) For complete details about Allaire Product Support options, please refer to the Allaire Support pages on the Allaire web site: http://www.allaire.com/support Postings to the ColdFusion Support Forum (...
  • Page 26 xxvi Developing Web Applications with ColdFusion...
  • Page 27: Chapter 1: Introduction To Coldfusion

    H A P T E R Introduction to ColdFusion Chapter 1 This chapter explains the difference between creating static Web pages with HTML and creating dynamic applications with ColdFusion. It also describes what ColdFusion is and how it works. Contents A Quick Web Overview..................
  • Page 28: A Quick Web Overview

    Developing Web Applications with ColdFusion A Quick Web Overview Over the last few years, the Web has changed from being simply a collection of static HTML pages to an application development platform. Rather than offering a space where organizations can merely advertise goods and services, similar to traditional yellow pages directories, companies conduct business ranging from ecommerce to managing internal business processes.
  • Page 29: What Is Coldfusion

    Chapter 1: Introduction to ColdFusion What is ColdFusion? ColdFusion lets you create page-based Web applications using ColdFusion Markup Language (CFML), the tag-based language you use to create server-side scripts that dynamically control data integration, application logic, and user interface generation. ColdFusion Web applications can contain XML, HTML, and other client technologies such as CSS and JavaScript.
  • Page 30: Rapid Development

    Developing Web Applications with ColdFusion Rapid development The ColdFusion development platform enhances the speed and ease of development through the following features: A tag-based server scripting language that is powerful and intuitive. Two-way visual programming and database tools. Remote interactive debugging for quickly identifying and fixing problems. Web application wizards to automate common development tasks.
  • Page 31: Complete Security

    Chapter 1: Introduction to ColdFusion Complete security ColdFusion provides a foundation for building secure applications through the following features: Integration with existing authentication systems including Windows NT domain and LDAP directory servers, and proprietary user and group databases. Advanced access control so that server administrators can control developers’ access to files and data sources.
  • Page 32: Coldfusion Studio

    Developing Web Applications with ColdFusion ColdFusion Studio ColdFusion Studio is the development environment for ColdFusion Server. It offers visual development tools, including dynamic page previews using your Web browser, an interactive debugger, a query builder, an expression builder, project management and source control tools, and many other productivity enhancements.
  • Page 33: Data Sources

    Chapter 1: Introduction to ColdFusion Data sources ColdFusion applications may interact with any database that supports the ODBC standard. However, ColdFusion is not limited to ODBC data sources. You can also retrieve data using OLE-DB, native database drivers, or directory servers that support the Lightweight Directory Access Protocol (LDAP).
  • Page 34 Developing Web Applications with ColdFusion...
  • Page 35: Chapter 2: Writing Your First Coldfusion Application

    H A P T E R Writing Your First ColdFusion Chapter 2 Application This chapter guides you through the ColdFusion development process as you create a ColdFusion application page, save it, and view it in a browser. Contents The Development Process................10 Writing Code.....................
  • Page 36: The Development Process

    Developing Web Applications with ColdFusion The Development Process Whether you are creating a static HTML page or a ColdFusion application page, you follow the same iterative process: Write some code. Save the code to a document or page. View the page in a browser. Modify the page.
  • Page 37: Saving Application Pages

    Chapter 2: Writing Your First ColdFusion Application Saving Application Pages Instead of saving pages with an HTM or HTML file extension, you save ColdFusion application pages with a CFM or CFML extension. By default, the Web server knows to pass a page that contains a CFM extension to the ColdFusion Server when it is requested by a browser.
  • Page 38 Developing Web Applications with ColdFusion Compare the code that was returned to the browser with what you originally created. Notice that the ColdFusion comments and CFML tags are processed, but do not appear in the HTML file that’s returned to the browser. Original ColdFusion page HTML file returned by Web server <HTML>...
  • Page 39: Variables

    Chapter 2: Writing Your First ColdFusion Application Variables A Web application page is different from a static Web page because it can publish data dynamically. This involves creating, manipulating, and outputting variables. A variable stores data that can be used in applications. As with other programming languages, you’ll set variables in ColdFusion to store data that you want to access later.
  • Page 40: Adding More Variables To The Application

    Developing Web Applications with ColdFusion Adding More Variables to the Application Applications can use many different variables. For example, the calldept.cfm application page can set and display values for department, city, and salary. To modify the application: Return to the file in ColdFusion Studio, calldept.cfm Modify the code so that it appears as follows:...
  • Page 41: Chapter 3: Querying A Database

    H A P T E R Querying a Database Chapter 3 This chapter describes how to retrieve data from a database, work with query data, and enable debugging in ColdFusion applications. You will learn how to use the ColdFusion Administrator to set up a data source and enable debugging, use the CFQUERY tag to query a data source, and use the CFOUTPUT tag to output the query results to a Web page.
  • Page 42: Publishing Dynamic Data

    Developing Web Applications with ColdFusion Publishing 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 —...
  • Page 43 Chapter 3: Querying a Database Data can be organized in multiple tables. This type of data structure is known as a relational database and is the type used for all but the simplest data sets. From this basic description, a few database design rules emerge: Each record should contain a unique identifier, known as the primary key.
  • Page 44: Understanding Data Sources

    Developing Web Applications with ColdFusion Understanding Data Sources A database is a file or server that contains a collection of data. A data source is a pointer from ColdFusion to a specific database. You add data sources to your ColdFusion Server so that you can point to the databases that you want to connect to from your ColdFusion applications.
  • Page 45: Adding Data Sources

    Chapter 3: Querying a Database Adding Data Sources You add data sources in the ColdFusion Administrator to define connection requirements for database access. When you add a data source, you assign it a name so that you can reference it within tags such as CFQUERY on application pages to query databases.
  • Page 46: Data Source Notes And Considerations

    Developing Web Applications with ColdFusion The data source is added to the data source list. Locate in the data source list. CompanyInfo 10. Choose Verify to run the verification test on the data source. If the data source was created, you should see this message: The connection to the data source was verified successfully.
  • Page 47: Writing Sql

    Chapter 3: Querying a Database Performs SQL commands that are enclosed within the block. Returns query variable values to the page. CFQUERY tag syntax <CFQUERY NAME="EmpList" DATASOURCE="CompanyInfo"> You’ll type SQL here </CFQUERY> In this example, the query code tells ColdFusion to: Use the data source to connect to the database.
  • Page 48: Basic Sql Syntax Elements

    Developing Web Applications with ColdFusion When the database processes the SQL, it creates a data set that is returned to ColdFusion Server. ColdFusion places the data set in memory and assigns it the name that you defined for the query in the begin CFQUERY tag. You may reference that data set by name using the CFOUTPUT tag further down on the page.
  • Page 49: Sql Notes And Considerations

    Chapter 3: Querying a Database Operators These specify conditions and perform logical and numeric functions: Basic SQL Operators Operator Description Both conditions must be met, such as Paris AND Texas At least one condition must be met, such as Smith OR Smyth Exclude the condition following, such as Paris NOT France Equal to <>...
  • Page 50: Building Queries

    Developing Web Applications with ColdFusion Building Queries As discussed earlier in this chapter, you build queries using the CFQUERY tag and SQL. To query the table: Create a new application page. Edit the page so that it appears as follows: <HTML>...
  • Page 51: Query Notes And Considerations

    Chapter 3: Querying a Database Query Notes and Considerations When creating queries to retrieve data, keep these guidelines in mind: Enter the query NAME and DATASOURCE attributes in the begin CFQUERY tag. Surround attribute settings with double quotes("). Reference the query data by naming the query in the CFOUTPUT tag later on the page.
  • Page 52: Query Output Notes And Considerations

    Developing Web Applications with ColdFusion #FirstName#, #LastName#, #Salary#, #Contract#<BR> </CFOUTPUT> </BODY> </HTML> Save the file as emplist.cfm View the page in a browser. A list of employees appears in the browser, with each line displaying one row of data. You have created a ColdFusion application page that retrieves and displays data from a database.
  • Page 53: Getting Information About Query Results

    Chapter 3: Querying a Database When outputting the data itself, you define the variable name using the QUERY attribute. When outputting query properties variables, don’t use the QUERY attribute; instead, prefix the variable reference with the name of the query, for example, EmpList.RecordCount Columns must exist and be retrieved to the application in order to output their values.
  • Page 54: Query Properties Notes And Considerations

    Developing Web Applications with ColdFusion <CFOUTPUT> The query returned #EmpList.RecordCount# records. </CFOUTPUT> </BODY> </HTML> Save the file as emplist.cfm View the page in a browser. The number of employees now appears below the list of employees. Code Review You now display the number of records retrieved in the query. Code Description <CFOUTPUT>...
  • Page 55: Chapter 4: Retrieving And Formatting The Data You Want

    H A P T E R Retrieving and Formatting the Chapter 4 Data You Want This chapter explains how to select the data to display in 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 56: Using Forms To Specify The Data To Retrieve

    Developing Web Applications with ColdFusion Using Forms to Specify the Data to Retrieve Until now, you’ve retrieved all of the records from a table. However, there are many instances when you’ll want to retrieve data based on certain criteria. For example, you may want to see records for everyone in a particular department, everyone in a particular town whose last name is Smith, or books by a certain author.
  • Page 57 Chapter 4: Retrieving and Formatting the Data You Want HTML Form Controls Control Code <INPUT TYPE="Text" NAME="ControlName" SIZE="Value" MAXLENGTH="Value"> Text control <INPUT TYPE="Radio" NAME="ControlName" VALUE="Value1">DisplayName1 Radio <INPUT TYPE="Radio" NAME="ControlName" VALUE="Value2">DisplayName2 buttons <INPUT TYPE="Radio" NAME="ControlName" VALUE="Value3">DisplayName3 <SELECT NAME="ControlName"> Select box <OPTION VALUE="Value1">DisplayName1 <OPTION VALUE="Value2">DisplayName2 <OPTION VALUE="Value3">DisplayName3 </SELECT>...
  • Page 58 Developing Web Applications with ColdFusion <HTML> <HEAD> <TITLE>Input form</TITLE> </HEAD> <BODY> <!--- 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>...
  • Page 59 Chapter 4: Retrieving and Formatting the Data You Want View the form in a browser. The form appears in the browser. Remember that you need an action page in order to submit values; you will create one later in this chapter. Code Review A form appears on the page, ready for user input.
  • Page 60: Form Notes And Considerations

    Developing Web Applications with ColdFusion Form Notes and Considerations To make the coding process easy to follow, name form controls the same as target database fields. Limit radio buttons to three-to-five mutually exclusive options. If you need more than that many options, consider a dropdown select box. Use select boxes to allow the user to choose multiple items.
  • Page 61: Creating Action Pages

    Chapter 4: Retrieving and Formatting the Data You Want But when you want to return information about employees that match user search criteria, you use the SQL WHERE clause with a SQL SELECT statement to compare a value against a character string field. When the WHERE clause is processed, it filters the query data based on the results of the comparison.
  • Page 62: Form Variable Notes And Considerations

    Developing Web Applications with ColdFusion Enter data for the LastName form control and submit it. Return to the form in your browser. Reset the values. Do not check the checkbox and submit the form again. An error occurs when the checkbox does not pass to the action page. You will receive errors if you submit the form without checking the checkbox form controls.
  • Page 63: Using Html Tables To Layout Query Results

    Chapter 4: Retrieving and Formatting the Data You Want Form variables for checkboxes and radio buttons generate errors on action pages if nothing is selected for the form controls. Using HTML Tables to Layout Query Results You have displayed each row of data from the Employees table, but the information was unformatted.
  • Page 64: Formatting Individual Data Items

    Developing Web Applications with ColdFusion View in your browser. formpage.cfm Enter data for the LastName form control and submit it. The records that match the criteria specified in the form appear in a table. Code Review Code Description <TABLE> Put data into a table. <TR>...
  • Page 65: Performing Pattern Matching

    Chapter 4: Retrieving and Formatting the Data You Want Performing Pattern Matching Use the SQL LIKE operator and SQL wildcard strings in a SQL WHERE clause when you want to compare a value against a character string field so that the query returns database information based on commonalities.
  • Page 66: Creating Table Joins

    Developing Web Applications with ColdFusion Creating Table Joins Many times, the data that you want to retrieve is maintained in multiple tables. For example, in the database that you’re working with: Department information is maintained in the Departments table. This includes department ID numbers.
  • Page 67: Code Review

    Chapter 4: Retrieving and Formatting the Data You Want <CFIF Form.LastName IS NOT ""> AND Employees.LastName = ’Form.LastName’ </CFIF> </CFQUERY> Code Review Code Description SELECT Departments.Department.Name, Retrieve the fields listed from the Departments Employees.FirstName, and Employees tables, joining the tables based Employees.LastName, on the Department_ID field in each table.
  • Page 68: Returning Query Results To The User

    Developing Web Applications with ColdFusion </TR> <CFOUTPUT QUERY="GetEmployees"> <TR> <TD>#FirstName#</TD> <TD>#LastName#</TD> <TD>#Salary#</TD> </TR> </CFOUTPUT> </TABLE> </BODY> </HTML> Save the file. Test the search interface in your browser. The returned records will not be displayed because you have not entered that code yet, however, you will see the number of records returned if you have debugging enabled.
  • Page 69 Chapter 4: Retrieving and Formatting the Data You Want <BODY> <CFQUERY NAME="GetEmployees" DATASOURCE="CompanyInfo"> SELECT Departments.Department.Name, Employees.FirstName, Employees.LastName, Employees.StartDate, Employees.Salary FROM Departments, Employees WHERE Departments.Department_ID = Employees.Department_ID <CFIF Form.Department_Name IS NOT ""> AND Departments.Department_Name = ’Form.Department_Name’ </CFQUERY> <H4>Employee Data Based on Criteia from Form</H4> <CFIF GetEmployees.RecordCount IS "0">...
  • Page 70 Developing Web Applications with ColdFusion...
  • Page 71: Chapter 5: Making Variables Dynamic

    H A P T E R Making Variables Dynamic Chapter 5 This chapter explains how to use CFML to dynamically populate forms and dynamically generate SQL. Contents Dynamically Populating Select Boxes ............46 Creating Dynamic Checkboxes and Multiple Select Boxes ......47 Testing for a variable’s existence..............
  • Page 72: Dynamically Populating Select Boxes

    Developing Web Applications with ColdFusion Dynamically Populating Select Boxes In the previous chapter, you hard-coded a form’s select box options. Instead of manually entering the information on a form, you can dynamically populate a select box with database fields. When you code this way, changes that you make to a database are automatically reflected on the form page.
  • Page 73: Creating Dynamic Checkboxes And Multiple Select Boxes

    Chapter 5: Making Variables Dynamic </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> </P> <!-- check box --> <P> Contractor? <input type="checkbox" name="Contractor" value="Yes" checked>Yes </P> <!-- reset button --> <INPUT TYPE="reset"...
  • Page 74 Developing Web Applications with ColdFusion Searching numeric values Suppose you want a user to select one or more departments using checkboxes. You query the database to retrieve detailed information on the selected department(s). Select one or more departments to get information on: <INPUT TYPE="checkbox"...
  • Page 75: Multiple Select Lists

    Chapter 5: Making Variables Dynamic The first example searched for department information based on a numeric primary key field called "Department_ID." Suppose, instead, that the primary key is a database field called "DepartmentName" that contains string values. In that case, it’s necessary to make the following modifications: Make the value attribute of the checkboxes equal to the string value.
  • Page 76 Developing Web Applications with ColdFusion multiple select list is a comma-delimited list of the entries selected by the user. For example, a multiple select list contains four entries: Training, Marketing, HR, and Sales. The user selects Marketing and Sales. The value of the form field variable is then ’Marketing’, ’Sales’.
  • Page 77: Testing For A Variable's Existence

    Chapter 5: Making Variables Dynamic <OPTION VALUE="’Sales’">Sales </SELECT> <INPUT TYPE="hidden" NAME="SelectDepts_required" VALUE="You must select at least one department."> If the user selected the Marketing and Sales items, the value of the SelectDepts form field would be ’Marketing’,’Sales’. Just as you did when using checkboxes to search database fields containing string values, use the ColdFusion PreserveSingleQuotes function with multiple select boxes: SELECT * FROM Departments...
  • Page 78: Checking Query Parameters With Cfqueryparam

    Developing Web Applications with ColdFusion There are two ways to use the CFPARAM tag, depending on how you want the validation test to proceed. Use CFPARAM with only the NAME attribute to test that a required variable exists. If it does not exist, the ColdFusion server stops processing the page. Use CFPARAM with both the NAME and DEFAULT attributes to test for the existence of an optional variable.
  • Page 79: Dynamic Sql

    Chapter 5: Making Variables Dynamic Example: Checking data types <!-------------------------------------------------------------------- This example shows the use of CFQUERYPARAM when valid input is given in Dept_ID. -----------------------------------------------------------------------> <HTML> <HEAD> <TITLE>CFQUERYPARAM Example</TITLE> </HEAD> <BODY> <H3>CFQUERYPARAM Example</H3> <CFSET Course_ID=12> <CFQUERY NAME="getFirst" DataSource="CompanyInfo"> SELECT * FROM departments WHERE Dept_ID=<CFQUERYPARAM VALUE="#Dept_ID#"...
  • Page 80 Developing Web Applications with ColdFusion <CFQUERY NAME=" queryname " DATASOURCE=" datasourcename " > ... Base SQL statement <CFIF value operator value > ... additional SQL </CFIF> </CFQUERY> First, you need to create an input form, which asks for information about several fields in the Employees table.
  • Page 81 Chapter 5: Making Variables Dynamic <!-- reset button --> <INPUT TYPE="reset" NAME="ResetForm" VALUE="Clear Form"> <!-- submit button --> <INPUT TYPE="submit" NAME="SubmitForm" VALUE="Submit"> </FORM> </BODY> </HTML> Save the page as askemp.cfm Once you have created the input form, you can then create the action page to process the user’s request.
  • Page 82 Developing Web Applications with ColdFusion <TABLE> <TR> <TH>First Name</TH> <TH>Last Name</TH> <TH>Salary</TH> <TH>Contractor</TH> </TR> <CFOUTPUT QUERY="GetEmployees"> <TR> <TD>#FirstName#</TD> <TD>#LastName#</TD> <TD>#DollarFormat(Salary)#</TD> <TD>#Contract#</TD> </TR> </CFOUTPUT> </TABLE> </BODY> </HTML> Save the page as getemp.cfm Open the file in your browser and enter criteria into any fields, then askemp.cfm submit the form.
  • Page 83 Chapter 5: Making Variables Dynamic CFML Code Description <CFIF #Form.LastName# is not ""> If the user entered anything in the AND Employees.LastName LIKE LastName text box in the form, add "AND ’#form.LastName#%’ Employees.LastName LIKE ‘[what the user </CFIF> entered in the LastName text box]%'" to the SQL statement.
  • Page 84 Developing Web Applications with ColdFusion...
  • Page 85: Chapter 6: Updating Your Data

    H A P T E R Updating Your Data Chapter 6 This chapter describes how to insert, update, and delete data in a database with ColdFusion. Contents Inserting Data ....................60 Creating an HTML Insert Form............... 60 Creating an Action Page to Insert Data............61 Updating Data ....................
  • Page 86: Inserting Data

    Developing Web Applications with ColdFusion Inserting Data Inserting data into a database is usually done with two application pages: An insert form An insert action page You can create an insert form with CFFORM tags (see “Creating Forms with the CFFORM Tag”...
  • Page 87: Data Entry Form Notes And Considerations

    Chapter 6: Updating Your Data </HTML> Save the file as in the directory. insertform.cfm myapps View in a browser. insertform.cfm Data Entry Form Notes and Considerations Creating data entry fields for an HTML form is very simple: You need only create the HTML form fields for each database field into which you want to insert data.
  • Page 88: Updating Data

    Developing Web Applications with ColdFusion Save the page. as insertpage.cfm View in a browser, enter values, and click the Submit button. insertform.cfm The data is inserted into the Employees table and the message appears. To create an insert page with CFQUERY: Create a new application page in Studio.
  • Page 89: Creating An Update Form

    Chapter 6: Updating Your Data Creating an Update Form An update form is similar to an insert form, but there are two key differences: An update form contains a reference to the primary key of the record that is being updated. A primary key is a field or combination of fields in a database table that uniquely identifies each record in the table.
  • Page 90 Developing Web Applications with ColdFusion <INPUT TYPE="Submit" VALUE="Update Information"> </FORM> </CFOUTPUT> </BODY> </HTML> Save the page. as updatedorm.cfm View in a browser. updateform.cfm Code Review Code Description <CFQUERY NAME="GetRecordtoUpdate" Query the CompanyInfo DATASOURCE="CompanyInfo"> datasource and return the records SELECT * in which the employee ID matches FROM Employees what was entered in the URL.
  • Page 91: Creating An Action Page To Update Data

    Chapter 6: Updating Your Data Creating an Action Page to Update Data You can create an action page to update data with either the CFUPDATE tag or CFQUERY with the UPDATE statement. The CFUPDATE tag is the easiest way to handle simple updates from a front end form. The CFUPDATE tag has an almost identical syntax to the CFINSERT tag.
  • Page 92: Deleting Data

    Developing Web Applications with ColdFusion UPDATE Employees SET Firstname=’#Form.Firstname#’, LastName=’#Form.LastName#’, Department_ID=’#Form.Department_ID#’ StartDate=’#Form.StartDate#’> Salary=#Form.Salary#> WHERE Employee_ID=#Employee_ID# </CFQUERY> <H1>Employee Added</H1> <CFOUTPUT> You have updated the information for #Form.FirstName# #Form.LastName# in the Employees database. </CFOUTPUT> Save the page. as updatepage.cfm View in a browser, enter values, and click the Submit button. updateform.cfm The data is updated into the Employees table and the message appears.
  • Page 93: Requiring Users To Enter Values In Form Fields

    Chapter 6: Updating Your Data Enter the following code: <CFQUERY NAME="DeleteEmployee" DATASOURCE="CompanyInfo"> DELETE FROM Employees WHERE Employee_ID = #URL.EmployeeID# </CFQUERY> <HTML> <HEAD> <TITLE>Delete Employee Record</TITLE> </HEAD> <BODY> <H3>The employee record has been deleted.</H3> </BODY> </HTML> Save the page. as deletepage.cfm View in a browser, enter values, and click the Submit button.
  • Page 94: Validating The Data That Users Enter In Form Fields

    Developing Web Applications with ColdFusion example, if you want the error message to read "You must enter your first name," use the syntax: <INPUT TYPE="hidden" NAME="FirstName_required" VALUE="You must enter your first name."> Validating the Data That Users Enter in Form Fields Another limitation of HTML forms is that you cannot validate that users input the type or range of data you expect.
  • Page 95 Chapter 6: Updating Your Data To validate the data users enter in the Insert Form Open the file in Studio. insertform.cfm Modify the file so that it appears as follows: <HTML> <HEAD> <TITLE>Insert Data Form</TITLE> </HEAD> <BODY> <H2>Insert Data Form</H2> <FORM ACTION="insertdata.cfm"...
  • Page 96 Developing Web Applications with ColdFusion <INPUT TYPE="reset" NAME="ResetForm" VALUE="Clear Form"> <INPUT TYPE="submit" NAME="SubmitForm" VALUE="Insert Data"> </FORM> </HTML> Save the file. The VALUE attribute is optional. A default message displays if no value is supplied. When the form is submitted, ColdFusion scans the form fields to find any validation rules you specified.
  • Page 97: Chapter 7: Reusing Code

    H A P T E R Reusing Code Chapter 7 This chapter describes how to reuse common code with CFINCLUDE, and create custom CFML tags that encapsulate common code. Contents Ways to Reuse Code ..................72 Reusing Common Code with CFINCLUDE............ 72 About Custom Tags in CFML................
  • Page 98: Ways To Reuse Code

    Developing Web Applications with ColdFusion Ways to Reuse Code ColdFusion provides several different ways to reuse code. If you are using ColdFusion Studio, you can write code snippets, which you can copy into templates. For more information on writing code snippets, see Using ColdFusion Studio. You can include a template within another template with the CFINCLUDE tag.
  • Page 99: About Custom Tags In Cfml

    Chapter 7: Reusing Code About Custom Tags in CFML Custom tags wrap functionality in a page that can be called from a ColdFusion application page. ColdFusion custom tags built in CFML allow for rapid application development and code re-use while offering off-the-shelf solutions to many programming chores.
  • Page 100: Passing Attribute Values Between Custom Tags

    Developing Web Applications with ColdFusion Defining attributes CFML custom tags support both required and optional attributes. Attributes are defined as name-value pairs. Custom tag attributes conform to CFML coding standards: ColdFusion passes any attributes in the ATTRIBUTES scope. Use the CFPARAM tag at the top of a custom tag to test for and assign defaults for each attribute that may be passed from a calling template.
  • Page 101 Chapter 7: Reusing Code <HTML> <HEAD> <TITLE>Enter Name</TITLE> </HEAD> <BODY> <!--- Enter a name, which could also be done in a form ---> <!--- This example simply uses a cfset ---> <CFSET NameYouEntered="Smith"> <!--- display the current name ---> <CFOUTPUT> Before you leave this page, you’re #NameYouEntered#.<BR>...
  • Page 102 Developing Web Applications with ColdFusion Open the file in your browser. callingpage.cfm The calling page uses the custom tag and displays the results. getmd Code Review Code Description <CFSET NameYouEntered="Smith"> In the calling page, create a variable NameYouEntered and assign it the value "Smith."...
  • Page 103: Nesting Custom Tags

    Chapter 7: Reusing Code Nesting Custom Tags ColdFusion lets you turn a custom tag into a special kind of container that can enclose additional custom tags, which allows you to nest tags. Base tags are also know as ancestors or parent tags, while the tags that base tags call are known as sub tags, descendants, or child tags.
  • Page 104: Passing Data Between Nested Custom Tags

    Developing Web Applications with ColdFusion Passing Data Between Nested Custom Tags A key custom tag feature is the ability of collaborating custom tags to exchange complex data without user intervention and without violating the encapsulation of a tag’s implementation outside the circle of its collaborating tags. The following issues need to be addressed: What data should be accessible? Which tags can communicate to which tags?
  • Page 105 Chapter 7: Reusing Code When CFASSOCIATE is encountered in a sub tag, the sub tag’s attributes are automatically saved in the base tag. The attributes are in a structure appended to the end of an array whose name is ‘ThisTag.collection_name'. The default value for the DataCollection attribute is ‘AssocAttribs'.
  • Page 106 Developing Web Applications with ColdFusion Example: Ancestor data access This example was snipped from a custom tag. <CFIF thisTag.executionMode is ’start’> <!--- Get the tag context stack The list will look something like "CFIF,MYTAGNAME..." ---> <CFSET ancestorList = getBaseTagList()> <!--- Output your own name because CFIF is the first element of the tag context stack --->...
  • Page 107: Passing Custom Tag Arguments Via Cfml Structures

    Chapter 7: Reusing Code <CFELSE> <!--- Say you are lonely ---> I’m not nested inside any custom tags. :^( <P> </CFIF> </CFIF> Passing Custom Tag Arguments via CFML Structures Attributes can be passed to custom tags via the reserved attribute ATTRIBUTECOLLECTION.
  • Page 108: Executing Custom Tags

    Developing Web Applications with ColdFusion Examples Via CFMODULE <CFSET zort=StructNew()> <CFSET zort.X = "-X-"> <CFSET zort.Y = "-Y-"> <CFMODULE TEMPLATE="testtwo.cfm" a="blab" attributecollection=#zort# foo="16"> Via shorthand <CFSET zort=StructNew()> <CFSET zort.X = "-X-"> <CFSET zort.Y = "-Y-"> <CF_TESTTWO a="blab" attributecollection=#zort# foo="16"> Accessing attributes within the custom tag contains this CFML: testtwo.cfm ---custom tag ---<br>...
  • Page 109: Pattern Of Execution

    Chapter 7: Reusing Code AssocAttribs — holds the attributes of all nested tags if CFASSOCIATE was used them. Pattern of execution The same CFML template is executed for both the start and end tag of a custom tag. Modes of execution ColdFusion invokes a custom tag template in either of two modes: Start tag execution End tag execution...
  • Page 110: Terminating Tag Execution

    Developing Web Applications with ColdFusion Terminating tag execution CFEXIT terminates execution of a custom tag. CFEXIT’s METHOD attribute specifies where execution continues. CFEXIT can specify that processing continues from the first child of the tag or continues immediately after the end tag marker. The METHOD attribute can also be used to specify that the tag body should be executed again.
  • Page 111: Installing Custom Tags

    Chapter 7: Reusing Code <CFIF ThisTag.ExecutionMode is ’end’> <CFSET ThisTag.GeneratedContent = ’<!--#ThisTag.GeneratedContent#-->’> </CFIF> Installing Custom Tags Custom tags are just like other .cfm files except that they must be installed in a specific location to be accessible from the calling template. Because ColdFusion loads the first instance it finds of the custom tag called by a template, you should avoid placing copies of a custom tag in different locations.
  • Page 112: Securing Custom Tags

    Developing Web Applications with ColdFusion CFMODULE Attributes Attribute Description Template Required if the NAME attribute is not used. Specifies a relative path to the cfm file. Same as TEMPLATE attribute in CFINCLUDE. Note that the directory must have a mapping defined in ColdFusion Administrator Example: <CFMODULE TEMPLATE="../MyTag.cfm">...
  • Page 113 Chapter 7: Reusing Code The following options are supported: cfencode Command Line Options Option Description input file Name of the file you want to encode. cfencode will not process an encoded file. output file Path and filename of the output file. Warning: If you don’t specify an output file name, a warning message asks if you want to continue, in which case the encoded file will overwrite the source file.
  • Page 114 Developing Web Applications with ColdFusion...
  • Page 115: Chapter 8: Debugging And Error Handling

    H A P T E R Debugging and Error Handling Chapter 8 ColdFusion includes sophisticated debugging and code validation tools. This chapter gives an overview of the debugging options available in the ColdFusion Administrator and how to enable CFML attribute validation. In addition, the ColdFusion Server offers a means to catch and process exceptions in ColdFusion application pages, through the CFTRY, CFCATCH, and CFTHROW tags.
  • Page 116: Debug Settings In The Coldfusion Administrator

    Developing Web Applications with ColdFusion Debug Settings in the ColdFusion Administrator ColdFusion can provide important debugging information for every application page requested by a browser. When enabled, debugging output is shown in a block following normal page output. For detailed information on the debugging and logging settings in the ColdFusion Administrator, see Administering ColdFusion Server .
  • Page 117: Cfml Code Validation

    Chapter 8: Debugging and Error Handling If you get a message that does not explicitly identify the cause of the error, check on key system parameters like available memory and disk space. For information on using the Logging settings and Mail Logging settings, see Administering ColdFusion Server.
  • Page 118: Http/Url

    Developing Web Applications with ColdFusion Connection errors may include problems with the location of files, network connections, and database client library configuration. First, verify that you can connect to the database by clicking the Verify button on the ODBC Data Sources page of the ColdFusion Administrator. If you are unable to make a simple connection from that page, you need to work with your database and/or driver vendor to solve the problem.
  • Page 119: Generating Custom Error Messages (Cferror)

    Chapter 8: Debugging and Error Handling Generating Custom Error Messages (CFERROR) ColdFusion displays error pages that can help you to debug your application. There are four types of errors in ColdFusion: REQUEST — Request errors occur when a application page is requested and there is an error in the page's code.
  • Page 120: Overview Of Exception Handling In Coldfusion

    Developing Web Applications with ColdFusion <P>An error occurred when you requested this page. Please email the Webmaster to report this error. We will work to correct the problem and apologize for the inconvenience.</P> <TABLE BORDER=1> <TR><TD><B>Error Information</B> <BR> #Error.DateTime# <BR> #Error.Template# <BR>...
  • Page 121: Types Of Recoverable Exceptions Supported

    Chapter 8: Debugging and Error Handling Note For cases when the error handler is not able to successfully handle the thrown error, use the CFRETHROW tag within a <CFCATCH> block. <CFTRY> ... Add code here ... <CFCATCH TYPE=" exception type 1"> ...
  • Page 122 Developing Web Applications with ColdFusion Types of recoverable exceptions Type Tag(s) Notes CFTHROW Application-defined Raise exceptions using the CFCATCH TYPE="Application" exception events CFTHROW tag (with an optional CFCATCH TYPE="Any" diagnostic message), then catch a CFCATCH block that has no TYPE using CFCATCH.
  • Page 123: Exception Information In Cfcatch

    Chapter 8: Debugging and Error Handling Specifying the type as ANY causes the ColdFusion Application Server to catch internal exceptions, memory allocation errors, and access violations, which you may not be prepared to handle. Applications can optionally use the CFTHROW tag to raise custom exceptions. Such exceptions are caught with any of the following type specifications: TYPE="custom_exception_type"...
  • Page 124: Tag Context Information

    Developing Web Applications with ColdFusion Exception Property Variables (Continued) Property variable Description CFCATCH.ERRORCODE Any exception that is a part of the CFML exception hierarchy supplies a value for this variable. CFTHROW tags may TYPE="Application" supply a value for this code via the ERRORCODE attribute.
  • Page 125: Database Exceptions

    Chapter 8: Debugging and Error Handling Database exceptions For database exceptions, ColdFusion supplies some additional diagnostic information. The following variables are available whenever the exception type is database: Property variable Description CFCATCH.NATIVEERRORCODE The native error code associated with this exception. Database drivers typically provide error codes to assist in the diagnosis of failing database operations.
  • Page 126: Missinginclude Exceptions

    Developing Web Applications with ColdFusion MissingInclude exceptions For exceptions related to missing files, where the type of exception is MissingInclude, the following variable is available: Property variable Description CFCATCH.MISSINGFILENAME The name of the file missing in an exception of type MissingInclude. Exception handling strategies Use CFTRY with CFCATCH to handle exceptions based on their point of origin within an application page, or based on diagnostic information.
  • Page 127 Chapter 8: Debugging and Error Handling <TITLE>Test CFTRY/CFCATCH</TITLE> </HEAD> <BODY> <HR> <CFINCLUDE TEMPLATE="includeme.cfm"> <CFOUTPUT QUERY="test"> <P>Department: #DepartmentID# <P>Last Name: #LastName# <P>First Name: #FirstName# </CFOUTPUT> <HR> <!--- Use CFCATCH to test for missing included files. ---> <!--- Print Message and Detail error messages. ---> <!--- Block executes only if a MissingInclude exception is thrown.
  • Page 128: Custom Exception Types

    Developing Web Applications with ColdFusion <UL> <LI><B>Message:</B> #CFCATCH.message# <LI><B>Detail:</B> #CFCATCH.Detail# </UL> </CFOUTPUT> </CFCATCH> </CFTRY> </BODY> </HTML> Custom Exception Types The TYPE attribute allows a CFTHROW tag to throw an exception of a specific type, which can be caught by a CFCATCH tag that has a matching TYPE attribute. A CFTHROW tag without a TYPE attribute will throw a TYPE="Application"...
  • Page 129: Chapter 9: Handling Complex Data With Structures

    H A P T E R Handling Complex Data Chapter 9 with 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.
  • Page 130: About Arrays

    Developing Web Applications with ColdFusion About Arrays Traditionally, an array is a tabular structure used to hold data, much like a spreadsheet table with clearly defined limits and dimensions. A 2-dimensional (2D) array is like a simple table. In ColdFusion, you typically use arrays to temporarily store data. For example, if your site allows users to order goods online, their shopping cart contents can be stored in an array.
  • Page 131: Creating An Array

    Chapter 9: Handling Complex Data with Structures ColdFusion dynamic 2D array A ColdFusion 2D array is actually a 1D array that contains a series of additional 1D arrays. Each of the arrays that make up a column can expand and contract independently of any other column.
  • Page 132: Multidimensional Arrays

    Developing Web Applications with ColdFusion Multidimensional Arrays ColdFusion supports dynamic multidimensional arrays. When you declare an array with the ArrayNew function, you can specify up to three dimensions. However, you can increase an array’s dimensions by nesting arrays as array elements: <CFSET myarray=ArrayNew(1)>...
  • Page 133: Adding Elements To An Array

    Chapter 9: Handling Complex Data with Structures firstname[1]=Coleman firstname[2]=Dexter Adding elements to an array You can add elements to an array by simply defining the value of an array element: <CFSET myarray[1]=form.variable> But you can also employ a number of array functions to add data to an array. You can use ArrayAppend to create a new array index at the end of the array, ArrayPrepend to create a new array index at the beginning of the array, and ArrayInsertAt to insert an array index and data.
  • Page 134: Additional Referencing Methods

    Developing Web Applications with ColdFusion <CFOUTPUT> #fullname[1][1]# #fullname[2][1]#<BR> #fullname[1][2]# #fullname[2][2]#<BR> #fullname[1][3]# #fullname[2][3]#<BR> </CFOUTPUT> Additional referencing methods You can reference array indexes in the standard way: myarray[x] where x is the index you want to reference. You can also use ColdFusion expressions inside the square brackets to reference an index.
  • Page 135: Using Nested Loops For 2D And 3D Arrays

    Chapter 9: Handling Complex Data with Structures In the following example, a simple one-dimensional array is populated with the names of the months using a CFLOOP. A second CFLOOP is used to output data in the array to the browser. <CFSET months=ArrayNew(1)>...
  • Page 136: Populating An Array From A Query

    Developing Web Applications with ColdFusion <P>My3darray’s values are currently: <CFLOOP INDEX="Dim1" FROM="1" TO="#ArrayLen(my3darray)#"> <CFLOOP INDEX="Dim2" FROM="1" TO="#ArrayLen(my3darray[Dim1])#"> <CFLOOP INDEX="Dim3" FROM="1" TO="#ArrayLen(my3darray[Dim1][Dim2])#"> <CFOUTPUT> <B>[#Dim1#][#Dim2#][#Dim3#]</B>: #my3darray[Dim1][Dim2][Dim3]#<BR> </CFOUTPUT> </CFLOOP> </CFLOOP> </CFLOOP> Populating an Array from a Query When populating an array from a query, keep the following things in mind: Query data cannot be added to an array all at once.
  • Page 137: Array Functions

    Chapter 9: Handling Complex Data with Structures <CFSET myarray[CurrentRow][1]=test.employee_id[CurrentRow]> <CFSET myarray[CurrentRow][2]=test.LASTNAME[CurrentRow]> <CFSET myarray[CurrentRow][3]=test.FIRSTNAME[CurrentRow]> <CFSET myarray[CurrentRow][4]=test.EMAIL[CurrentRow]> </CFLOOP> <!--- Now, create a loop to output the array contents ---> <CFSET Total_Records=Test.RecordCount> <CFLOOP INDEX="Counter" FROM=1 TO="#Total_Records#"> <CFOUTPUT> ID: #MyArray[Counter][1]#, LASTNAME: #MyArray[Counter][2]#, FIRSTNAME: #MyArray[Counter][3]#, EMAIL: #MyArray[Counter][4]# <BR>...
  • Page 138 Developing Web Applications with ColdFusion Array Functions (Continued) Function Description ArrayResize Resets an array to a specified minimum number of elements. ArraySet Sets the elements in a 1D array in a specified range to a specified value. ArraySort Returns the specified array with elements sorted numerically or alphanumerically.
  • Page 139: About Structures

    Chapter 9: Handling Complex Data with Structures About Structures ColdFusion supports the creation and handling of structures, which enable developers to create and maintain key-value pairs. A structure lets you build a collection of related variables that are grouped under a single name. Structures can also be used as associative arrays.
  • Page 140: Creating And Using Structures

    Developing Web Applications with ColdFusion Creating and Using Structures This section explains how to use the structure functions to create and use structures in ColdFusion. The sample structure is called employee, and is used to add new employees to a corporate information system. Creating structures You create structures by assigning a variable name to the structure with the StructNew function:...
  • Page 141: Finding Information In Structures

    Chapter 9: Handling Complex Data with Structures <CFSET rc=StructInsert(employee, "firstname", "#FORM.firstname#")> <CFSET rc=StructInsert(employee, "lastname", "#FORM.lastname#")> <CFSET rc=StructInsert(employee, "email", "#FORM.email#")> <CFSET rc=StructInsert(employee, "phone", "#FORM.phone#")> <CFSET rc=StructInsert(employee, "department", "#FORM.department#")> Finding information in structures To find the value associated with a specific key, use the StructFind function: StructFind( structure_name, key ) Example The following example shows how to generate a list of keys defined for a structure.
  • Page 142: Copying Structures

    Developing Web Applications with ColdFusion But if the key is dynamic, or contains special characters, you must use the StructKeyExists function: <CFSET temp=StructKeyExists( structure_name, key )> Getting a list of keys in a structure To get a list of the keys in a CFML structure, you use the StructKeyList function: <CFSET temp=StructKeyList( structure_name, [ delimiter ] )>...
  • Page 143: Structure Example

    Chapter 9: Handling Complex Data with Structures Structure Example Structures are particularly useful for grouping together a set of variables under a single name. In the following example files, structures are used to collect information from a form, , and to submit that information to a custom tag at structinsert.cfm addemployee.cfm These example files show how you can use a structure to pass information to a custom...
  • Page 144 Developing Web Applications with ColdFusion <!--- Call the custom tag that adds employees ---> <CF_ADDEMPLOYEE EMPINFO="#employee#"> </CFIF> <HR> <FORM ACTION="structinsert.cfm" METHOD="Post"> <P>First Name:&nbsp; <INPUT NAME="firstname" TYPE="text" HSPACE="30" MAXLENGTH="30"> <P>Last Name:&nbsp; <INPUT NAME="lastname" TYPE="text" HSPACE="30" MAXLENGTH="30"> <P>EMail:&nbsp; <INPUT NAME="email" TYPE="text" HSPACE="30" MAXLENGTH="30"> <P>Phone:&nbsp;...
  • Page 145: Using Structures As Associative Arrays

    Chapter 9: Handling Complex Data with Structures </CFOUTPUT> </CFQUERY> </CFIF> <CFOUTPUT><HR>Employee Add Complete</CFOUTPUT> </CFCASE> </CFSWITCH> Using Structures as Associative Arrays You can also use structures as associative arrays. When used as associative arrays, structures index repetitive data by string keys rather than by integers. You might use structures to create an associative array that matches people’s names with their departments.
  • Page 146: Structure Functions

    Developing Web Applications with ColdFusion called person to hold value of key as loop runs ---> <CFLOOP COLLECTION=#Departments# ITEM="person"> <TR> <TD>#person#</TD> <TD>#Departments[person]#</TD> </TR> </CFLOOP> </TABLE> </CFOUTPUT> Structure Functions There are several functions that help you create and manage structures in ColdFusion applications.
  • Page 147 Chapter 9: Handling Complex Data with Structures Structure Functions (Continued) Function Description StructNew Returns a new structure. StructUpdate Updates the specified key with the specified value. Note that in all cases, except StructDelete, an exception will be thrown if the referenced key or structure does not exist.
  • Page 148 Developing Web Applications with ColdFusion...
  • Page 149: Chapter 10: Building Dynamic Forms

    H A P T E R Building Dynamic Forms Chapter 10 This chapter shows you how to use the CFFORM tag to enrich your forms with sophisticated graphical controls, including several Java applet-based controls. These controls can be enabled without the need to code Java directly. Contents Creating Forms with the CFFORM Tag............
  • Page 150: Creating Forms With The Cfform Tag

    Developing Web Applications with ColdFusion Creating Forms with the CFFORM Tag You’ve already learned how to use HTML forms to gather user input. (See “Using Forms to Specify the Data to Retrieve” on page 30.) This chapter shows you how to use the CFFORM tag to create dynamic forms in CFML.
  • Page 151: Improving Performance With Enablecab

    Chapter 10: Building Dynamic Forms CFFORM Controls (Continued) Control Description CFTREE and Java applet-based controls used to define a tree control and CFTREEITEM individual tree control items. CFTEXTINPUT A Java applet-based control used to define a text input box. CFSELECT Used to define a drop-down list box.
  • Page 152: Input Validation With Cfform Controls

    Developing Web Applications with ColdFusion Input Validation with CFFORM Controls The CFINPUT and CFTEXTINPUT tags include the VALIDATE attributes which allows you to specify a valid data type entry for the control. You can validate user entries on the following data types. Input Validation Controls VALIDATE Entry Description...
  • Page 153: Input Validation With Javascript

    Chapter 10: Building Dynamic Forms Input Validation with JavaScript In addition to native ColdFusion input validation using the VALIDATE attribute of the CFINPUT and CFTEXTINPUT tags, the following tags support the ONVALIDATE attribute , which allows you to specify a JavaScript function to handle your CFFORM input validation: CFINPUT CFSLIDER...
  • Page 154 Developing Web Applications with ColdFusion To use JavaScript to validate form data: Create a new file in Studio. Edit the page so that it appears as follows: <HTML> <HEAD> <TITLE>JavaScript Validation</TITLE> <SCRIPT> <!-- function testbox(form) { Ctrl = form.inputbox1; if (Ctrl.value == "" || Ctrl.value.indexOf (’@’, 0) == -1) { return (false);...
  • Page 155: Building Tree Controls With Cftree

    Chapter 10: Building Dynamic Forms Code Review Code Description <SCRIPT> JavaScript code to test for <!-- valid entry in text box. function testbox(form) { Ctrl = form.inputbox1; if (Ctrl.value == "" || Ctrl.value.indexOf (’@’, 0) == -1) { return (false); } else return (true);...
  • Page 156: Grouping Output From A Query

    Developing Web Applications with ColdFusion QUERY="engquery" QUERYASROOT="yes" IMG="folder,document"> </CFTREE> </CFFORM> Save the page and view it in your browser. Code Review Code Description <CFTREE NAME="tree1" Create a tree and name it tree1. REQUIRED="yes" Specify that a user must select an item in the tree. HSCROLL="no"...
  • Page 157: Cftree Form Variables

    Chapter 10: Building Dynamic Forms <!--- Build the tree control ---> <CFFORM NAME="form1" ACTION="submit.cfm" METHOD="Post"> <CFTREE NAME="tree1" HSCROLL="no" VSCROLL="no" BORDER="yes" HEIGHT="350" REQUIRED="yes"> <CFTREEITEM VALUE="Department_ID, FullName" QUERY="deptquery" QUERYASROOT="Department_ID" IMG="cd,folder"> </CFTREE> <BR><INPUT TYPE="Submit" VALUE="Submit"> </CFFORM> Save the page and view it in your browser. Code Review Code Description...
  • Page 158: Input Validation

    Developing Web Applications with ColdFusion form.treename.path — Returns the complete path of the user selection, in the form: root\node1\node2\node_n\value The root part of the path is only returned if you set the COMPLETEPATH attribute tof CFTREE to YES; otherwise, the path value starts with the first node. In the previous example, if the user selects the name "John Allen"...
  • Page 159: Image Names In A Cftree

    Chapter 10: Building Dynamic Forms Example: Multi-level tree control When populating a CFTREE, you manipulate the structure of the tree by specifying a TREEITEM parent. In this example, every TREEITEM, except the top level, specifies a parent. The PARENT attribute allows your CFTREE to show the relationships between elements in the tree control.
  • Page 160: Embedding Urls In A Cftree

    Developing Web Applications with ColdFusion The built-in image names are: computer document element folder floppy fixed remote Embedding URLs in a CFTREE The HREF attribute in the CFTREEITEM tag allows you to designate tree items as links. To use this feature in a CFTREE, you simply define the destination of the link in the HREF attribute of CFTREEITEM.
  • Page 161: Specifying Which Tree Items To Send To The Action Page

    Chapter 10: Building Dynamic Forms Code Review Code Description HREF="http://www.allaire.com"> Make the node of the tree a link. HREF="http://forums.allaire.com" Make the node of the tree a link. Note HREF can refer to the name of a column in a query if the tree item is populated from that query.
  • Page 162: Populating A Grid From A Query

    Developing Web Applications with ColdFusion Populating a grid from a query To populate a grid from a query: Open a new file named in Studio. grid1.cfm Edit the file so that it appears as follows: <CFQUERY NAME="empdata" DATASOURCE="CompanyInfo"> SELECT * FROM Employees </CFQUERY>...
  • Page 163: Creating An Updateable Grid

    Chapter 10: Building Dynamic Forms Code Review Code Description <CFGRID NAME="employee_grid" Create a grid named "employee_grid" QUERY="empdata" and popluate it with the results of the query "empdata" SELECTMODE="single"> Allow the user to select only one cell. <CFGRIDCOLUMN NAME="Employee_ID"> Put the contents of the Employee_ID column in the query results in the first column of the grid <CFGRIDCOLUMN NAME="LastName">...
  • Page 164: Editing Data In A Cfgrid

    Developing Web Applications with ColdFusion Editing data in a CFGRID To enable grid editing, you use the SELECTMODE="EDIT" attribute. When enabled, a user can edit cell data and insert or delete grid rows. When a CFFORM containing a CFGRID is submitted, data about changes to grid cells are stored in one-dimensional arrays you can reference like any other ColdFusion array.
  • Page 165 Chapter 10: Building Dynamic Forms HEADERITALIC="NO" HEADERBOLD="YES" DISPLAY="YES" SELECT="YES"> <CFGRIDCOLUMN NAME="Department_ID" HEADER="Department" WIDTH=240 ITALIC="No" HEADERALIGN="center" HEADERITALIC="No" HEADERBOLD="Yes" BOLD="Yes" DISPLAY="Yes"> </CFGRID> <INPUT TYPE="Submit" VALUE="Submit"> </CFFORM> Save the file as grid2.cfm To update the data source with CFQUERY: Open a new file in Studio. Modify the file so that it appears as follows: <HTML>...
  • Page 166 Developing Web Applications with ColdFusion </CFQUERY> <CFELSEIF form.employee_grid.rowstatus.action[Counter] IS "U"> <CFQUERY NAME="UpdateExistingEmployee" DATASOURCE="CompanyInfo"> UPDATE Employees LastName=’#form.employee_grid.LastName[Counter]#’, Department_ID=#form.employee_grid.Department_ID[Counter]# WHERE Employee_ID=#form.employee_grid.original.Employee_ID[Counter]# </CFQUERY> <CFELSEIF form.employee_grid.rowstatus.action[Counter] IS "I"> <CFQUERY NAME="InsertNewEmployee" DATASOURCE="CompanyInfo"> INSERT into Employees (Employee_ID, LastName, Department_ID) VALUES (#form.employee_grid.Employee_ID[Counter]#, ’#form.employee_grid.LastName[Counter]#’, #form.employee_grid.Department_ID[Counter]#) </CFQUERY> </CFIF> </CFLOOP> </CFIF>...
  • Page 167 Chapter 10: Building Dynamic Forms How user edits are stored The following arrays are created to keep track of edits to grid rows and cells: Arrays Used to Store Grid Cell Edit Information Array reference Description gridname . colname [ row_index ] Stores the new value of an edited grid cell gridname.
  • Page 168: Building Slider Bar Controls

    Developing Web Applications with ColdFusion Building Slider Bar Controls You can use the CFSLIDER control to create a slider control and define a wide range of formatting options for slider label text, , colors for the groove in which the slider knob moves, label font name, size, boldface, italics, and color, as well as slider scale increments, range, positioning, and behavior.
  • Page 169: Cftextinput Form Variable

    Chapter 10: Building Dynamic Forms validation methods using either a JavaScript or the VALIDATE attribute in CFTEXTINPUT. The following example shows a basic CFTEXTINPUT control. This example validates a date entry, which means that a user must enter a valid date in the form mm/dd/yy. For a complete list of validation formats, refer to the CFML Language Reference.
  • Page 170: Embedding Java Applets

    Developing Web Applications with ColdFusion To populate a drop-down list box with query data using CFSELECT: Open a new file in Studio. Modify the file so that it appears as follows: <CFQUERY NAME="getNames" DATASOURCE="CompanyInfo"> SELECT * FROM Employees </CFQUERY> <CFFORM NAME="Form1" ACTION="submit.cfm" METHOD="Post">...
  • Page 171: Registering A Java Applet

    Chapter 10: Building Dynamic Forms Parameter options — You can override parameter values you defined in the Administrator by specifying the parameter value pair in CFAPPLET. Unless overridden, ColdFusion uses the parameter value pairs you defined in the Administrator. When an applet is registered, enter just the applet source and the form variable name: <CFAPPLET APPLETSOURCE="Calculator"...
  • Page 172: Using Cfapplet To Embed An Applet

    Developing Web Applications with ColdFusion Applet Registration Fields (Continued) 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.
  • Page 173: Handling Form Variables From An Applet

    Chapter 10: Building Dynamic Forms <CFAPPLET APPLETSOURCE="myapplet" NAME="applet1_var" HEIGHT=400 WIDTH=200 VSPACE=125 HSPACE=125 ALIGN="left"> Overriding parameter values You can also override the values you assigned to applet parameters in the Administrator by providing new values for any parameter. Note that in order to override a parameter, you must have already defined the parameter and a default value for it in the ColdFusion Administrator Applets page.
  • Page 174 Developing Web Applications with ColdFusion...
  • Page 175: Chapter 11: Indexing And Searching Data

    H A P T E R Indexing and Searching Data Chapter 11 You can provide a full-text search capability for documents and data sources on a ColdFusion site by enabling the Verity search engine. Contents Searching a ColdFusion Web Site..............150 Supported File Types..................
  • Page 176: Searching A Coldfusion Web Site

    Developing Web Applications with ColdFusion Searching a ColdFusion Web Site Until now, you’ve searched for records in databases based on the value of particular fields using ODBC. However, to efficiently search through paragraphs of text or files of varying types requires full-text search capabilites. The Verity, Inc. search engine is bundled with ColdFusion to provide full-text indexing and searching.
  • Page 177: Online Verity Training

    Chapter 11: Indexing and Searching Data Online Verity training A video titled "Creating Search Engines with Verity" is available at http:// alive.allaire.com. The video gives an overview of the Verity implementation in ColdFusion and illustrates the development process with sample code. The video is part of Allaire Alive, an educational service that offers Web videos on topics specific to ColdFusion development and application deployment as well as broader industry issues.
  • Page 178: Support For International Languages

    Developing Web Applications with ColdFusion Supported File Types (Continued) Documents Versions Type MS Word for DOS 4, 5, 6 Binary MS Word for Macintosh 4.0, 5.0, 6.0 Binary MS Notepad, WordPad Binary MS Write, MS Works Binary XYWrite 4.12 Binary Spreadsheets Corel QuattroPro 7, 8...
  • Page 179: Steps In Creating A Searchable Data Source

    Chapter 11: Indexing and Searching Data Spanish Swedish The default language for Verity collections is English. To index data in one of the supported languages, you must select the language from the drop-down list when you create a collection on the ColdFusion Administrator Verity page. You must then enter the selected language as a value of the LANGUAGE attribute in both the CFINDEX and CFSEARCH tags used against that collection.
  • Page 180: Using The Coldfusion Administrator To Create A Collection

    Developing Web Applications with ColdFusion Using the ColdFusion Administrator to create a collection To create a new collection: Open the ColdFusion Administrator Verity page. If you checked the option to install the ColdFusion Documentation, the documentation collection is listed by default. The Verity engine is used to search our online documents.
  • Page 181 Chapter 11: Indexing and Searching Data <HEAD> <TITLE>Collection Creation Input Form</TITLE> </HEAD> <BODY> <H2>Specify a collection</H2> <FORM ACTION="collectioncreateaction.cfm" METHOD="POST"> <P>Collection name: <INPUT TYPE="text" NAME="CollectionName" SIZE="25"></P> <P>What do you want to do with the collection?</P> <INPUT TYPE="radio" NAME="CollectionAction" VALUE="Create" checked>Create<BR> <INPUT TYPE="radio" NAME="CollectionAction"...
  • Page 182 Developing Web Applications with ColdFusion To create a collection action page: Open a new file in Studio. Modify the file so that it appears as follows: <HTML> <HEAD> <TITLE>CFCOLLECTION</TITLE> </HEAD> <BODY> <H2>Collection creation</H2> <CFOUTPUT> <CFSWITCH EXPRESSION=#FORM.CollectionAction#> <CFCASE VALUE="Create"> <CFCOLLECTION ACTION="Create" COLLECTION="#FORM.CollectionName#"...
  • Page 183: Populating And Indexing A Collection

    Chapter 11: Indexing and Searching Data Populating and Indexing a Collection At this point, the new collection is just an empty shell. To populate the collection with indexed data, you can use either of two methods: The CF Administrator The CFINDEX tag You can use the Verity Wizard in ColdFusion Studio to create the templates to make yur documents searchable.
  • Page 184 Developing Web Applications with ColdFusion Check the Recursively index subdirectories box if you want to extend the indexing operation to all directories below the selected path. Optionally, you can enter a Return URL to prepend to all indexed files. This allows you to easily create a link to any of the files in the index.
  • Page 185: Building A Search Interface

    Chapter 11: Indexing and Searching Data To use CFINDEX to index a collection: Open a new file in Studio. Modify the file so that it appears as follows: <HTML> <HEAD> <TITLE>Creating Index</TITLE> </HEAD> <BODY> <H2>Indexing Complete</H2> <CFINDEX COLLECTION="#Form.IndexColl#" KEY="#Form.IndexDir#" ACTION="REFRESH" TYPE="PATH"...
  • Page 186: Basic Search Operations

    Developing Web Applications with ColdFusion Basic search operations To search the collection: Create a new file in Stuio. Modify the file so that it appears as follows: <HTML> <HEAD> <TITLE>Select the collection to search</TITLE> </HEAD> <BODY> <H2>Search</H2> <FORM METHOD="Post" ACTION="collectionsearchaction.cfm"> <P>Enter the collection you want to search: <INPUT TYPE="text"...
  • Page 187: Summarization

    Chapter 11: Indexing and Searching Data <BODY> <CFSEARCH NAME="Search1" COLLECTION="#form.collection#" FORM TYPE="#form.type#" CRITERIA="#form.searchstring#"> <H2>Search Results</H2> <CFOUTPUT> #Search1.RecordCount# found out of #Search1.RecordsSearched# searched. </CFOUTPUT> <HR NOSHADE> <CFOUTPUT QUERY="Search1"> <A HREF="#Search1.URL#">#Search1.title#</A><BR> </CFOUTPUT> <HR NOSHADE> </BODY> </HTML> Save the file as collectionsearchaction.cfm View the file in your browser, enter values in the collectionsearchform.cfm form, then submit it.
  • Page 188: Cfsearch Properties

    Developing Web Applications with ColdFusion CFSEARCH properties Three properties are generated for each CFSEARCH query that provide information about a particular query: RecordCount — The total number of records returned by the query. CurrentRow — The current row of the query being processed by CFOUTPUT. RecordsSearched —...
  • Page 189: Indexing Cfldap Query Results

    Chapter 11: Indexing and Searching Data This CFINDEX statement specifies the MessageText column as the core of the collection and names the table’s primary key, the Message_ID column, as the KEY value. Note that the TITLE attribute names the Subject column. The TITLE attribute can be used to designate an output parameter.
  • Page 190: Indexing Cfpop Query Results

    Developing Web Applications with ColdFusion <!--- Run the LDAP query ---> <CFLDAP NAME="OrgList" SERVER="myserver" ACTION="query" ATTRIBUTES="o, telephonenumber, dn, mail" SCOPE="onelevel" FILTER="(|(O=a*) (O=b*))" SORT="o" START="c=US"> <!--- Output query result set ---> <CFOUTPUT QUERY="OrgList"> DN: #dn# <BR> O: #o# <BR> TELEPHONENUMBER: #telephonenumber# <BR> MAIL: #mail# <BR>...
  • Page 191: Using Query Expressions

    Chapter 11: Indexing and Searching Data <!--- Run POP query ---> <CFPOP ACTION="getall" NAME="p_messages SERVER="mail.mycompany.com" USERNAME="user1" PASSWORD="user1"> <!--- Output POP query result set ---> <CFOUTPUT QUERY="p_messages"> #MESSAGENUMBER# <BR> #FROM# <BR> #TO# <BR> #SUBJECT# <BR> #BODY# <BR> =========================<BR> <!--- Index result set ---> <CFINDEX ACTION="update"...
  • Page 192: Simple Query Expressions

    Developing Web Applications with ColdFusion pass a simple query expression to the search engine directly from an HTML input form. The Verity query language provides many operators and modifiers for composing queries. The following search techniques can be used in searching a Verity collection: Word searches Proximity searches Concept–based...
  • Page 193 Chapter 11: Indexing and Searching Data density of the search term in the searched documents. The more frequent the occurrence of a word in a document, the higher the document’s score. As a result, the search engine ranks documents according to word density as it searches for the word you specify, as well as words that have the same stem.
  • Page 194: Special Characters

    Developing Web Applications with ColdFusion Special characters A number of characters are handled in particular ways by the search engine. Special Search Characters Characters Description , () [ These characters end a text token. = > <! These characters also end a text token. They are terminated by an associated end character.
  • Page 195 Chapter 11: Indexing and Searching Data When prefix notation is used, precedence is handled explicitly within the expression. The following example means: "Look for documents that contain b and c first, then documents that contain a": OR (a, AND (b,c)) When infix notation is used, precedence is implicit in the expression.
  • Page 196: Searching With Wildcards

    Developing Web Applications with ColdFusion Searching with Wildcards This table shows the wildcard characters for searching Verity collections. Verity Wildcard Characters Wildcard Description Question. Specifies any single alphanumeric character. Asterisk. Specifies zero or more alphanumeric characters. Avoid using the asterisk as the first character in a search string. Asterisk is ignored in a set, [] or an alternative pattern {}.
  • Page 197: Operators And Modifiers

    Chapter 11: Indexing and Searching Data left curly brace ({) left bracket ([) less than sign (<) backquote (‘ ) In addition to the backslash character, you can use paired backquotes (‘ ‘ ) to interpret special characters as literals. For example, to search for the wildcard string "a{b" you can surround the string with backquotes, as follows: ‘a{b‘...
  • Page 198 Developing Web Applications with ColdFusion Natural language operators — Allow the use of natural language expressions in forming queries. Ordinarily, you use operators in explicit searches. They are used in the following manner: "<operator>search_string" Evidence operators Evidence operators can be used to specify either a basic word search or an intelligent word search.
  • Page 199 Chapter 11: Indexing and Searching Data The following table describes each operator. Verity Proximity Operators Operator Description NEAR Selects documents containing specified search terms. The closer the search terms are to one another within a document, the higher the document’s score. The document with the smallest possible region containing all search terms always receives the highest score.
  • Page 200 Developing Web Applications with ColdFusion The following operators are used for numeric and date comparisons. Verity Numerical and Date Relational Operators Operator Description Equals > Greater than >= Greater than or equal to < Less than <= Less than or equal to Text comparison operators match words and parts of words.
  • Page 201 Chapter 11: Indexing and Searching Data VerityText Comparison Operators (Continued) Operator Description ENDS Selects documents by matching the character string you specify with the ending characters of the values stored in a specific document field. SUBSTRING Selects documents by matching the query string you specify with any portion of the strings in a specific document field.
  • Page 202 Developing Web Applications with ColdFusion YearPlaceText (Continued) Year Place Text 1991 Oregon Text about Oregon 1991 1992 Utah Text about Utah 1992 The following application page matches records that have 1990 in the TEXT column and are in the Place Utah. The search is performed against the collection that contains the TEXT column and then is narrowed further by searching the string "Utah"...
  • Page 203 Chapter 11: Indexing and Searching Data </CFOUTPUT> <CFOUTPUT QUERY="GetText_Search"> #GetText_Search.TITLE# <BR> </CFOUTPUT> Concept operators Concept operators combine the meaning of search elements to identify a concept in a document. Documents retrieved using concept operators are ranked by relevance. The following table describes each concept operator. Verity Concept Operators Operator Description...
  • Page 204: Modifiers

    Developing Web Applications with ColdFusion The following table lists the score operators. Verity Score Operators Operator Description YESNO Forces the score of an element to 1 if the element’s score is non- zero: <YESNO>mainframe If the retrieval result of the search on "mainframe" is 0.75, the YESNO operator forces the result to 1.
  • Page 205 Chapter 11: Indexing and Searching Data Search modifiers Modifiers are combined with operators to change the standard behavior of an operator in some way. For example, you can use the CASE modifier with an operator to specify that you want to match the case of the search word. Modifiers are as follows.
  • Page 206: Managing Collections

    Developing Web Applications with ColdFusion Verity Search Modifiers (Continued) Modifier Description Used to exclude documents that contain the specified word or phrase. Used only with the AND and OR operators. Java <AND> programming <NOT> coffee ORDER Used to specify that the search elements must occur on the same order in which they were specified in the query.
  • Page 207: Securing A Collection

    Chapter 11: Indexing and Searching Data Delete (when used as a CFINDEX ACTION) — Deletes the specified KEY value, or comma-separated values, from the collection. Delete (when used on the Administrator Verity page or in CFCOLLECTION) — Deletes the entire collection. Update —...
  • Page 208 Developing Web Applications with ColdFusion...
  • Page 209: Chapter 12: Using The Application Framework

    H A P T E R Using the Application Chapter 12 Framework The ColdFusion Web Application Framework is a powerful tool you can use to help structure your ColdFusion applications. This section describes how to create and use file, the application page that controls the application Application.cfm framework.
  • Page 210: Understanding The Web Application Framework

    Developing Web Applications with ColdFusion Understanding the Web Application Framework A ColdFusion application is a collection of application pages that work together. Applications can be as simple as a guest book or as sophisticated as a full Internet commerce system with catalog pages, shopping carts, and reporting. You can combine individual applications to create advanced Web systems.
  • Page 211: Custom Error Handling

    Chapter 12: Using the Application Framework Custom error handling Using the CFERROR tag, you can display customized HTML pages when errors occur. This allows you to maintain a consistent look and feel within your application even when errors occur. It also allows you to optionally suppress the display of error information.
  • Page 212 Developing Web Applications with ColdFusion Development: The application is easier to develop and maintain because the application page files are well organized. Portability: The application can be more easily moved to another server or another part of a server without having to change any code in the application page files.
  • Page 213: Behavior With Cfinclude

    Chapter 12: Using the Application Framework Bandwidth Associates Web Wonders, Inc. Application.cfm Application.cfm Products Products Consulting Orders Support Application.cfm Marketing Services Application.cfm Sales Application.cfm Behavior with CFINCLUDE Only one file is ever processed for each ColdFusion application Application.cfm page. The presence of an file is an implicit CFINCLUDE.
  • Page 214: Naming The Application

    Developing Web Applications with ColdFusion Default variables Custom error pages Data sources Default style settings Exclusive locks Other application-level constants Note Because UNIX is case sensitive, the application framework file must be spelled with an initial capital, , for applications that run Application.cfm on UNIX platforms.
  • Page 215: Choosing A Client Variable Storage Method

    Chapter 12: Using the Application Framework <!--- This example illustrates CFAPPLICATION ---> <!--- Name the application and enable client management---> <CFAPPLICATION NAME="SearchApp" CLIENTMANAGEMENT="Yes"> Save the file as in the root directory of your application Application.cfm framework. Choosing a client variable storage method Once you have enabled client state management, you then have to determine where you want to store client variables.
  • Page 216: Managing Client State In A Clustered Environment

    Developing Web Applications with ColdFusion Cookie storage When you set the cookie that ColdFusion creates has the CLIENTSTORAGE="Cookie" application’s name. Storing client data in a cookie is scalable to large numbers of clients, but this storage mechanism has some limitations. Chief among them is that if the client turns off cookies in the browser, client variables won’t work.
  • Page 217: Creating A Client Variable

    Chapter 12: Using the Application Framework Creating a client variable To create a client variable and set the value of the parameter, use the CFSET or CFPARAM tag., for example: <CFSET Client.FavoriteColor="Red"> Once a client variable has been set in this manner, it is available for use within any application page in your application that is accessed by the client for whom the variable is set.
  • Page 218: Getting A List Of Client Variables

    Developing Web Applications with ColdFusion the client ID (CFID)and the client security token (CFTOKEN) between pages, either in hidden form fields or appended to URLs. You accomplish this using the variable Client.URLTOKEN or Session.URLTOKEN. Note In ColdFusion, client state management is explicitly designed to work with cookies, the standard tool for identifying clients.
  • Page 219: Exporting The Client Variable Database

    Chapter 12: Using the Application Framework Variable caching All client variable reads and writes are cached to help decrease the overhead of client state management operations. See Administering ColdFusion Server for information on variables and server clustering. Exporting the client variable database If your client variable database is stored in the system registry and you need to move it to another machine, you can export the registry key that stores your client variables and take it to your new server.
  • Page 220: Differentiating Client, Session, And Application Variables

    Developing Web Applications with ColdFusion For information on setting time-outs for variables, See Administering ColdFusion Server. Differentiating client, session, and application variables This table shows the relationships among client, session, and application variables.: Kinds of Variables Variable Application Client Client Session Time-out Type...
  • Page 221: Storing Session Data In Session Variables

    Chapter 12: Using the Application Framework period, ColdFusion interprets this as the end of the session and clears any variables associated with that session. The default time-out for session variables is set to 20 minutes. In the Variables page of the ColdFusion Administrator, you can change this time-out value.
  • Page 222: Using Application Variables

    Developing Web Applications with ColdFusion to be triggered on every page ---> <CFSET MainPage = "default.cfm"> <CFSET session.current_location = "Davis, Porter, Alewife"> <CFSET sm_location = "dpa"> <CFSET current_page = "#cgi.path_info#?#cgi.query_string#"> Using Application Variables Application variables require an application name be associated with them and are always scoped within that application name.
  • Page 223: Tips For Using Session And Application Variables

    Chapter 12: Using the Application Framework You can set the time-out period for application variables within a specific application (thereby overriding the default setting in the ColdFusion Administrator) by using the APPLICATIONTIMEOUT attribute of the CFAPPLICATION tag. If no clients access the application within the specified time-out period, ColdFusion Server destroys its application variables.
  • Page 224: Using Cflock For Exclusive Locking

    Developing Web Applications with ColdFusion Example: Application.cfm The following example shows a complete file for the sample Application.cfm Products application: <!--- Set application name and enable client variables option, with client variables stored in a data source called mycompany ---> <CFAPPLICATION NAME="Products"...
  • Page 225: Using Cflock

    Chapter 12: Using the Application Framework Exclusive locks allow only one request to process the locked code. Read-only locks allow multiple requests to execute concurrently, provided that no exclusive locks are executing. Note Unless you specify the TYPE attribute, the default lock is exclusive. You should minimize the use of exclusive locks.
  • Page 226: Cflock Examples

    Developing Web Applications with ColdFusion A deadlock is a state in which no request can execute the locked section of the page. Thus, all requests to the protected section of the page are blocked until there is a time- out. The following table shows one scenario that would cause a deadlock. Deadlock Scenario User 1 User 2...
  • Page 227 Chapter 12: Using the Application Framework The following sample code might be part of the file. Application.cfm <HTML> <HEAD> <TITLE>Define Session and Application Variables</TITLE> </HEAD> <H3>CFAPPLICATION Example</H3> <P>CFAPPLICATION defines scoping for a ColdFusion applicationand enables or disables the storing of client and/or session variables. This tag is placed in the Application.cfm file for the current application.
  • Page 228 Developing Web Applications with ColdFusion <CFOUTPUT> E-Turtleneck is proud to say that we have sold #application.number# turtlenecks to date. </CFOUTPUT> </CFLOCK> In general, you should limit lock scopes. When locking variables, queries, and arrays (anything other than structures), you can copy to a local variable in the CFLOCK block, then reference the local variable.
  • Page 229 Chapter 12: Using the Application Framework <!--- Show the form only if it has not been submitted. ---> <CFELSE> <FORM ACTION="cflock.cfm" METHOD="Post"> <P> Congratulations! You have just selected the longest wearing, most comfortable turtleneck in the world. Please indicate the color and size you want to buy.</P>...
  • Page 230 Developing Web Applications with ColdFusion dynamic value for the NAME attribute to allow protection of a file with any given name. <CFLOCK NAME=#FileName# TIMEOUT=60 TYPE="Exclusive"> <CFFILE ACTION="Append" FILE=#FileName# OUTPUT=#TextToAppend#> </CFLOCK> Example of protecting ColdFusion Extensions This example illustrates how a custom tag wrapper can be built around CFXs that are not thread-safe.
  • Page 231 H A P T E R Sending and Receiving Email Chapter 13 You can add interactive email features to your ColdFusion applications, providing complete two-way interface to mail servers via the CFMAIL tag and the CFPOP tag. The boom in Internet mail services makes ColdFusion’s enhanced email capability a vital link to your users.
  • Page 232: Using Coldfusion With Mail Servers

    Developing Web Applications with ColdFusion Using ColdFusion with Mail Servers Adding email to your ColdFusion applications lets you respond automatically to user requests. You can use email in your ColdFusion applications in many different ways. These are just a few examples: Trigger email messages based on users’...
  • Page 233: Sending Smtp Mail With Cfmail

    Chapter 13: Sending and Receiving Email Sending SMTP mail with CFMAIL The CFMAIL tag provides support for sending SMTP email from within ColdFusion applications. The CFMAIL tag is similar to the CFOUTPUT tag, except that CFMAIL outputs the generated text as SMTP mail messages rather than to a page. You can use all the attributes and commands that you use with CFOUTPUT with CFMAIL as well.
  • Page 234: Sending Form-Based Email

    Developing Web Applications with ColdFusion Use a query to send a customized mail message, such as a billing statement to a list of recipients that is dynamically populated from a database. Send a MIME file attachment along with a mail message. Sending form-based email In the example below, the contents of a customer inquiry form submittal are forwarded to the marketing department.
  • Page 235: Sending Email To Multiple Recipients

    Chapter 13: Sending and Receiving Email the "ProductRequests" query, while the text above and below it serve as the header and footer (respectively) for the mail message. Sending email to multiple recipients In the following example, a query ("CFBetaTesters") is run to retrieve a list of people who are beta testing ColdFusion.
  • Page 236: Attaching A Mime File

    Developing Web Applications with ColdFusion Company Name: #Company# Contact: #FirstName# #LastName# Address: #Address1# #Address2# #City#, #State# #Zip# Phone: #Phone# Fax: #Fax# Home Page: #HomePageURL# Please let us know if any of the above information has changed, or if we need to get in touch with someone else in your organization regarding this request.
  • Page 237: Advanced Sending Options

    Chapter 13: Sending and Receiving Email Advanced Sending Options The ColdFusion implementation of SMTP mail uses a spooled architecture. This means that when a CFMAIL tag is processed in an application page, the messages generated are not sent immediately. Instead, they are spooled to disk and processed in the background.
  • Page 238: Using Cfpop

    Developing Web Applications with ColdFusion Use CFPOP in applications when you want to receive email. Here are two instances where implementing POP mail makes sense: If your site has generic mailboxes that are read by more than one person (sales@yourcompany.com), it may be more efficient to construct a ColdFusion mail front-end to supplement individual user mail clients.
  • Page 239: Handling Pop Mail

    Chapter 13: Sending and Receiving Email Handling POP Mail This section gives an example of each of the following usages: Retrieving only message headers Retrieving a message body Retrieving attachments Deleting messages Returning only message headers The header includes: DATE FROM MESSAGENUMBER REPLYTO...
  • Page 240: Returning An Entire Message

    Developing Web Applications with ColdFusion Cc: #HTMLEditFormat(Sample.CC)# <BR> ReplyTo: #HTMLEditFormat(Sample.REPLYTO)# <BR> </CFOUTPUT> </BODY> </HTML> Change the following line so that it refers to a valid POP mail server, as well as a valid user name and password: <CFPOP SERVER="mail.company.com" USERNAME=#username# PASSWORD=#password# Save the file as under the Web root directory.
  • Page 241: Returning Attachments With Messages

    Chapter 13: Sending and Receiving Email the message body:</H2> <CFPOP SERVER="mail.company.com" USERNAME=#username# PASSWORD=#password# ACTION="GetAll" NAME="Sample"> <CFOUTPUT QUERY="Sample"> MessageNumber: #HTMLEditFormat(Sample.MESSAGENUMBER)# <BR> To: #HTMLEditFormat(Sample.TO)# <BR> From: #HTMLEditFormat(Sample.FROM)# <BR> Subject: #HTMLEditFormat(Sample.SUBJECT)# <BR> Date: #HTMLEditFormat(Sample.DATE)# <BR> Cc: #HTMLEditFormat(Sample.CC)# <BR> ReplyTo: #HTMLEditFormat(Sample.REPLYTO)# <BR> Body: #HTMLCodeFormat(Sample.BODY)# <BR> Header: #HTMLCodeFormat(Sample.HEADER)# <BR>...
  • Page 242: Deleting Messages

    Developing Web Applications with ColdFusion <BODY> <H2>This example retrieves message header, body, and all attachments:</H2> <CFPOP SERVER="mail.company.com" USERNAME=#username# PASSWORD=#password# ACTION="GetAll" ATTACHMENTPATH="c:\attachdir" NAME="Sample"> <CFOUTPUT QUERY="Sample"> MessageNumber: #HTMLEditFormat(Sample.MESSAGENUMBER)# <BR> To: #HTMLEditFormat(Sample.TO)# <BR> From: #HTMLEditFormat(Sample.FROM)# <BR> Subject: #HTMLEditFormat(Sample.SUBJECT)# <BR> Date: #HTMLEditFormat(Sample.DATE)# <BR> Cc: #HTMLEditFormat(Sample.CC)# <BR> ReplyTo: #HTMLEditFormat(Sample.REPLYTO)# <BR>...
  • Page 243 Chapter 13: Sending and Receiving Email returned will be 1,2,3,4. If messages 1 and 2 are then deleted within a single CFPOP tag, messages 3 and 4 will be assigned message numbers 1 and 2, respectively. To delete messages: Create a new file in Studio. Modify the file so that it appears as follows: <HTML>...
  • Page 244 Developing Web Applications with ColdFusion...
  • Page 245 H A P T E R Managing Files on the Server Chapter 14 The CFFILE, CFDIRECTORY, and CFCONTENT tags handle browser/server file management tasks. To perform server-to-server operations, use the CFFTP tag. Contents Using CFFILE ....................220 Uploading Files....................220 Setting File and Directory Attributes ............
  • Page 246: Using Cffile

    Developing Web Applications with ColdFusion Using CFFILE The CFFILE tag gives you the ability to work with files on your server in a number of ways: Uploading files from a client to the Web server using an HTML form. Moving, renaming, copying, or deleting files on the server. Reading, writing, or appending to text files on the server.
  • Page 247 Chapter 14: Managing Files on the Server Code Review Code Description <FORM ACTION="uploadfileaction.cfm" Create a form that contains file ENCTYPE="multipart/form-data" selection fields for upload by the METHOD="post"> user. <INPUT TYPE="file" Allow the user to input a field. NAME="FiletoUpload" (The File input type SIZE="45">...
  • Page 248: Resolving Conflicting File Names

    Developing Web Applications with ColdFusion Change the following line to point to an appropriate location on your server: DESTINATION="c:\inetpub\wwwroot\HR\" Save the file as under the Web root directory. uploadfileaction.cfm myapps View in your browser, enter values and submit the form. uploadfileform.cfm The file you specified is uploaded.
  • Page 249: Setting File And Directory Attributes

    Chapter 14: Managing Files on the Server A file’s MIME type is determined by the browser. Common types, like "image/gif" and "text/plain", are registered in your browser. Note Not all browsers support MIME type associations. Example: Restricting file types This CFFILE specification will only save an image file that is in the GIF format: <CFFILE ACTION="Upload"...
  • Page 250: Windows

    Developing Web Applications with ColdFusion You enter permissions values in the MODE attribute for each type of user: owner, group, other in that order. For example to assign read permissions for all: MODE=444 To give a file or directory owner read/write/execute permissions and read only permissions for everyone else: MODE=744 Windows...
  • Page 251 Chapter 14: Managing Files on the Server The following file upload status variables are available after an upload. File Upload Variables Parameter Description AttemptedServerFile Initial name ColdFusion used attempting to save a file, for example, . See "Resolving conflicting file myfile.txt names"...
  • Page 252: Moving, Renaming, Copying, And Deleting Server Files

    Developing Web Applications with ColdFusion File Upload Variables (Continued) Parameter Description ServerFileExt Extension of the uploaded file on the server, without a period, for example, not. ServerFileName Filename, without an extension, of the uploaded file on the server. TimeCreated Time the uploaded file was created. TimeLastModified Date and time of the last modification to the uploaded file.
  • Page 253: Reading, Writing, And Appending To A Text File

    Chapter 14: Managing Files on the Server Reading, Writing, and Appending to a Text File In addition to managing files on the server, you can use CFFILE to read, create, and modify text files. This gives you the ability to Create log files.
  • Page 254 Developing Web Applications with ColdFusion To create a form in which to enter data for a text file: Open a new file in Studio. Modify the file so that it appears a follows: <HTML> <HEAD> <TITLE>Put Information into a Text File</TITLE> </HEAD>...
  • Page 255: Performing Directory Operations

    Chapter 14: Managing Files on the Server Performing Directory Operations Use the CFDIRECTORY tag to return file information from a specified directory and to create, delete, and rename directories. As with CFFILE, ColdFusion administrators can disable CFDIRECTORY processing in the ColdFusion Administrator Tags page. See the CFML Language Reference for details on the syntax of this tag.
  • Page 256 Developing Web Applications with ColdFusion <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 line so that it points to a DIRECTORY="c:\inetpub\wwwroot\mine" directory on your server. Save the file as and view it in your browser. directoryinfo.cfm...
  • Page 257 H A P T E R Interacting with Remote Servers Chapter 15 This chapter describes how ColdFusion wraps the complexity of Hypertext Transfer Protocol communications in a simplified tag syntax that allows you to easily extend your site’s offerings across the Web. Contents Using CFHTTP to Interact with the Web ............
  • Page 258: Using Cfhttp To Interact With The Web

    Developing Web Applications with ColdFusion Using CFHTTP to Interact with the Web The CFHTTP tag is one of the more powerful tags in the CFML tag set. You can use one of two methods to interact with a remote server using the CFHTTP tag: Get or Post. The Get method is a one-way transaction in which CFHTTP retrieves an object.
  • Page 259 Chapter 15: Interacting with Remote Servers Code Review Code Description <CFHTTP METHOD="Get" Get the page specified in the URL="http://www.allaire.com/index.cfm" URL and make the links RESOLVEURL="Yes"> absolute instead of relative.. <CFOUTPUT> Display the page, which is #CFHTTP.FileContent# <BR> stored in the variable </CFOUTPUT>...
  • Page 260: Creating A Query From A Text File

    Developing Web Applications with ColdFusion <CFHTTP METHOD="Get" URL="http://maximus/downloads/quakestuff/q2_test.zip" PATH="c:\quake2\install" FILE="quake2beta.zip"> <CFOUTPUT> #CFHTTP.MimeType# </CFOUTPUT> Change the URL to point to a binary file you want to download. Change the path to point to a path on your hard drive. Save the file as under your Web root directory and view savebinary.cfm myapps...
  • Page 261 Chapter 15: Interacting with Remote Servers When duplicate column heading names are encountered, ColdFusion adds an underscore character to the duplicate column name to make it unique. For example, if two CustomerID columns are found, the second is renamed "CustomerID_". To create a query from a text file: Create a new file in Studio.
  • Page 262: Using The Cfhttp Post Method

    Developing Web Applications with ColdFusion Using the CFHTTP Post Method Use the Post method to send cookie, form field, CGI, URL, and file variables to a specified ColdFusion page or CGI program. For Post operations, you must use the CFHTTPPARAM tag for each variable you want to post. Unlike the Get method, Post passes data to a specified ColdFusion page or to some executable that interprets the variables being sent and returns data.
  • Page 263 Chapter 15: Interacting with Remote Servers You have POSTed to me.<BR> <CFFILE DESTINATION="c:\temp\junk" NAMECONFLICT="Overwrite" FILEFIELD="myfile" ACTION="Upload" ATTRIBUTES="Normal"> <CFOUTPUT> The URL variable is: #url.myurl# <BR> The Cookie variable is: #cookie.mycookie6# <BR> The CGI variable is: #cgi.mycgi#. <BR> The Formfield variable is: #form.myformfield#. <BR> </CFOUTPUT>...
  • Page 264: Using Secure Sockets Layer (Ssl) With Cfhttp

    Developing Web Applications with ColdFusion This example runs a CGI program, , that searches the site and returns the search.exe hits on the value specified in VALUE. Using Secure Sockets Layer (SSL) with CFHTTP When using Secure Sockets Layer (SSL) to transmit secured transactions via CFHTTP , you need to be aware of limitations on its use caused by a bug in one of the components of Microsoft’s InetSDK.
  • Page 265: Performing File Operations With Cfftp

    Chapter 15: Interacting with Remote Servers Performing File Operations with CFFTP The CFFTP tag allows you to perform tasks on remote servers via the File Transfer Protocol (FTP). CFFTP allows you to cache connections for batch file transfers. Note In order to use CFFTP, make sure CFOBJECT is enabled on the Basic Security page of the ColdFusion Administrator.
  • Page 266: Caching Connections Across Multiple Pages

    Developing Web Applications with ColdFusion <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="Date(Format#lastmodified#)"> <CFCOL HEADER="<B>IsDirectory</B>" TEXT="#isdirectory#"> </CFTABLE> Change to the name of a server you have permission to FTP to. beta.company.com Change to a valid username and password. betauser monroe To establish an anonymous connection enter "anonymous"...
  • Page 267: Connection Caching Actions And Attributes

    Chapter 15: Interacting with Remote Servers Connection caching actions and attributes The following table shows which CFFTP attributes are required for CFFTP actions when employing connection caching. If connection caching is not used, the connection attributes USERNAME, PASSWORD, and SERVER must be specified. CFFTP Required Attributes by Action Action Attributes...
  • Page 268: An Overview Of Distributed Data For The Web

    Developing Web Applications with ColdFusion The best source of information about WDDX is http://www.wddx.org/. This site, sponsored by Allaire Corporation, offers a free download of the WDDX SDK and a number of resources, including a WDDX FAQ and a developer forum. An Overview of Distributed Data for the Web Web Distributed Data Exchange (WDDX) is an Extensible Markup Language (XML) vocabulary for describing complex data structures such as arrays, associative arrays,...
  • Page 269: Working With Application-Level Data

    Chapter 15: Interacting with Remote Servers descriptors that allow the data to be manipulated on a target system between arbitrary application servers. WDDX is based on XML, which is a W3C Recommendation. Other W3C efforts now in the works will have obvious application to WDDX when they are completed, most importantly, the XML-Schema proposal.
  • Page 270: How Wddx Works

    Developing Web Applications with ColdFusion All of Allaire’s WDDX serializers (CFML, COM, and JS) have an attribute/property that specifies whether time zone information should be used in the useTimezoneInfo serialization process. The default value is true. In the CFML implementation, is a property of the CFWDDX useTimezoneInfo Action=Cfml2WDDX tag.
  • Page 271: Converting Cfml Data To A Javascript Object

    Chapter 15: Interacting with Remote Servers Comparison of JavaScript object and deserialized XML JavaScript CFML x = new Object(); x = structNew(); x.a = "Property a"; x.a = "Property a"; x.b = "Property b"; x.b = "Property b"; See the CFML Language Reference for more information on JavaScript objects. Converting CFML Data to a JavaScript Object The following example demonstrates the transfer of a CFQUERY result set from a CFML template executing on the server to a JavaScript object that is processed by the...
  • Page 272: Transferring Data From Browser To Server

    Developing Web Applications with ColdFusion <!--- Dump the recordset ---> q.dump(true); </SCRIPT> Note To see how CFWDDX Action="cfml2js" works, view the source to the page. Transferring Data From Browser to Server This example serializes form field data, posts it to the server, deserializes it, and outputs the data.
  • Page 273 Chapter 15: Interacting with Remote Servers </SCRIPT> <!--- Data collection form ---> <FORM ACTION="wddx_browser_2_server.cfm" METHOD="post" NAME="personForm"> <!--- Input fields ---> Personal information<p> First name: <INPUT TYPE=text NAME=firstName><BR> Last name: <INPUT TYPE=text NAME=lastName><BR> <P> <!--- Navigation & submission bar ---> <INPUT TYPE="button" BALUE="Next" onclick="doNext()"> <INPUT TYPE="button"...
  • Page 274 Developing Web Applications with ColdFusion...
  • Page 275 H A P T E R Connecting to LDAP Directories Chapter 16 Support for the Lightweight Directory Access Protocol (LDAP) API in CFML is part of Allaire’s commitment to open networking standards. Contents What is LDAP? ....................250 ColdFusion Support for LDAP............... 252 Working with LDAP Directories ..............
  • Page 276: What Is Ldap

    Developing Web Applications with ColdFusion What is LDAP? LDAP (Lightweight Directory Access Protocol) is a protocol that enables organizations to arrange directory information in a hierarchy. Note that in this case, "directory" refers to a collection of information something like a telephone directory, not a collection of files in a folder on a disk drive.
  • Page 277: Ldap Attributes

    Chapter 16: Connecting to LDAP Directories LDAP attributes Following is a list of the common attributes: Common LDAP Attributes Attribute Name country state or province locality organization organizational unit common name surname Key Terms Following is a brief description of the LDAP information structure. Entry The basic information object of LDAP is the entry.
  • Page 278: Coldfusion Support For Ldap

    Developing Web Applications with ColdFusion attribute is "ou=support, o=allaire" the level below "support" is searched. You can optionally restrict a query to the level of the Start entry or extend it to the entire subtree. Referral While not supported directly in the LDAP2 standard, the ability of an LDAP server to refer a client query to another server is an attractive feature and has been implemented in the Netscape and University of Michigan servers.
  • Page 279: Working With Ldap Directories

    Chapter 16: Connecting to LDAP Directories Build applications that incorporate data from directory queries in their processes. Working with LDAP Directories The CFLDAP tag allows you to work with LDAP directories in the following ways. You can: View the directory schema Search an LDAP directory Process the results of querying an LDAP directory (OUTPUT) Viewing the Directory Schema...
  • Page 280: Querying An Ldap Directory

    Developing Web Applications with ColdFusion ATTRIBUTES="dn, objectclasses, attributetypes" SCOPE="BASE" FILTER="objectclass=*" START=#EntryList.subschemasubentry# > <CFOUTPUT QUERY="EntryList2"> DN=#dn#<BR> objectClasses: #objectclasses#<BR><BR><BR> attribute Types: #attributetypes#<BR><BR> </CFOUTPUT> </BODY> </HTML> Change the SERVER from to a valid LDAP server. testldap.company.com Save the template as under your Web root directory and testldap.cfm myapps view it in your browser.
  • Page 281 Chapter 16: Connecting to LDAP Directories CFLDAP Filter Operators (Continued) Operator Example o=alla* - organization names starting with "alla" o=*aire - organization names ending with "aire" o=all*aire - organization names starting with "all and " ending with "aire" & (&(o=allaire)(co=usa)) - organization name = "allaire" AND country = "usa"...
  • Page 282: Updating An Ldap Directory

    Developing Web Applications with ColdFusion <CFFORM NAME="GridForm" ACTION="org_query.cfm"> <CFGRID NAME="grid_one" QUERY="OrgList" HEIGHT=250 WIDTH=620 HSPACE=20 VSPACE="6"> <CFGRIDCOLUMN NAME="o" HEADER="Organization" WIDTH=380> <CFGRIDCOLUMN NAME="st" HEADER="State" WIDTH=100> <CFGRIDCOLUMN NAME="telephoneNumber" HEADER="Phone ##" WIDTH=150> </CFGRID> </CFFORM> </BODY> </HTML> Save the page as and view it in your browser. ldapadd.cfm Updating an LDAP Directory Entries can be added, modified, and deleted.
  • Page 283 Chapter 16: Connecting to LDAP Directories <!--- query the LDAP server ---> <CFLDAP Name="AriusList" SERVER="myserver" ACTION="QUERY" ATTRIBUTES="cn,mail,telephonenumber" SCOPE="SUBTREE" FILTER="ou=Human Resources" SORT="cn ASC" START="o=airius.com"> <!--- generate a form page for query output ---> <H3> Human Resources Directory for Arius</H3> <CFFORM ACTION="ariusform_action.cfm"> <CFGRID NAME="ariusgrid"...
  • Page 284 Developing Web Applications with ColdFusion <!--- modify a record, preserving other existing attributes ---> <!--- You must include the existing attribute values plus the new one you want to add. In this case we are adding a unique member gfarmer to the Accounting Managers.
  • Page 285 Chapter 16: Connecting to LDAP Directories PASSWORD="testldap" ACTION="MODIFYDN" ATTRIBUTES=#new_dn# DN=#rename_dn#> <CFELSE> <CFIF IsDefined(dn)> <CFSET #UPDATE_ATTRS#=#mailtag# & #email# & ";" & #phonetag# & #Phone#> <CFLDAP Name="CustomerModify" SERVER="myserver" USERNAME="cn=Directory Manager, o=Ace Industry, c=US" PASSWORD="testldap" ACTION="MODIFY" ATTRIBUTES=#UPDATE_ATTRS# DN=#dn#> <CFELSE> <!--- If the insert parameter is sent then run this insert --->...
  • Page 286 Developing Web Applications with ColdFusion <!--- Use CFLDAP to retrieve the common name and distinguished name for all employees that have a surname that contains ens and a common name that is > K. Search starts in the country US and organization Ace Industry.--->...
  • Page 287: Creating Searchable Cfldap Output

    Chapter 16: Connecting to LDAP Directories Change the to a valid user id. Save the page as and view it in your browser. ldapchangeattr.cfm To delete an entry: Open a new file in Studio. Modify the file so that it appears as follows: <!--- If the delete parameter is sent then run this update --->...
  • Page 288 Developing Web Applications with ColdFusion...
  • Page 289 H A P T E R Application Security Chapter 17 ColdFusion 4.5 supports several levels of Advanced security. This chapter teaches you how to deploy user security, which is controlled by the ColdFusion developer and offers runtime security for ColdFusion applications. It also describes the Remote Development Services security feature, which authenticates developers accessing server resources through ColdFusion Studio before giving them access to protected resources.
  • Page 290: Coldfusion Security Features

    Developing Web Applications with ColdFusion ColdFusion Security Features ColdFusion Server Professional and Enterprise editions include Advanced Security features that provide scalable, granular security for building and deploying your ColdFusion applications: Application development — System administrators can control access to files, data sources and administration for each developer on your team.
  • Page 291: Overview Of User Security

    Chapter 17: Application Security Overview of User Security User security authenticates users when they log into a ColdFusion application, and then assigns privileges based on group membership or other criteria that you determine. For example, suppose you’ve used ColdFusion to build and host your company’s intranet.
  • Page 292: Using The Cfauthenticate Tag

    Developing Web Applications with ColdFusion Use the IsAuthenticated function to check if the current user is authenticated. Use the IsAuthorized function to check if the user is authorized to access resources. This function lets developers offer or deny access to protected resources based on a user’s authorization level, which is determined by already-established security contexts.
  • Page 293: Authentication And Authorization Functions

    Chapter 17: Application Security Example <CFAUTHENTICATE SECURITYCONTEXT="SecurityContextName" USERNAME=#userID# PASSWORD=#pwd#> If the user has not already been defined in the system, ColdFusion throws a SECURITY exception. You can either reject access to the resource or re-route the user to a login page.
  • Page 294: Catching Security Exceptions

    Developing Web Applications with ColdFusion IsAuthorized returns TRUE if the user is authorized to perform the specified action on the specified ColdFusion resource. IsAuthorized takes three parameters: IsAuthorized(ResourceType, ResourceName, [ResourceAction]) For example, to check whether the authenticated user is authorized to update a data source resource called orders, use this syntax: IsAuthorized("Datasource", "orders", "update") In this example, the IsAuthorized function returns TRUE if the user is authorized for...
  • Page 295: Using The Cfimpersonate Tag

    Chapter 17: Application Security a new user. <!--- This code is from an Application.cfm file ---> <CFTRY> <CFAUTHENTICATE SECURITYCONTEXT="Allaire" USERNAME=#user# PASSWORD=#pwd#> <CFCATCH TYPE="Security"> <!--- The message to display ---> <H3>Authentication error</H3> <CFOUTPUT> <--- Display the message. Alternatively, you might place code here to define the user to the security context.
  • Page 296: Example Of User Authentication And Authorization

    Developing Web Applications with ColdFusion USERNAME — The username of the user to impersonate. PASSWORD — The password of the user to impersonate. TYPE — Indicates the type of impersonation to implement, application-level or operating-system-level. Application-level impersonation lets you assume the rights assigned to a ColdFusion user by a specified security context.
  • Page 297: Authenticating Users In Application.cfm

    Chapter 17: Application Security If a user passes the authentication test, ColdFusion passes a cookie to carry the user’s authentication state to subsequent application pages governed by this page. Application.cfm Next, only authenticated users are able to access the requested application page, for selecting and updating customer orders in a database.
  • Page 298: Checking For Authentication And Authorization

    Developing Web Applications with ColdFusion <!--- Security error in login occurred, show login again ---> <H3>Invalid Login</H3> <CFSET showLogin = "Yes"> </CFCATCH> </CFTRY> <CFELSE> <!--- The login was not detected ---> <CFSET showLogin = "Yes"> </CFIF> <CFIF showLogin> <!--- Recreate the url used to call this template ---> <CFSET url = "#cgi.script_name#">...
  • Page 299 Chapter 17: Application Security Example: orders.cfm <!--- This example calls the IsAuthorized function. ---> <!--- First, check whether a form button was submitted ---> <CFIF IsDefined("form.btnUpdate")> <!--- Is user is authorized to update or select information from the Orders data source? ---> <CFIF ISAUTHORIZED("DataSource", "Orders", "update")>...
  • Page 300 Developing Web Applications with ColdFusion...
  • Page 301 H A P T E R Building Custom CFAPI Tags Chapter 18 For some applications, building executables to run with ColdFusion is the best solution. Perhaps the application requirements go beyond what is currently feasible in CFML. Or perhaps application performance can be improved for certain types of processing.
  • Page 302: What Are Cfx Tags

    Developing Web Applications with ColdFusion What Are CFX Tags? CFX tags are custom tags written against the ColdFusion Application Programming Interface. Generally, you create a CFX if you want to do something that’s not possible in CFML, or if you want to improve performance of a task in CFML that’s repetitive. Unlike CFML custom tags, CFXs are implemented as DLL files and can: Handle any number of custom attributes.
  • Page 303: Using The Tag Wizard To Create Cfxs In C

    Chapter 18: Building Custom CFAPI Tags Using the Tag Wizard to create CFXs in C++ On Windows NT, you can get a start in developing CFXs by using the ColdFusion Tag Wizard. To use the wizard, the CFXAPI Tag Development Kit must be installed (it is by default), and the setup routine must detect Microsoft Visual C++ on the system.
  • Page 304: Before You Begin Developing Cfx Tags In Java

    Developing Web Applications with ColdFusion On UNIX Solaris You can debug custom tags on UNIX using the dbx debugger. You should shut down ColdFusion using the stop script. Set the environment variables, including as they are set LD_LIBRARY_PATH CFHOME in the start script. You should then be able to run the cfserver executable under the dbx debugger and set break points in your CFX code.
  • Page 305: Setting Up Your Development Environment To Develop Cfxs In Java

    Chapter 18: Building Custom CFAPI Tags - Generates a "Hello World!" graphic in JPEG format. HelloWorldGraphic Demonstrates how to dynamically create and return graphics from a Java CFX. Setting Up Your Development Environment to Develop CFXs in Java You can use a wide range of Java development environments to build Java CFXs, including the Java Development Kit which you can download from Sun at http://www.javasoft.com/products/jdk/1.2/index.html Although you can use just the basic JDK, it is highly recommended that you use one of...
  • Page 306: Processing Requests

    Developing Web Applications with ColdFusion To create a Java CFX: Create a new source file in your editor. Enter the code, for example, the code below illustrates the creation of a very simple Java CFX named that writes a text string back to the calling SimpleJavaCFX page: import com.allaire.cfx.* ;...
  • Page 307 Chapter 18: Building Custom CFAPI Tags Request Object Passed to the method of the interface. Provides methods processRequest CustomTag for retrieving attributes passed to the tag, including queries, and reading global tag settings. Methods Used by Request Object Method Description attributeExists Checks if the attribute was passed to this tag getAttribute...
  • Page 308: Java Cfx Class Loading

    Developing Web Applications with ColdFusion Query Object Provides an interface for working with ColdFusion queries, including methods for retrieving name, row count, and column names as well as methods for getting and setting data elements.. Methods Used by Query Object Method Description getName...
  • Page 309: Automatic Class Reloading

    Chapter 18: Building Custom CFAPI Tags Automatic Class Reloading You can determine how the server treats changed Java CFX class files by using the (?) . The allowable values for the attribute are as follows:. RELOAD RELOAD Allowable Values of RELOAD Attribute Value Description Automatically reload Java CFX and dependent classes within the...
  • Page 310: Calling The Cfx From A Coldfusion Template

    Developing Web Applications with ColdFusion your object. If you wish to store data and/or objects that are accessible to all CustomTag instances of your you should use static data members. CustomTag Calling the CFX from a ColdFusion Template You call Java CFXs from within ColdFusion templates by using the name of the CFX. The following CFML template calls the custom tag: HelloColdFusion...
  • Page 311 Chapter 18: Building Custom CFAPI Tags The Java implementation of is as follows: ZipBrowser 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 312: Approaches To Debugging Java Cfxs

    Developing Web Applications with ColdFusion Approaches to Debugging Java CFXs Java CFXs are not standalone applications that run in their own process like typical Java applications. Rather, they are created and invoked from an existing process — ColdFusion Server. This makes debugging Java CFXs more difficult because it is not possible to use an interactive debugger to debug Java classes that have been loaded by another process.
  • Page 313 Chapter 18: Building Custom CFAPI Tags — An implementation of the interface that enables DebugResponse Response you to print the results of a request once it has completed. — An implementation of the interface that enables you to DebugQuery Query initialize a query with a name, columns, and a data set.
  • Page 314: Debugging Classes Reference

    Developing Web Applications with ColdFusion DebugQuery query = new DebugQuery( "Employees", columns, data ) ; // create tag, process debug request, and print results OutputQuery tag = new OutputQuery() ; DebugRequest request = new DebugRequest( attributes, query ) ; DebugResponse response = new DebugResponse() ; tag.processRequest( request, response ) ;...
  • Page 315: Java Customization And Configuration

    Chapter 18: Building Custom CFAPI Tags DebugQuery // initialize a query with name and columns public DebugQuery( String name, String[] columns ) throws IllegalArgumentException ; // initialize a query with name, columns, and data public DebugQuery( String name, String[] columns, String[][] data ) throws IllegalArgumentException ;...
  • Page 316 Developing Web Applications with ColdFusion To register a C++ CFX: In the CF Administrator, open the Extensions > CFX Tags page. Enter in the Tag name and, optionally, a description. CFX_MyNewTag Select the type of tag (either C++ or Java). Click Add to open the New CFX Tag page.
  • Page 317: Distribution

    Chapter 18: Building Custom CFAPI Tags Distribution If you are distributing a custom tag, you may want to automatically register the custom tag during the setup process by writing the registration entries directly into the Registry. The location, key, and value names to write are as follows: Registration Entries for C++ CFXs Entry Value...
  • Page 318 Developing Web Applications with ColdFusion To import a C++ custom tag: Export the custom tag’s registry entry by using the Regedit utility. This creates a file similar to the following: REGEDIT4 [HKEY_LOCAL_MACHINE\SOFTWARE\Allaire\ColdFusion\CurrentVersion\ CustomTags\CFX_TEST] "LibraryPath"="C:\\cfusion\\cfx\\CFX_TEST\\test.dll" "ProcedureName"="ProcessTagRequest" "Description"="Sample CFX tag." "CacheLibrary"="1" In the install script, import the registry entry by including the following command in the install script: regedit importfilename To import a Java custom tag:...
  • Page 319: C++ Cfx Reference

    Chapter 18: Building Custom CFAPI Tags C++ CFX Reference Below is a listing of CFXAPI classes and members. Individual members are described fully in the following sections. Class Members CCFXException Class CCFXException::GetError CCFXException::GetDiagnostics CCFXQuery Class CCFXQuery::AddRow CCFXQuery::GetColumns CCFXQuery::GetData CCFXQuery::GetName CCFXQuery::GetRowCount CCFXQuery::SetData CCFXQuery::SetQueryString CCFXQuery::SetTotalTime...
  • Page 320: Ccfxexception Class

    Developing Web Applications with ColdFusion CCFXException Class Abstract class that represents an exception thrown during the processing of a ColdFusion Extension (CFX) procedure. Exceptions of this type can be thrown by CCFXRequest Class, CCFXQuery Class, and CCFXStringSet Class. Your ColdFusion Extension code must therefore be written to handle exceptions of this type.
  • Page 321: Ccfxquery Class

    Chapter 18: Building Custom CFAPI Tags pRequest->ReThrowException( e ) ; // Catch ALL other exceptions and throw them as // Cold Fusion exceptions (DO NOT REMOVE! -- // this prevents the server from crashing in // case of an unexpected exception) catch( ...
  • Page 322: Ccfxquery::addrow

    Developing Web Applications with ColdFusion CCFXQuery::AddRow int CCFXQuery::AddRow(void) Add a new row to the query. You should call this function each time you want to append a row to the query. Returns the index of the row that was appended to the query. Example The following example demonstrates the addition of 2 rows to a query that has 3 columns (’City’, ’State’, and ’Zip’):...
  • Page 323: Ccfxquery::getdata

    Chapter 18: Building Custom CFAPI Tags CCFXQuery::GetData iRow iColumn LPCSTR CCFXQuery::GetData(int , int Retrieves a data element from a row and column of the query. Row and column indexes begin with 1. You can determine the number of rows in the query by calling CCFXQuery::GetRowCount.
  • Page 324: Ccfxquery::setdata

    Developing Web Applications with ColdFusion Retrieves the number of rows in the query. Returns the number of rows contained in the query. Example The following example retrieves the number of rows in a query and writes it back to the user: CCFXQuery* pQuery = pRequest->GetQuery() ;...
  • Page 325: Ccfxquery::setquerystring

    Chapter 18: Building Custom CFAPI Tags CCFXQuery::SetQueryString This is a deprecated function and should not be used. CCFXQuery::SetTotalTime This is a deprecated function and should not be used. CCFXRequest Class Abstract class that represents a request made to a ColdFusion Extension (CFX). An instance of this class is passed to the main function of your extension DLL.
  • Page 326: Ccfxrequest::addquery

    Developing Web Applications with ColdFusion virtual void WriteDebug( LPCSTR lpszOutput ) CCFXRequest::WriteDebug writes text output into the debug stream. virtual CCFXStringSet* CreateStringSet() CCFXRequest::CreateStringSet allocates and returns a new CCFXStringSet instance. virtual void ThrowException( LPCSTR lpszError, LPCSTR lpszDiagnostics ) CCFXRequest::ThrowException throws an exception and ends processing of this request.
  • Page 327: Ccfxrequest::attributeexists

    Chapter 18: Building Custom CFAPI Tags // Create a query that contains these columns CCFXQuery* pQuery = pRequest->AddQuery( "People", pColumns ) ; // Add data to the query int iRow ; iRow = pQuery->AddRow() ; pQuery->SetData( iRow, iFirstName, "John" ) ; pQuery->SetData( iRow, iLastName, "Smith"...
  • Page 328: Ccfxrequest::debug

    Developing Web Applications with ColdFusion CCFXRequest::Debug BOOL CCFXRequest::Debug(void) Checks whether the tag contains the attribute. You should use this function to DEBUG determine whether or not you need to write debug information for this request. (See CCFXRequest::WriteDebug tag for details on writing debug information.) Returns if the tag contains the attribute;...
  • Page 329: Ccfxrequest::getcustomdata

    Chapter 18: Building Custom CFAPI Tags You are not responsible for freeing the memory allocated for the returned string set (it will be freed automatically by ColdFusion after the request is completed). Example The following example retrieves the list of attributes and then iterates over the list, writing each attribute and its value back to the user.
  • Page 330: Ccfxrequest::getsetting

    Developing Web Applications with ColdFusion (created using the CFQUERY tag or another custom tag). The attribute is QUERY optional and should only be used by tags that need to process an existing data set. Returns an object of the CCFXQuery Class that represents the query that was passed to the tag.
  • Page 331: Ccfxrequest::setcustomdata

    Chapter 18: Building Custom CFAPI Tags your extension code and then either re-throw them (if they are of the CCFXException Class) or create and throw a new exception pointer using CCFXRequest::ThrowException. An existing CCFXException that has been caught. Example The following code demonstrates the correct way to handle exceptions in ColdFusion Extension DLL procedures: ...Code that could throw an exception...
  • Page 332: Ccfxrequest::setvariable

    Developing Web Applications with ColdFusion void ProcessTagRequest( CCFXRequest* pRequest ) MYTAGDATA tagData ; pRequest->SetCustomData( (LPVOID)&tagData ) ; ... remainder of procedure ... CCFXRequest::SetVariable void CCFXRequest::SetVariable(LPCSTR lpszName , LPCSTR lpszValue ) Sets a variable in the calling template. If the variable name specified already exists in the template, its value is replaced.
  • Page 333: Ccfxrequest::write

    Chapter 18: Building Custom CFAPI Tags CCFXRequest::ReThrowException to provide protection against resource leaks in extension code. lpszError Short identifier for error. lpszDiagnostics Error diagnostic information. Example The following example throws an exception indicating that an unexpected error occurred while processing the request: char buffError[512] ;...
  • Page 334: Ccfxstringset Class

    Developing Web Applications with ColdFusion Example The following example checks to see whether the DEBUG attribute is present, and if it is, it writes a brief debug message: if ( pRequest->Debug() ) pRequest->WriteDebug( "Top secret debug info" ) ; CCFXStringSet Class Abstract class that represents a set of ordered strings.
  • Page 335: Ccfxstringset::getcount

    Chapter 18: Building Custom CFAPI Tags CCFXStringSet::GetCount int CCFXStringSet::GetCount(void) Gets the number of strings contained in the string set. This value can be used along with CCFXStringSet::GetString to iterate over the strings in the set (when iterating, remember that the index values for strings in the list begin at 1). Returns the number of strings contained in the string set.
  • Page 336: Ccfxstringset::getstring

    Developing Web Applications with ColdFusion CCFXStringSet::GetString LPCSTR CCFXStringSet::GetString(int iIndex ) Retrieves the string located at the passed index (note that index values are 1-based). Returns the string located at the passed index. iIndex Index of string to retrieve. Example The following example demonstrates using along with GetString CCFXStringSet::GetCount...
  • Page 337: Java Cfx Reference

    Chapter 18: Building Custom CFAPI Tags Java CFX Reference Contents Interface CustomTag Interface Query Interface Request Interface Response Interface CustomTag public abstract interface CustomTag Interface for implementing custom tags. Classes that implement this interface can be specified in the CLASS attribute of the Java CFX tag.
  • Page 338: Interface Query

    Developing Web Applications with ColdFusion — Interface for generating response to request (output, variables, response queries, etc.) Throws: — If an unexpected error occurs while processing the request. Exception Interface Query public abstract interface Query Interface to a query used or created by a CustomTag. A query contains tabular data organized by named columns and rows Method Summary addRow()
  • Page 339 Chapter 18: Building Custom CFAPI Tags Returns: The name of the query. getRowCount public int getRowCount() Retrieves the number of rows in the query. The following example retrieves the number of rows in a query and writes it back to the user: Query query = request.getQuery() ;...
  • Page 340 Developing Web Applications with ColdFusion Retrieves a list of the column names contained in the query. The following example retrieves the array of columns and then iterates over the list, writing each column name back to the user: // Get the list of columns from the query String[] columns = query.getColumns() ;...
  • Page 341 Chapter 18: Building Custom CFAPI Tags Throws: - If an invalid index is passed to the method. IndexOutOfBoundsException See Also: setData, addRow addRow public int addRow() Adds a new row to the query. Call this method each time you want to append a row to the query.
  • Page 342: Interface Request

    Developing Web Applications with ColdFusion int iCity = 1, iState = 2, iZip = 3 ; // First row int iRow = query.addRow() ; query.setData( iRow, iCity, "Minneapolis" ) ; query.setData( iRow, iState, "MN" ) ; query.setData( iRow, iZip, "55345" ) ; // Second row iRow = query.addRow() ;...
  • Page 343: Method Detail

    Chapter 18: Building Custom CFAPI Tags Method Summary String getAttributeList() Retrieves a list of all attributes passed to the tag. getIntAttribute(String name) Retrieves the value of the passed attribute as an integer. getIntAttribute(String name, int def) Retrieves the value of the passed attribute as an integer (returns default if the attribute does not exist or is...
  • Page 344 Developing Web Applications with ColdFusion getAttribute public String getAttribute(String name) Retrieves the value of the passed attribute. Returns an empty string if the attribute does not exist (use attributeExists to test whether an attribute was passed to the tag). Use getAttribute(String,String) to return a default value rather than an empty string.
  • Page 345 Chapter 18: Building Custom CFAPI Tags Throws: — If the attribute is not a valid number. NumberFormatException See Also: attributeExists, getAttributeList, getIntAttribute(String,int) getAttributeList public String[] getAttributeList() Retrieves a list of all attributes passed to the tag. To retrieve the value of an individual attribute you should use the getAttribute member function.
  • Page 346 Developing Web Applications with ColdFusion "order for this tag to work correctly." ) ; Returns: The Query that was passed to the tag. If no query was passed to the tag then null is returned. getSetting public String getSetting(String name) Retrieves the value of a global custom tag setting.
  • Page 347: Interface Response

    Chapter 18: Building Custom CFAPI Tags Returns: Returns true if the tag contains the DEBUG attribute otherwise returns false. See Also: Response.writeDebug Interface Response public abstract interface Response Interface to response generated from a CustomTag. This interface includes methods for writing output, generating queries, and setting variables within the calling page.
  • Page 348 Developing Web Applications with ColdFusion Sets a variable in the calling template. If the variable name specified already exists in the template then its value is replaced. If it does not already exist then a new variable is created. For example, this code sets the value of a variable named ’MessageSent’ based on the success of an operation performed by the custom tag: boolean bMessageSent ;...
  • Page 349 Chapter 18: Building Custom CFAPI Tags query.setData( iRow, iFirstName, "John" ) ; query.setData( iRow, iLastName, "Smith" ) ; iRow = query.addRow() ; query.setData( iRow, iFirstName, "Jane" ) ; query.setData( iRow, iLastName, "Doe" ) ; Parameters: — The name of the query to add to the template name —...
  • Page 350 Developing Web Applications with ColdFusion...
  • Page 351 H A P T E R Using CFOBJECT to Invoke Chapter 19 Component Objects The CFOBJECT tag is used to invoke objects created by component technologies. This includes COM/DCOM, CORBA, Java, and EJB objects. Contents Component Object Overview................ 326 Invoking Component Objects ............... 327 Getting Started with COM/DCOM..............
  • Page 352: Component Object Overview

    Developing Web Applications with ColdFusion Component Object Overview This section gives you some basic information on objects supported in ColdFusion and provides resources for further inquiry. About COM COM (Component Object Model) is a specification and a set of services defined by Microsoft to enable component portability, reusability, and versioning.
  • Page 353: Invoking Component Objects

    Chapter 19: Using CFOBJECT to Invoke Component Objects Invoking Component Objects The CFOBJECT tag is used to create an instance of the object and other ColdFusion tags, such as CFSET and CFOUTPUT, are used to invoke properties (attributes), and methods (operations) on the object. An object created by CFOBJECT or returned by other objects is implicitly released at the end of the template execution.
  • Page 354: Calling Nested Objects

    Developing Web Applications with ColdFusion Calling nested objects The current release of ColdFusion does not support nested (scoped) object calls. For example, if an object method returns another object and you would like to invoke a property/method on that object, the following is required: <CFSET objX = myObj.X>...
  • Page 355: Finding The Component Progid And Methods

    Chapter 19: Using CFOBJECT to Invoke Component Objects deployed with their own setup programs that register objects automatically, while others may require manual registration. Inproc object servers (*.dll, *.ocx) can be registered manually by using the "regsvr32.exe" utility using the following form: regsvr32 c:\path\servername.dll Local servers (*.exe) are typically registered either by simply starting them or specifying a command line parameters like:...
  • Page 356 Developing Web Applications with ColdFusion To view an object’s properties: Open the Object Viewer and scroll to the object you want to examine. Select and expand the object in the Object Viewer. Right-click the object to view it. If you view the TypeInfo, you’ll see the object’s methods and properties.
  • Page 357: Creating And Using Com Objects

    Chapter 19: Using CFOBJECT to Invoke Component Objects Creating and Using COM Objects In the following example, an SMTP mail handling component is created using CFOBJECT. <CFOBJECT ACTION=CREATE NAME=MAILER CLASS=SMTP.Mailer> The component needs to be created by ColdFusion before any methods in the component can be invoked or properties assigned in your application pages.
  • Page 358: Setting Properties And Invoking Methods

    Developing Web Applications with ColdFusion REMOTE — This is also an Out-of-Process server object (also typically an EXE) that is running remotely on the network. Using REMOTE implies using the SERVER attribute to identify where the object resides. Setting properties and invoking methods The following example, using the sample SMTPMailer COM object, shows how to assign properties to the mail message you want to send and how to execute component methods to handle mail messages.
  • Page 359: Calling A Corba Object

    Chapter 19: Using CFOBJECT to Invoke Component Objects If VisiBroker is already installed on the server, the log directory is the directory pointed to by the environment variable. VBROKER_ADM If this is a new VisiBroker installation, the log directory is created on the root of the drive from which ColdFusion Server is started.
  • Page 360: Exception Handling

    Developing Web Applications with ColdFusion short s; long l; float d; struct NestedStruct SimpleStruct f; char c; string s; typedef sequence<long, 5> BLongSequence; interface SomeObject { short SomeMethod( in NestedStruct inStruct, in BlongSequence inSeq); The applicable ColdFusion code <!—Declare a couple of structures -‡ <CFSET x = StructNew()>...
  • Page 361: Calling Java Objects

    Chapter 19: Using CFOBJECT to Invoke Component Objects Calling Java Objects The CFOBJECT tag can call any Java class that’s available on the Class Path specified in the ColdFusion Administrator. For example: <CFOBJECT Type="Java" Class="MyClass" Name = "myObj"> Although this loads the class, it doesn’t create an instance object. Static methods and fields are accessible after the call to CFOBJECT.
  • Page 362 Developing Web Applications with ColdFusion...
  • Page 363 H A P T E R Extending ColdFusion Pages Chapter 20 with CFML Scripting ColdFusion offers a server-side scripting language, CFScript, that provides ColdFusion functionality in script syntax. This JavaScript-like language gives developers the same control flow, but without tags. This chapter describes the CFScript language’s functionality and syntax.
  • Page 364: About Cfscript

    Developing Web Applications with ColdFusion About CFScript The ColdFusion server-side scripting language, CFScript, offers ColdFusion functionality in script syntax. This JavaScript-like language offers the same control flow, but without tags. CFScript regions are bounded by <CFSCRIPT> and </CFSCRIPT>. You can use ColdFusion expressions, but not CFML tags, inside a CFScript region.
  • Page 365: The Cfscript Language

    Chapter 20: Extending ColdFusion Pages with CFML Scripting break continue for-in switch-case For more information The following JavaScript references may be useful in understanding the concepts and control flow statements in CFScript: Netscape’s JavaScript Guide Netscape’s JavaScript Reference David Flanagan’s JavaScript: The Definitive Guide, published by O’Reilly & Associates, 1996, 1998, http://www.oreilly.com.
  • Page 366 Developing Web Applications with ColdFusion for loop: for (init-expr ; test-expr ; final-expr) statement ; Note that init-expr and final-expr 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) empty The test-expr can be one of the following: any ColdFusion expression, for example, A LT 5, loop LE x, or Y EQ "not found"...
  • Page 367 Chapter 20: Extending ColdFusion Pages with CFML Scripting do-while loop: do statement while (expr) ; // Complete do-while loop on a single line a = ArrayNew(1); do {a[loop1] = loop1 + 5; loop1 = loop1 + 1;} while (loop1 LT 10); // Multiline do-while loop a = ArrayNew(1);...
  • Page 368: Expressions

    Developing Web Applications with ColdFusion continue: skip to next loop iteration for ( loop=1; loop LT 10; loop = loop+1) if(a[loop]=0) continue; a[loop]=1; break: break out of the current switch statement or loop for( ; ; ) indx=indx+1; if(Find("key",strings[indx],1)) break; Expressions CFScript supports all CFML expressions.
  • Page 369: Reserved Words

    Chapter 20: Extending ColdFusion Pages with CFML Scripting CFScript is case-insensitive. All statements end in a semi-colon, and line breaks in your code are insignificant. In CFScript, assignments are statements, not expressions. Some implicit objects are not available, such as Window and Document. Note CFScript is not directly exportable to JavaScript.
  • Page 370 Developing Web Applications with ColdFusion <CFOUTPUT QUERY="employees"> <CFSCRIPT> //‘testres' is a column in the "employees" query if( testres EQ 1 ) result="positive"; else result="negative"; </CFSCRIPT> <!--- The variable result takes its value from the script region ---> Test for #name# is #result#. </CFOUTPUT>...
  • Page 371 H A P T E R Accessing the Windows NT Chapter 21 Registry The CFREGISTRY tag gives you programmatic access to the Windows Registry. Contents Overview of Registry Access in ColdFusion ..........346 Getting Registry Values .................. 346 Setting Registry Values................... 347 Deleting Registry Values ................
  • Page 372: Overview Of Registry Access In Coldfusion

    Developing Web Applications with ColdFusion Overview of Registry Access in ColdFusion ColdFusion includes the CFREGISTRY tag, which allows you to get, set, and delete registry values. The registry is a database that Windows uses to maintain hierarchical information about users, hardware, and software. Under UNIX, ColdFusion includes functionality that emulates the registry.
  • Page 373: Chapter 21: Accessing The Windows Nt Registry

    Chapter 21: Accessing the Windows NT Registry <CFREGISTRY ACTION="GetAll" BRANCH="HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM" TYPE="Any" NAME="RegQuery"> Access the record set (this example uses the CFTABLE tag): <H1>CFREGISTRY ACTION="GetAll"</H1> <CFTABLE QUERY="RegQuery" COLHEADERS HTMLTABLE BORDER="Yes"> <CFCOL HEADER="<B>Entry</B>" WIDTH="35" TEXT="#RegQuery.Entry#"> <CFCOL HEADER="<B>Type</B>" WIDTH="10" TEXT="#RegQuery.Type#"> <CFCOL HEADER="<B>Value</B>" WIDTH="35" TEXT="#RegQuery.Value#">...
  • Page 374: Deleting Registry Values

    Developing Web Applications with ColdFusion If the specified value does not exist, ColdFusion creates it. If the value already exists, ColdFusion updates the value data. To create a registry key: Call the CFREGISTRY tag with the SET action, specifying the branch, the entry to set, specifying KEY for the TYPE attribute: <CFREGISTRY ACTION="Set"...
  • Page 375: Index

    Index storing variables 196 C++ development environment 276 Arrays 104 Accessing 2-dimensional 104 Caching collections 181 3-dimensional 104 FTP connections 241 Action pages 34 adding data to 106 Catching security Active Server Pages 242 adding elements to 106, 107 exceptions 268 Advanced security associative 113 CCFXException class 294...
  • Page 376 Developing Web Applications with ColdFusion CFAUTHENTICATE tag 185, 266 CFWDDX tag 241 ColdFusion Markup Language See example 270 CFX tags 276 CFML syntax 266 CFXs 199, 276 ColdFusion Server 6 using SETCOOKIE 266 calling 284 configuring 6 CFCATCH tag 95 compiling 277 description of 7 CFCONTENT tag 239...
  • Page 377 Index descendants 77 custom pages and tags 93 Common Object Request Broker distributing 291 Java CFXs 286 Architecture 326 downloading 73 Declaring arrays 105 Component Object Model 326 encrypting 86 Default values Custom tags 276 executing 82 of variables 52 Lightweight Directory Access DELETE statement 2, 22 Protocol 250...
  • Page 378 Developing Web Applications with ColdFusion CFFORM 124 Java CFXs 289 querying directories 254 Form fields Importing scope 251 required 68 C++ CFXs 292 search filters 254 Form variables Java CFXs 292 updating directories 256 in queries 35 Indexing viewing directory schema 253 directories 150 LIKE operator 39 naming 34...
  • Page 379 Index relational 173 records returned 27 Search interfaces score 177 Querying building 159 searching 171 LDAP directories 254 Search modifiers 179 SQL 23 Quotes Searching OR operator 23 using 21, 51 collections 150 file types 151 ORDER BY clause 22 full-text 150 RDN (Relative Distinguished international languages 152...
  • Page 380 Developing Web Applications with ColdFusion application-level 184 Text testing for existence 51 Shared data displaying 12 types of 13 modifying 199 Text control 31 Verity 150 Single quotes 21, 51 Text files Viewing directory schema, LDAP 253 in form field values 49 column headings 234 creating queries from 234 using 21...

This manual is also suitable for:

Coldfusion 4.5

Table of Contents