Page 2
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 Macromedia, Incorporated. Macromedia, Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear in this book.
Page 11
Using Query Expressions ..........285 Simple query expressions .
Page 12
Contents Evaluating the Results of a File Upload ........324 Moving, Renaming, Copying, and Deleting Server Files .
Page 13
xiii Authenticating users in Application.cfm ......363 Checking for authentication and authorization ..... 365 Chapter 20 Using cfobject to Invoke Component Objects Component Object Overview .
CFML Reference for details about various tags and functions. Contents Intended Audience....................xvi New Features ......................xvi Developer Resources....................xvii About ColdFusion Documentation ..............xviii Getting Answers ......................xx Contacting Macromedia....................xx...
About This Book Intended Audience Developing ColdFusion Applications is intended for Web application programmers who are learning ColdFusion orwish to extended their ColdFusion programming knowledge. It provides a solid grouding in the tools that ColdFusion provides to develop Web applications. The initial chapters provide e instructions for creating a basic ColdFusion application and are intended for those who are new to ColdFusion.
Cisco CSS 11000. Enhanced COM support Experience easier integration with COM components. Developer Resources Macromedia, Inc. is committed to setting the standard for customer support in developer education, technical support, and professional services. The Web site is...
About This Book designed to give you quick access to the entire range of online resources, as the following table describes. Resource Description Macromedia Web General information about Macromedia www.macromedia.com/ site products and services Information on Detailed product information on www.coldfusion.com/products/coldfusion/...
About ColdFusion Documentation Printed and online documentation set The ColdFusion documentation set consists of the following titles. Book Description Installing and Describes system installation and basic configuration for Configuring Windows NT, Windows 2000, Solaris, Linux, and HP-UX ColdFusion Server Advanced Describes how to connect your data sources to the ColdFusion ColdFusion Server Server, configure security for your applications, and how to use...
San Francisco, CA 4103 Tel: 415.252.2000 Fax: 415.626.0554 Web: www.macromedia.com Technical Macromedia offers a range of telephone and Web-based support options. Go to http://www.coldfusion.com/ support support/ for a complete description of technical support services. You can make postings to the ColdFusion Support Forum (http://forums.coldfusion.com/DevConf/index.cfm) at...
Chapter 1 Introduction to ColdFusion 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....................2 Before You Begin ......................3 What is ColdFusion?....................
Chapter 1 Introduction to ColdFusion A Quick Web Overview Over the last few years, the Web 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 e-commerce to managing internal business processes.
Before You Begin Before You Begin Before you begin using ColdFusion to create your Web applications, you should be familiar with HTML, relational database design and management, and Structured Query Language (SQL). HTML You will find that ColdFusion tags (CFML) are similar in syntax to HTML tags, yet, unlike HTML, they enable you to create dynamic Web pages.
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.
ColdFusion Features and Components ColdFusion Features and Components ColdFusion provides a comprehensive set of features and components for developing and managing your Web applications. Using the ColdFusion components, you can enhance the speed and ease of development, dynamically deploy your applications, integrate new and legacy technologies, and build secure applications.
Support for existing Web server authentication, security, and encryption For detailed information about security, see Advanced ColdFusion Administration. For the latest publications from Macromedia on security, visit the Security Zone at http://www.coldfusion.com/developer/securityzone/. For a complete feature list and more detailed information, see the ColdFusion product pages at http://www.coldfusion.com/coldfusion.
Page 27
ColdFusion Features and Components data input and format data output. They can contain ColdFusion (CFML) tags, HTML tags, CFScript, JavaScript, and anything else that you can normally embed in an ordinary HTML page. You can easily access data sources, such as relational databases, from your application pages.
Chapter 1 Introduction to ColdFusion How ColdFusion Server Works Regardless of which ColdFusion Server you have installed, ColdFusion application pages are processed on the server at runtime, each time they are requested by a browser. A page request happens when you click a Web site link to open a Web page in your browser.
Chapter 2 Writing Your First ColdFusion 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 Working with ColdFusion Application Pages............10 Working with Variables .....................
Chapter 2 Writing Your First ColdFusion Application 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.
Working with ColdFusion Application Pages <!--- Set all variables ---> <cfset department="Sales"> <!--- Display results ---> <cfoutput> I’d like to talk to someone in #Department#. </cfoutput> </body> </html> 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.
Page 32
Chapter 2 Writing Your First ColdFusion Application 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 is returned to the browser. Original ColdFusion page HTML file returned by Web server <html>...
Working with Variables Working with 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 you can use in applications. As with other programming languages, you set variables in ColdFusion to store data that you want to access later.
Page 34
Chapter 2 Writing Your First ColdFusion Application you can write: I’d like to talk to someone in #Variables.Department#. Some variable scopes, such as the local scope, do not require the scope identifier prefix, while others do. However, it is good programming practice to use prefixes for most or all scopes.
Working with Variables CFML code Results <cfoutput> ColdFusion replaces the variable I’d like to talk to someone in Department with its value. The HTML page #Department#. displays: </cfoutput> I’d like to talk to someone in Sales. <cfoutput> ColdFusion sees Reverse(Department) as The department name spelled text and displays it unchanged.
Chapter 2 Writing Your First ColdFusion Application View the page in your Web browser by entering the following URL: http://127.0.0.1/myapps/calldept.cfm. Development Considerations The same development rules that apply for any programming environment apply to ColdFusion. You should also follow the same programming conventions that you would with any other language: Comment your code as you go.
Chapter 3 Querying a Database 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 tag to query a data source, and use the tag to output the query cfquery...
Chapter 3 Querying a Database 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—as your users interact with pages in their browsers.
Understanding Database Basics Understanding Database Basics You do not need a thorough knowledge of databases to develop a data-driven ColdFusion application, but you need to know some basic concepts and techniques. A database is a structure for storing information. Databases are organized in tables, which are collections of related items.
Chapter 3 Querying a Database Database design guidelines From this basic description, a few database design rules emerge: Each record should contain a unique identifier, known as the primary key. This can be an employee ID, a part number, or a customer number. The primary key is typically the column used to maintain each record’s unique identity among the tables in a relational database.
Accessing Data Sources Borland dBase-compliant databases Microsoft Excel worksheet data ranges Borland Paradox Databases Informix databases Progress databases Oracle 8 databases Centura SQLBase databases Sybase ASE databases Delimited text files You can also use any additional ODBC drivers that are installed on your system. On UNIX, look in the ODBC page of the ColdFusion Administrator for a list of available ODBC drivers.
Chapter 3 Querying a Database Adding data sources You use the ColdFusion Administrator to add data sources to the ColdFusion Administrator. When you add a data source, you assign it a name so that you can reference it within tags such as on application pages to query databases.
Page 43
Accessing Data Sources Name the data source CompanyInfo On Windows Select Microsoft Access Driver (*.mdb) from the drop-down box to describe the ODBC driver. On UNIX, select the Merant Dbase/FoxPro driver. Click Add. In the Database File field, enter the full path of the database. (You can also use the Browse button to locate the file.).
Chapter 3 Querying a Database Adding data source notes and considerations When adding data sources to ColdFusion Server, keep these guidelines in mind: Data source names should be all one word and begin with a letter. Data source names can contain only letters, numbers, and the underscore. Data source names should not contain special characters.
Retrieving Data Retrieving Data You can query databases to retrieve data at runtime. The retrieved data, called the result set, is stored on that page as a query object. When retrieving data from a database, perform the following tasks: Use the tag on a page to tell ColdFusion how to connect to a database.
Chapter 3 Querying a Database When referencing text literals in SQL, use single quotes (’). For example, Select selects every record from mytable in * from mytable WHERE FirstName=’Russ’ which the first name is Russ. Writing SQL In between the begin and end tags, write the SQL that you want the cfquery database to execute.
Writing SQL Statement clauses Use the following keywords to refine SQL statements: Keyword Description FROM Names the data tables for the operation WHERE Sets one or more conditions for the operation ORDER BY Sorts the result set in the specified order GROUP BY Groups the result set by the specified select list items Operators...
Chapter 3 Querying a Database Some DBMS vendors use nonstandard SQL syntax (known as a dialect) in their products. ColdFusion does not validate the SQL in a , so you are free to cfquery use any syntax that is supported by your data source. Check your DBMS documentation for nonstandard SQL usage.
Building Queries Reviewing the code The query you just created retrieves data from the CompanyInfo database. The following table describes the code and its function: Code Description <cfquery name="EmpList" Queries the database specified in the datasource="CompanyInfo"> CompanyInfo data source SELECT FirstName, LastName, Gets information from the FirstName, Salary, Contract LastName, Salary, and Contract fields in...
Chapter 3 Querying a Database Outputting Query Data After you define a query on a page, you can use the tag with the cfoutput query attribute to specify the query object that contains the data you want to output to a page.
Outputting Query Data You now display the results of the query on the page. The following table describes the code and its function: Code Description <cfoutput query="EmpList"> Display information retrieved in the EmpList query. Display information for each record in the query, until you run out of records.
Chapter 3 Querying a Database Getting Information About Query Results Each time you query a database with the tag, you get not only the data itself, cfquery but also query properties, as described in the following table: Property Description RecordCount The total number of records returned by the query.
Getting Information About Query Results You now display the number of records retrieved in the query. The following table describes the code and its function: Code Description <cfoutput> Display what follows The query returned Display the text “The query returned” #EmpList.RecordCount# Display the number of records retrieved in the EmpList query...
Chapter 3 Querying a Database Using Query Results in Queries ColdFusion allows you to use the results of a previous query in any tag that cfquery returns row data to ColdFusion. You can query a database once and use the results in several dependent queries.
Using Query Results in Queries Boolean predicates: Aggregate functions: LIKE Count([DISTINCT][*] expr) NOT LIKE Sum([DISTINCT] expr) Avg([DISTINCT] expr) NOT IN Max(expr) BETWEEN Min(expr) NOT BETWEEN You cannot nest aggregate functions. Comparison operators: <= >= < > <> You can also do the following tasks: Use the results of one or two queries in your SQL statement.
Page 56
Chapter 3 Querying a Database To use the results of a query in a query: Create a new application page in ColdFusion Studio. Edit the page so that it appears as follows: <html> <head> <title>Using Query Results in a Query</title> </head>...
Page 57
Using Query Results in Queries Reviewing the code The page retrieves the entire Employee table from the CompanyInfo database. A second query selects only the three columns to display for employees with the specified last name. The following table describes the code and its function: Code Description cfset ListNameSearch = "Jones"...
Chapter 4 Retrieving and Formatting Data 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. Contents Using Forms to Specify the Data to Retrieve............
Chapter 4 Retrieving and Formatting Data Using Forms to Specify the Data to Retrieve In the examples in previous chapters, you have retrieved all of the records from a table. However, there are many instances when you want to retrieve data based on certain criteria.
Using Forms to Specify the Data to Retrieve <form name="getReportCriteria" action="runReport.cfm?RequestTimeout=120" method="post"> Form controls Within the form, you describe the form controls needed to gather and submit user input. There are a variety of form controls types available. You choose form control input types based on the type of input the user should provide.
Page 62
Chapter 4 Retrieving and Formatting Data Control Code <input type="Reset" name="ControlName" value="DisplayName"> Reset button <input type="Submit" name="ControlName" Submit button value="DisplayName"> Use the following procedure to create a sample form. To create a form Create a new application page, using ColdFusion Studio. Edit the page so that it appears as follows: <html>...
Page 63
Using Forms to Specify the Data to Retrieve <!-- check box --> <p> Contractor? <input type="checkbox" name="Contractor" value="Yes" checked>Yes </p> <!-- 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 formpage.cfm within the myapps directory under your Web root directory.
Chapter 4 Retrieving and Formatting Data Code Description <select name="City"> Create a drop-down list box named City <option value="Arlington"> and populate it with the values Arlington “Arlington,” “Boston,” “Cambridge,” <option value="Boston">Boston “Minneapolis,” and “Seattle.” <option value="Cambridge"> Cambridge <option value="Minneapolis"> Minneapolis <option value="Seattle">Seattle </select>...
Working with Action Pages Working with Action Pages A ColdFusion action page is just like any other application page except that you can use the form variables that are passed to it from an associated form. The following sections describe how to create effective action pages. Processing form variables on action pages The action page gets a form variable for every form control that contains a value when the form is submitted.
Chapter 4 Retrieving and Formatting Data However, instead of putting the LastName directly in the SQL WHERE clause, you can use the text that the user entered in the form for comparison: <cfquery name="GetEmployees" datasource="CompanyInfo"> SELECT FirstName, LastName, Salary FROM Employee WHERE LastName="#Form.LastName#"...
Working with Action Pages This time an error occurs because the check box does not pass a variable to the action page. Reviewing the code The following table describes the highlighted code and its function: Code Description <cfquery name="GetEmployees" Query the data source CompanyInfo and datasource="CompanyInfo">...
Chapter 4 Retrieving and Formatting Data The argument passed to the IsDefined function must always be enclosed in double quotes. For more information on the IsDefined function, see the CFML Reference. If you attempt to evaluate a variable that you did not define, ColdFusion cannot process the page and displays an error message.
Working with Queries and Data Working with Queries and Data The ability to generate and display query data is one of the most important and flexible features of ColdFusion. The following sections further your understanding of using queries and displaying their results. Some of these tools are effective for presenting any data, not just query results.
Chapter 4 Retrieving and Formatting Data </body> </html> Save the page as actionpage.cfm within the myapps directory. View formpage.cfm in your browser. Enter Smith in the Last Name text box and submit the form. The records that match the criteria specified in the form appear in a table. Reviewing the code The following table describes the highlighted code and its function: Code...
Working with Queries and Data 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. This technique is known as pattern matching and is often used to query databases.
Chapter 4 Retrieving and Formatting Data Creating table joins Many times, the data that you want to retrieve is maintained in multiple tables. For example, in the database that you are working with: Department information is maintained in the Departmt table. This includes department ID numbers.
Page 73
Working with Queries and Data The following action page allows users to search for employees by department, last name, or both. To build a more flexible search interface: Open the page ctionpage.cfm in ColdFusion Studio. Modify the page so that it appears as follows: <html>...
Page 74
Chapter 4 Retrieving and Formatting Data Reviewing the code The following table describes the highlighted code and its function: Code Description SELECT Departmt.Dept_Name, Retrieve the fields listed from the Employee.FirstName, Departmt and Employee tables, joining Employee.LastName, the tables based on the Dept_ID field in Employee.StartDate, each table.
Returning Results to the User Returning Results to the User When you return your results to the user, you must make sure that your pages respond to the user’s needs and are appropriate for the type and amount of information. In particular you must consider the following situations: When there are no query results When you want to return partial results If there are no query results...
Chapter 4 Retrieving and Formatting Data <cfif form.lastname is not ""> AND Employee.LastName = ’#Form.LastName#’ </cfif> </cfquery> <cfif GetEmployees.recordcount is "0"> No records match your search criteria. <br> Please go back to the form and try again. <cfelse> <h4>Employee Data Based on Criteria from Form</h4> <table>...
Page 77
Returning Results to the User When you flush data, make sure that a sufficient amount of information is available, because some browsers might not respond if you flush only a very small amount. Similarly, if you use an attribute, set it for a reasonable size, such as a few interval hundred bytes or more but not many thousands of bytes.
Page 78
Chapter 4 Retrieving and Formatting Data Reviewing the code The following table describes the code and its function: Code Description <H2>We are sure you will agree it was Send the HTML header and all HTML worth the short wait!</H2> output to the tag to the user.
It illustrates ways cfgraph that you can graph data and gives you the tools you need to create effective graphs. tag requires the JRun server and the Macromedia Generator server, cfgraph which install with ColdFusion. Contents Creating a Graph .......................
Chapter 5 Graphing Data Creating a Graph tag provides five graph types. A large number of attributes let you cfgraph customize the graph appearance to meet your needs. Graph types You can create the following types of graphs: Horizontal bar Line Area (a line graph with the area below the line filled in) The following illustrations show one sample of each type of graph:...
Creating a Graph Creating a basic graph You use the following attributes to create a basic graph: cfgraph Attribute Description type Must be one of the following values: , or horizontalbar . (An area graph is a kind of line graph.) line query The query containing the data.
Chapter 5 Graphing Data Graphing Data One of the most important considerations when you graph data is the way you supply the data to the tag. You can supply data in several ways: cfgraph Provide all the data in a single query. Specify individual data points using tags.
Page 83
Graphing Data Attribute Description (Optional) Works only with bar, horizontal bar, and pie charts in Flash file format. A static prefix for all data point URLs. When the user clicks a bar or pie wedge, the page links to a URL created by appending the data from the data point’s URLColumn value.
Page 84
Chapter 5 Graphing Data <!-- Generate a query with statistical data for each department. --> <cfquery dbtype = "query" name = "DeptSalaries"> SELECT Dept_Name, AVG(Salary) AS AvgByDept FROM GetSalaries GROUP BY Dept_Name </cfquery> <!--- Reformat the generated numbers to show only thousands ---> <cfloop index="i"...
Graphing Data Reviewing the code The following table describes the code and its function: Code Description <cfquery name="GetSalaries" Query the CompanyInfo database to datasource="CompanyInfo"> get the Dept_Name and Salary for SELECT Departmt.Dept_Name, each employee. Because the Employee.Salary Dept_Name is in the Departmt table FROM Departmt, Employee and the Salary is in the Employee WHERE Departmt.Dept_ID =...
Chapter 5 Graphing Data This pie chart displays the income values of four departments. Each cfgraph specifies a department’s income and the corresponding item description for the legend. The values are specified by individual ColdFusion variables. The title “Income by Department” appears above the chart. tag lets you specify the following information about a data point: cfgraphdata Attribute...
Controlling Graph Appearance Controlling Graph Appearance tag allows you to customize the appearance of your graph in many cfgraph ways. Common graph characteristics You can optionally specify the following characteristics on all types of graphs: Graph characteristic Attributes used Description Title title The title to display on the graph and the font to...
Chapter 5 Graphing Data Setting bar and horizontal bar chart characteristics You can specify the following additional characteristics for bar and horizontal bar charts: Graph characteristic Attributes used Description Value labels showValueLabel Labels that display the numeric value being valueLabelFont graphed.
Page 89
Controlling Graph Appearance Graph characteristic Attributes used Description Data point colorList A comma-separated list of colors to use for colors each bar. You can use any of the 256 standard Web colors and any valid Web color name notation (for example, blue or ##FF33CC). You must use double pound signs with hexadecimal color notation.
Page 90
Chapter 5 Graphing Data Return to your browser and enter the following URL to view graphdata.cfm: http://127.0.0.1/myapps/graphdata.cfm Reviewing the code The following table describes the highlighted code and its function: Code Description title = "Average Salary by Put a title above the graph. Department"...
Controlling Graph Appearance Setting pie chart characteristics You can specify the following additional characteristics for pie charts: Graph characteristic Attributes used Description Value labels showValueLabel Labels that display the numeric value being valueLabelFont graphed. valueLabelSize Value labels are on by default. You can turn valueLocation them off or have them display when the user points to the bar (Flash file format only).
Page 92
Chapter 5 Graphing Data Example: adding a pie chart The example in the following procedure adds a pie chart to the page. To create a pie chart: Open graphdata.cfm in ColdFusion Studio. Edit the DeptSalaries query and the code so that they appear as follows: cfloop <!--- A query to get statistical data for each department.
Page 93
Controlling Graph Appearance Reviewing the code The following table describes the highlighted code and its function: Code Description SUM(Salary) AS SumByDept, In the DeptSalaries query, add a SUM aggregation function to get the sum of all salaries per department. <cfset DeptSalaries.SumByDept[i]= In the , round the salary sums to cfloop...
Chapter 5 Graphing Data Setting line and area graph characteristics You can specify the following additional characteristics for line-based graphs Graph characteristic Attributes used Description Value axis scaleFrom The minimum and maximum points on the scaleTo vertical axis. By default the minimum is 0 and the maximum is the largest data value.
Page 95
Controlling Graph Appearance Edit the GetSalaries query so that it appears as follows: <!-- Get the raw data from the database. --> <cfquery name="GetSalaries" datasource="CompanyInfo"> SELECT Departmt.Dept_Name, Employee.StartDate, Employee.Salary FROM Departmt, Employee WHERE Departmt.Dept_ID = Employee.Dept_ID </cfquery> Add the following code before the tag: html <!--- Convert start date to start year.
Page 96
Chapter 5 Graphing Data Return to your browser and enter the following URL to view graphdata.cfm: http://127.0.0.1/myapps/graphdata.cfm Reviewing the code The following table describes the highlighted code and its function: Code Description Employee.StartDate, Add the employee start date to the data in the GetSalaries query.
Linking Dynamically from Graphs Linking Dynamically from Graphs You can make Flash-format bar and pie charts interactive so that ColdFusion displays a new data point–specific Web page when the user clicks a bar or pie wedge. ColdFusion provides two methods for specifying the destination page: For data points from queries, ColdFusion takes the value of the cfgraph URL attribute, appends the value of the query column specified by the...
Page 99
Linking Dynamically from Graphs Reviewing the code The following table describes the code and its function: Code Description <cfquery name="GetSalaryDetails" Get the salary data for the datasource="CompanyInfo"> department whose name SELECT was passed in the URL Departmt.Dept_Name, parameter string. Sort the Employee.FirstName, data by the employee’s last Employee.LastName,...
Page 100
Chapter 5 Graphing Data title="Total Salaries by Department" titleFont="Times" showValueLabel="rollover" valueLabelFont="Times" backgroundColor = "##CCFFFF" borderWidth = 0 colorlist="##6666FF,##66FF66,##FF6666,##66CCCC" LegendFont="Times"> </cfgraph> Save the page. Return to your browser and enter the following URL to view graphdata.cfm: http://127.0.0.1/myapps/graphdata.cfm. Click the slices of the pie chart. Reviewing the code The following table describes the highlighted code and its function: Code...
Chapter 6 Making Variables Dynamic This chapter explains how to use CFML to dynamically populate forms and dynamically generate SQL. It also discusses ways to make sure that variables exist and have valid data because this information is important to effectively use dynamic data.
Chapter 6 Making Variables Dynamic Dynamically Populating List Boxes In Chapter 4, you hard-coded a form’s list box options. Instead of manually entering the information on a form, you can dynamically populate a list box with database fields. When you code this way, the form page automatically reflects the changes that you make to the database.
Chapter 6 Making Variables Dynamic Creating Dynamic Check Boxes and Multiple-Selection List Boxes When an HTML form contains either a list of check boxes with the same name or a multiple-selection list box (that is, where users can select multiple items from the list), the user’s entries are made available as a comma-delimited list with the selected values.
Page 105
Creating Dynamic Check Boxes and Multiple-Selection List Boxes The user sees the name of the department, but the attribute of each check box value is a number that corresponds to the underlying database primary key for the department’s record. If the user checks the Marketing and Sales items, the value of the SelectedDept form field is "2,4"...
Chapter 6 Making Variables Dynamic Note In SQL, all strings must be surrounded in single quotes. The function ListQualify returns a list with the specified qualifying character (here, a single quote) around each item in the list. If you select the second and fourth check boxes in the form, the following statement gets sent to the database: SELECT * FROM Departmt...
Page 107
Creating Dynamic Check Boxes and Multiple-Selection List Boxes Searching string values Suppose you want the user to select departments from a multiple selection list box. The database search field is a string field. The query retrieves detailed information on the selected department(s): <select name="SelectDepts"...
Chapter 6 Making Variables Dynamic Ensuring that Variables Exist The sample code in the previous sections is incomplete. Either the form or the action page should make sure that the SelectDepts variable has a value before it is used in the SQL Select statement.
Ensuring that Variables Exist For example, the following series of tags indicates that this page expects two cfparam form variables named StartRow and RowsToFetch: <cfparam name="Form.StartRow"> <cfparam name="Form.RowsToFetch"> If the page with these tags is called without either one of the form variables, an error occurs and the page stops processing.
Chapter 6 Making Variables Dynamic Validating Data Types It is often not sufficient that input data merely exists; it must also have the right format. For example, a date field must have data in a date format. A salary field must have data in a numeric or currency format.
Validating Data Types If the variable is not in a valid date format, an error occurs and the page stops processing. Validating form field data types One limitation of standard HTML forms is that you cannot validate that users input the type or range of data you expect.
Page 112
Chapter 6 Making Variables Dynamic Using a single page for both the form and action provides the opportunity to illustrate the use of the function to check that data exists. This way, the IsDefined form does not show any results until you submit the input. To validate the data that users enter in the insert form: Create a new page in ColdFusion Studio.
Page 113
Validating Data Types </cfoutput> </cfif> </html> Save the file as datatest.cfm. View the file in your browser, omit a field or enter invalid data, and click the Submit button. When the user submits the form, ColdFusion scans the form fields to find any validation rules you specified.
Chapter 6 Making Variables Dynamic Code Description Salary: Create a text box called Salary in which <input type="text" users can enter their salary. Make it name="Salary" exactly ten characters wide. size="10" maxlength="10"><br> <cfif isdefined("Form.StartDate")> Output the values of the StartDate and <cfoutput>...
Page 115
Validating Data Types The following example shows the use of when valid input is given in cfqueryparam the Course_ID variable used as a query parameter. To see what happens when you use invalid data, substitute a text string such as “test” for the integer 12 in the cfset statement.
Chapter 6 Making Variables Dynamic Code Description WHERE Course_ID=<cfqueryparam Only select rows where the Course_ID value="#Course_ID#" column equals the value of Course_ID cfsqltype="CF_SQL_INTEGER"> CFML local variable. Validate that the </cfquery> variable value is an integer and, if appropriate for the database driver, use a bind parameter to associate the value with the SQL statement.
Page 117
Dynamic SQL Creating the input form First, you need to create an input form, which asks for information about several fields in the Employee table. To search for data based on only the fields the user enters in the form, you use statements in the SQL statement.
Page 118
Chapter 6 Making Variables Dynamic Creating the action page After you create the input form, you can create the action page to process the user’s request. This action page determines where the user entered search criteria and searches based only on those criteria. To create the action page: Create a new application page in ColdFusion Studio.
Page 119
Dynamic SQL <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. Verify that the results meet the criteria you specify. Reviewing the code The action page builds a SQL statement dynamically based on what the...
Page 120
Chapter 6 Making Variables Dynamic CFML Code Description <cfif isDefined("Form.Contract")> If the user selected the Contractor check Employee.Contract = ‘Yes' AND box, get data for the employees who are <cfelse> contractors; otherwise, get data for Employee.Contract = 'No' AND employees who are not contractors. The </cfif>...
Chapter 7 Updating Your Database This chapter describes how to insert, update, and delete data in a database with ColdFusion. Contents Inserting Data ......................102 Updating Data ......................106 Deleting Data......................112...
Chapter 7 Updating Your Database Inserting Data You usually use two application pages to insert data into a database: An insert form An insert action page You can create an insert form with standard HTML form tags or with tags (see cfform “Creating Forms with the cfform Tag”...
Inserting Data Save the file as insertform.cfm in the myapps directory. View insertform.cfm in a browser. Data entry form notes and considerations If you use the tag in the action page to insert the data into the database, cfinsert you should follow these rules for creating the form page: You only need to create HTML form fields for the database fields into which you want to insert data.
Page 124
Chapter 7 Updating Your Database </cfoutput> </body> </html> Save the page as insertaction.cfm. View insertform.cfm in a browser, enter values, and click the Submit button. The data is inserted into the Employee table and the message displays. Reviewing the code The following table describes the code and its function: Code Description...
Page 125
Inserting Data Creating an insert action page with cfquery For more complex inserts from a form submittal you can use a SQL INSERT statement in a tag instead of a tag. The SQL INSERT statement is cfquery cfinsert more flexible because you can insert information selectively or use functions within the statement.
Chapter 7 Updating Your Database Reviewing the code The following table describes the highlighted code and its function: Code Description <cfquery name="AddEmployee" Use a tag to insert a new row cfquery datasource="CompanyInfo"> into the Employee table of the INSERT INTO Employee CompanyInfo Database.
Page 127
Updating Data To create an update form: Create a new page in ColdFusion Studio. Edit the page so that it appears as follows: <cfquery name="GetRecordtoUpdate" datasource="CompanyInfo"> SELECT * FROM Employee WHERE Emp_ID = #URL.Emp_ID# </cfquery> <html> <head> <title>Update Form</title> </head> <body>...
Page 128
Chapter 7 Updating Your Database Reviewing the code The following table describes the code and its function: Code Description <cfquery name="GetRecordtoUpdate" Query the CompanyInfo data source datasource="CompanyInfo"> and return the records in which the SELECT * employee ID matches what was FROM Employee entered in the URL that called this WHERE Emp_ID = #URL.Emp_ID#...
Updating Data Creating an action page to update data You can create an action page to update data with either the tag or cfupdate cfquery with the UPDATE statement. Creating an update action page with cfupdate tag is the easiest way to handle simple updates from a front end form. cfupdate tag has an almost identical syntax to the tag.
Page 130
Chapter 7 Updating Your Database Reviewing the code The following table describes the code and its function: Code Description <cfif not If the user clears the Contractor check box, isdefined("Form.Contract")> no value gets passed to the action page. <cfset Form.contract = "No"> Also, the database field must have a value <cfelse>...
Page 131
Updating Data <h1>Employee Updated</h1> <cfoutput> You have updated the information for #Form.FirstName# #Form.LastName# in the Employees database. </cfoutput> Save the page. View updateform.cfm in a browser by specifying the page URL and an Employee ID, for example, http://localhost/myapps/updateform.cfm?Emp_ID=3. Enter new values in any of the fields, and click Submit. The data is updated into the Employee table and the message displays.
Chapter 7 Updating Your Database Deleting Data You use a tag with a SQL DELETE statement to delete data from a database. cfquery Deleting a single record To delete a single record, use the table’s primary key in the WHERE condition of a SQL DELETE statement.
Deleting Data View deleteform.cfm a browser by specifying the page URL and an Employee ID, for example, http://localhost/myapps/updateform.cfm?Emp_ID=3. and click the Submit button. The employee is deleted from the Employee table and the message displays. Reviewing the code The following table describes the code and its function: Code Description <cfquery name="DeleteEmployee"...
Chapter 8 Handling Complex Data 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. This chapter explains the basics of creating and working with structures.
Chapter 8 Handling Complex Data with Structures 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 two-dimensional (2D) array is like a simple table. In ColdFusion, you typically use arrays to temporarily store data.
Page 137
About Arrays ColdFusion dynamic 2D array A ColdFusion 2D array is actually a one-dimensional array that contains a series of additional 1D arrays. Each of the arrays that make up a row can expand and contract independently of any other column. The following terms will help you understand subsequent discussions of ColdFusion arrays: Array dimension The relative complexity of the array structure.
Chapter 8 Handling Complex Data with Structures Basic Array Techniques To use arrays in ColdFusion, as in other languages, you need to first declare the array, specifying its dimension. Once it is declared, you can add array elements, which you can then reference by index. As an example, suppose you declare a 1D array called "firstname": <cfset firstname=ArrayNew(1)>...
Basic Array Techniques Creating 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 140
Chapter 8 Handling Complex Data with Structures <!--- This example adds a 1D array to a 1D array ---> <!--- Declare two one-dimensional arrays for the first and last names ---> <cfset firstname=arraynew(1)> <cfset lastname=arraynew(1)> <!--- Assign first names directly to the firstname array ---> <cfset firstname[1]="Coleman">...
Populating Arrays with Data Populating Arrays with Data Array elements can store any values, including queries, structures, and other arrays. You can use a number of functions to populate an array with data, including , and . These functions are ArraySet ArrayAppend ArrayInsertAt...
Chapter 8 Handling Complex Data with Structures Using nested loops for 2D and 3D arrays To output values from 2D and 3D arrays, you must employ nested loops to return array data. With a 1D array, a single is sufficient to output data, as in the cfloop previous example.
Populating Arrays with Data 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. A looping structure is generally required to populate an array from a query. Query column data can be referenced using array-like syntax.
Chapter 8 Handling Complex Data with Structures Array Functions The following functions are available for creating, editing, and handling arrays: Function Description ArrayAppend Appends an array element to the end of a specified array. ArrayAvg Returns the average of the values in the specified array. ArrayClear Deletes all data in a specified array.
About Structures About Structures ColdFusion structures consist of key-value pairs. Structures let you build a collection of related variables that are grouped under a single name. You can define ColdFusion structures dynamically. You can use structures to refer to related values as a unit rather than individually. To maintain employee lists, for example, you can create a structure that holds personnel information such as name, address, phone number, ID numbers, and so on.
Chapter 8 Handling Complex Data with Structures Structure notation ColdFusion supports three types of notation for structures. Which notation you use depends on your needs: Notation Description Object.property Use to refer to values in a structure. You can refer to a property, prop, of an object, obj, as obj.prop.
Creating and Using Structures Creating and Using Structures This section explains how to use the structure functions to create and use structures in ColdFusion. The sample code in this section uses a structure called employee, which 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:...
Chapter 8 Handling Complex Data with Structures Updating values in structures You can update structure element values in a tag or a function. cfset SructUpdate Updating a structure with cfset You can use the tag to update structure values (but not keys). For example, the cfset following code uses and Object.property notation to change John’s...
Creating and Using Structures Getting information about structures To find out if a given value represents a structure, use the function: IsStruct IsStruct(variable) This function returns True if variable is a structure. Structures are not indexed numerically, so to find out how many name-value pairs exist in a structure, use the StructCount function, as in this example: StructCount(employee) To discover whether a specific Structure contains data, use the StructIsEmpty...
Chapter 8 Handling Complex Data with Structures Copying structures To copy a structure, use the function. This function takes the name of StructCopy the structure that you want to copy and returns a new structure with all the keys and values of the named structure.
Page 151
Creating and Using Structures <body> <h1>Add New Employees</h1> <!--- Action page code for the form at the bottom of this page ---> <!--- Establish parameters for first time through ---> <cfparam name="Form.firstname" default=""> <cfparam name="Form.lastname" default=""> <cfparam name="Form.email" default=""> <cfparam name="Form.phone" default=""> <cfparam name="Form.department"...
Chapter 8 Handling Complex Data with Structures <input type="Submit" value="OK"> </form> </body> </html> Example file addemployee.cfm <!--- This file is an example of a custom tag used to add employees. Employee information is passed through the employee structure (the empinfo attribute). For databases that do not support automatic key generation, you must also add the Emp_ID.
Structure Functions <table cellpadding="2" cellspacing="2"> <tr> <td><b>Employee</b></td> <td><b>Department</b></td> </tr> <!--- In cfloop, use item to create a variable 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 Use the following functions to create and manage structures in ColdFusion applications: Function...
Page 154
Chapter 8 Handling Complex Data with Structures Note that in all cases, except , an exception is thrown if the referenced StructDelete key or structure does not exist. For more information on these functions, see the CFML Reference.
Chapter 9 Building Dynamic Forms This chapter shows you how to use the tag to enrich your forms with cfform sophisticated graphical controls, including several Java applet-based controls. You can use these controls without writing a line of Java code. Contents Creating Forms with the cfform Tag ..............
Chapter 9 Building Dynamic Forms Creating Forms with the cfform Tag You already learned how to use HTML forms to gather user input (see “Using Forms to Specify the Data to Retrieve” on page 40). This chapter shows you how to use the tag to create dynamic forms in CFML.
Creating Forms with the cfform Tag cfform controls The following table describes the controls ColdFusion controls you use in forms created using cfform Control Description cfgrid A Java applet-based control that creates a data grid you can populate from a query or by defining the contents of individual cells. You can also use grids to insert, update, and delete records from a data source.
Chapter 9 Building Dynamic Forms Usage notes , the attribute causes the tree to expand the tree to the cftree preservedata previously selected element. For this to work correctly, you must also set the attribute to True. completePath attribute has no effect on .
Input Validation with cfform Controls Input Validation with cfform Controls tags include the attributes which allows you cfinput cftextinput validate to specify a valid data entry type for the control. You can validate user entries on the following data types. Data type Description Date...
Chapter 9 Building Dynamic Forms Validating with regular expressions You can use regular expressions to match and validate the text that users enter in tags. Ordinary characters are combined with special cfinput cftextinput characters to define the match pattern. The validation succeeds only if the user input matches the pattern.
Page 161
Input Validation with cfform Controls If the first character of a set of characters in bracket is the caret (^), the expression matches any character except those in the set. It does not match the empty string. For example: [^akm] matches any character except "a", "k", or "m". The caret loses its special meaning if it is not the first character of the set.
Page 162
Chapter 9 Building Dynamic Forms A one-character regular expression or grouped subexpression followed by a plus (+) matches one or more occurrences of the regular expression. For example, [a-z]+ matches one or more lowercase characters. A one-character regular expression or grouped subexpression followed by a question mark (?) matches zero or one occurrences of the regular expression.
Page 163
Input Validation with cfform Controls Expression examples The following examples show some regular expressions and describe what they match: Expression Description [\?&]value= Any string containing a URL parameter value. ^[A-Z]:(\\[A-Z0-9_]+)+$ An uppercase DOS/Windows directory path that is not the root of a drive and has only letters, numbers, and underscores in its text.
Chapter 9 Building Dynamic Forms Input Validation with JavaScript In addition to native ColdFusion input validation using the attribute of the validate tags, the following tags support the attribute, cfinput cftextinput onvalidate which allows you to specify a JavaScript function to handle your input cfform validation:...
Page 165
Input Validation with JavaScript To use JavaScript to validate form data: Create a new file in ColdFusion 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 (’@’, 1) == -1 || Ctrl.value.indexOf (’.’, 3) == -1) return (false);...
Page 166
Chapter 9 Building Dynamic Forms Reviewing the code The following table describes the highlight code and its function: Code Description <script> JavaScript code to test for valid <!-- entry in the text box. The if function testbox(form) { statement checks to making Ctrl = Form.inputbox1;...
Building Tree Controls with cftree Building Tree Controls with cftree form lets you display hierarchical information in a space-saving cftree collapsible tree populated from data source queries. To build a tree control with , you use individual tags to populate the control. You can specify cftree cftreeitem one of six built-in icons to represent individual items in the tree control, or supply a...
Chapter 9 Building Dynamic Forms Grouping output from a query In a query that you display using a control, you might want to organize your cftree employees by the department. In this case, you separate column names with commas in the attribute.
Building Tree Controls with cftree Reviewing the code The following table describes the highlight code and its function: Code Description ORDER BY Dept_ID Order the query results by department. Populate the tree with the Department ID, and under <cftreeitem value="Dept_ID, FullName"...
Chapter 9 Building Dynamic Forms Structuring Tree Controls Tree controls built with can be very complex. Knowing how to specify the cftree relationship between multiple entries will help you handle even the cftreeitem most complex of constructs. cftree Example: one-level tree control This example consists of a single root and a number of individual items: <cfquery name="deptquery"...
Creating Data Grids with cfgrid Specifying the tree item in the URL When a user clicks on a tree item to link to a URL the variable, which cftreeItemKey identifies the selected value, is appended to the URL in the form: http://myserver.com?cftreeitemkey =selected_value Automatically passing the name of the selected tree item as part of the URL makes it easy to implement a basic "drill down"...
Chapter 9 Building Dynamic Forms Populating a grid from a query To populate a grid from a query: Open a new file named in ColdFusion Studio. grid1.cfm Edit the file so that it appears as follows: <cfquery name="empdata" datasource="CompanyInfo"> SELECT * FROM Employee </cfquery>...
Creating an Updateable Grid Note If you specify a tag with a attribute defined and no corresponding cfgrid query attributes the grid contains all the columns in the query. cfgriditem Creating an Updateable Grid You can build grids to allow users to edit data within them. Users can edit individual cell data, as well as insert, update, or delete rows.
Chapter 9 Building Dynamic Forms Controlling cell contents attributes let cfgridcolumn type value valuesDisplay, valuesDelimiter you control the data that a user can enter into a cell in the following ways: cfgrid By default, a cell is an editable text field. Use the attribute to require numeric or string data, to make the fields check type...
Creating an Updateable Grid The value of change_index increments for each row that changes, and does not indicate the specific row number. When the user updates data or inserts or deletes rows, the action page gets one array for each changed column, plus the RowStatsus.Action array.
Page 178
Chapter 9 Building Dynamic Forms To make the grid editable: Open the file in ColdFusion Studio. grid1.cfm Edit the file so that it appears as follows: <cfquery name="empdata" datasource="CompanyInfo"> SELECT * FROM Employee </cfquery> <cfform name="GridForm" action="handle_grid.cfm"> <cfgrid name="employee_grid" height=300 width=250 vspace=10 selectmode="edit"...
Creating an Updateable Grid Reviewing the code The following table describes the code and its function: Code Description <cfgrid name="employee_grid" Populate a control with data from the cfgrid height=300 empdata query. Selecting a grid cell enables you width=250 to edit it. Rows can be inserted and deleted. The vspace=10 grid is 300 X 250 pixels and has 10 pixels of selectmode="edit"...
Chapter 9 Building Dynamic Forms To update the data source with cfgridupdate Open a new file in ColdFusion Studio. Modify the file so that it appears as follows: <cfgridupdate grid="Employee_grid" datasource="CompanyInfo" tablename="Employee"> Save the file as handle_grid.cfm View in your browser, make changes to the grid, and then submit grid2.cfm them.
Page 181
Creating an Updateable Grid <br> </cfoutput> <cfif Form.employee_grid.rowstatus.action[counter] is "D"> <cfquery name="DeleteExistingEmployee" datasource="CompanyInfo"> DELETE FROM Employee WHERE Emp_ID=#Form.employee_grid.original.Emp_ID [Counter]# </cfquery> <cfelseif Form.employee_grid.rowstatus.action[counter] is "U"> <cfquery name="UpdateExistingEmployee" datasource="CompanyInfo"> UPDATE Employee LastName=’#Form.employee_grid.LastName[Counter]#’, Dept_ID=#Form.employee_grid.Dept_ID[Counter]# WHERE Emp_ID=#Form.employee_grid.original.Emp_ID [Counter]# </cfquery> <cfelseif Form.employee_grid.rowstatus.action[counter] is "I"> <cfquery name="InsertNewEmployee" datasource="CompanyInfo">...
Page 182
Chapter 9 Building Dynamic Forms Reviewing the code The following table describes the code and its function: Code Description <cfif isdefined If there is an array of edit types, then the ("Form.employee_grid.rowstatus.action")> table needs changing. Otherwise, do <cfloop index = "Counter" from = "1" to = nothing.
Page 183
Creating an Updateable Grid Code Description <cfelseif Otherwise, if the action is to insert a row, Form.employee_grid.rowstatus.action[counter] is generate a SQL INSERT query to insert "I"> the Employee’s last name and department ID from the grid row into the database. The <cfquery name="InsertNewEmployee"...
Chapter 9 Building Dynamic Forms Building Slider Bar Controls You can use the control to create a slider control and define a wide range of cfslider formatting options for slider label text, label font name, size, boldface, italics, and color, as well as slider scale increments, range, positioning, tick marks, and behavior. Slider bars are useful because they are highly visual and users cannot enter invalid values.
Building Text Entry Boxes Building Text Entry Boxes tag is similar to the HTML =text tag. With cftextinput input cftextinput however, you can also specify font and alignment options, as well as enable input validation methods using either a JavaScript or the attribute.
Chapter 9 Building Dynamic Forms Building Drop-Down List Boxes The drop-down list box that you can create with is similar to the HTML cfselect tag. However, gives you more control over user inputs, provides select cfselect error handling, and, most importantly, allows you to automatically populate the selection list from a query.
Embedding Java Applets Embedding Java Applets tag allows you to embed Java applets in a . To use cfapplet cfform cfapplet you must first register your Java applet using the ColdFusion Administrator Java Applets page (under Extensions on the Server tab). In the Administrator, you define the interface to the applet, encapsulating it so that each invocation of the cfapplet tag is very simple.
Page 188
Chapter 9 Building Dynamic Forms Applet registration fields The following table explains the applet registration fields: Field Description Codebase Enter the base URL of the applet: the directory that contains the applet components. The applet class files must be located within the Web browser root directory. Example: http://servername/classes Code...
Embedding Java Applets Using cfapplet to embed an applet After you register an applet, you can use the tag to place the applet in a cfapplet ColdFusion page. The tag has two required attributes: cfapplet appletsource . Since you registered the applet, and you defined each applet parameter with a name default value, you can invoke the applet with a very simple form of the tag:...
Page 190
Chapter 9 Building Dynamic Forms To reference a Java applet return value in your application page: Specify the name of the method in the Add/Registered Java Applet page of the ColdFusion Administrator. Specify the method name in the attribute of the tag when you name cfapplet...
Chapter 10 Reusing Code This chapter describes how to reuse common code with , and create cfinclude custom CFML tags that encapsulate common code. Contents Ways to Reuse Code ....................172 Reusing Common Code with cfinclude..............172 Using Custom Tags....................173 Nesting Custom Tags....................
Chapter 10 Reusing Code Ways to Reuse Code ColdFusion provides several different ways to reuse code. These ways include the following techniques: If you are using ColdFusion Studio, you can write code snippets, which you can copy into pages. You use the tag to include a ColdFusion page in another page.
Using Custom Tags Include the header.cfm file in this page: <cfinclude template="header.cfm"> View askemp.cfm in a browser, then submit the form so that you display getemp.cfm. The header should appear on both pages. Note The file header.cfm must be in the same directory where you saved askemp.cfm and getemp.cfm (or a subdirectory).
Chapter 10 Reusing Code Using existing custom tags Before creating a custom tag in CFML, you should review the Custom Tag section of the ColdFusion Developer Exchange. Tags are grouped in several broad categories and are downloadable as freeware, shareware, or commercial software. You can quickly view each tag’s syntax and usage information.
Using Custom Tags Custom tag pages also have access to system data structure called . The thisTag structure contains information about the tag and its execution thisTag environment. The variable is described in “Executing Custom Tags,” on thisTag page 185. Using tag attributes Custom tag attribute values are passed from the calling page to the custom tag page as name-value pairs.
Chapter 10 Reusing Code Passing values to and from custom tags Because custom tags are individual ColdFusion pages, variables and other data are not automatically shared between a custom tag and the calling page. To pass data from the calling page to the custom tag, specify attribute name-value pairs in the custom tag, just as you do for normal HTML and CFML tags.
Using Custom Tags Passing custom tag attributes via CFML structures You can use the reserved attribute to pass attributes to attributecollection custom tags. must reference a structure that contains the Attributecollection attribute names as the keys and the attribute values as the values. You can freely mix with other attributes when you call a custom tag.
Chapter 10 Reusing Code Custom tag example In this example, we create a custom tag that uses an attribute that is passed to it to set the value of a variable called Doctor on the calling page. To create a custom tag: Create a new application page (the calling page) in ColdFusion Studio.
Page 199
Using Custom Tags Reviewing the code The following table describes the code and its function: Code Description <cfset NameYouEntered="Smith"> In the calling page, create a variable NameYouEntered and assign it the value "Smith." <cfoutput> In the calling page, display the value of the Before you leave this page, NameYouEntered variable before calling you’re...
Chapter 10 Reusing Code Nesting Custom Tags A custom tag can call other custom tags, thereby nesting tags. ColdFusion uses nested tags such as , and cfgraph cfgraphdata cfhttp cfhttppam cftree . The ability to nest tags allows you to provide similar functionality. cftreeitem The calling tag is known as an ancestor, parent, or base tag, while the tags that ancestor tags call are known as descendant, child, or sub tags.
Passing Data Between Nested Custom Tags 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 while encapsulating each tag’s implementation so that others cannot see it. When you decide to you use nested tags, you must address the following issues: What data should be accessible? Which tags can communicate to which tags?
Page 202
Chapter 10 Reusing Code tag has the following format: cfassociate <cfassociate baseTag="tagName" dataCollection="collectionName" attribute is the name of the base tag that gets access to this tag’s baseTag attributes. The attribute is the name of the structure in which the dataCollection base tag stores the sub-tag data.
Page 203
Passing Data Between Nested Custom Tags name. By default, the closest ancestor is returned. If there is no ancestor by the given name or if the ancestor does not expose any data (such as CFIF), an exception is thrown. Example: Ancestor data access This example creates two custom tags and a simple page that calls each of the custom tags.
Page 204
Chapter 10 Reusing Code <!--- output all the contents of the stack a line at a time ---> <cfloop index="loopcount" from="1" to=#listlen(ancestorlist)#> Ancestorlist entry #loopcount# n is #ListGetAt(ancestorlist,loopcount)#<br> </cfloop><br> </cfoutput> <!--- Determine whether you’re nested inside a loop ---> <cfset inloop = listfindnocase(ancestorlist,’cfloop’)> <cfif inloop neq 0>...
Executing Custom Tags Executing Custom Tags The following sections provide information on executing custom tags. Tag instance data When a custom tag page executes, ColdFusion keeps data related to the tag instance. built in structured variable preserves this data with a unique identifier. thisTag The behavior is similar to the tag-specific variable (sometimes called the File...
Chapter 10 Reusing Code A custom tag page that performs processing in both modes can have the following format: <cfif thisTag.ExecutionMode is ’start’> <!--- Start tag processing ---> <cfelse> <!--- End tag processing ---> </CFIF> You can also use cfswitch <cfswitch expression=#thisTag.ExecutionMode#>...
Installing Custom Tags Access to generated content Custom tags can access and modify the generated content of any of its instances using the variable. In this context, the term generated thisTag.GeneratedContent content means the results of processing the body of a given tag. This includes all text and HTML code in the body, the results of evaluating ColdFusion variables, expressions, and functions, and the results generated by descendant tags.
Chapter 10 Reusing Code Managing Custom Tags If you deploy custom tags in a multideveloper environment or distribute your tags publicly, you can use additional ColdFusion capabilities: An advanced invocation syntax to resolve possible name conflicts Advanced security Template encoding Resolving filename conflicts To avoid errors caused by duplicate custom tag filenames, use the tag in...
Managing Custom Tags Encoding custom tags You can use the command-line utility to encode any ColdFusion cfencode application page. By default, the utility is installed in the /cfusion/bin directory. It is especially useful for securing custom tag code before distributing it. tag uses the following syntax: cfencode cfencode infile outfile [/r /q] [/h "message"] /v"2"...
Chapter 11 Preventing and Handling Errors ColdFusion includes many tools and techniques for ensuring that your code works properly. These tools include sophisticated debugging and code validation tools, error logging tools, and error handling mechanisms. This chapter describes these tools and presents approaches to troubleshooting common problems. ColdFusion Studio also provides interfaces for debugging application pages and for dynamically validating multiple levels of HTML and CFML code.
Chapter 11 Preventing and Handling Errors Debug Settings in the ColdFusion Administrator ColdFusion can provide important debugging information for every application page requested by a browser. When you enable debugging, the output displays in a block following normal page output. For detailed information on the debugging and logging settings in the ColdFusion Administrator, see Advanced ColdFusion Administration.
Page 213
Debug Settings in the ColdFusion Administrator ColdFusion returns the following information: Database errors, including the ODBC error code, the extended error message returned from the ODBC driver, the name of the data source, and the SQL statement submitted to the database Syntax error, including the line of the application page file on which the error occurred System-related errors, such as out of memory conditions, or file or disk access...
The CFML Syntax Checker Runtime validation The ColdFusion Application Server features two modes of attribute checking for processing application pages: strict and relaxed. Macromedia recommends that you always use the strictest possible level of CFML validation. To enable strict validation: Open the ColdFusion Administrator Server Settings page.
Troubleshooting Common Problems Troubleshooting Common Problems The following section describes a few common problems that you might encounter and ways to resolve them. ODBC data source configuration Problem: ODBC driver manager cannot make a connection to the database. Connection errors include problems with the location of files, network connections, and database client library configuration.
Page 216
Chapter 11 Preventing and Handling Errors Problem: Invalid attribute or value. If you use an invalid attribute or attribute values, ColdFusion returns an error message. To prevent such syntax errors, use the ColdFusion syntax validation tools in ColdFusion Studio. Problem: Mismatched quotes and escape characters. Check strings in attributes and expressions for proper placement of single and double quotes.
Error Handling in ColdFusion Error Handling in ColdFusion By default, ColdFusion generates its own error messages when it encounters errors. In addition, it provides a variety of tools and techniques for you to customize error information and handle errors when they occur, including the following techniques: You can specify custom pages for ColdFusion to display when a ColdFusion page is missing or if it encounters an exception error during the processing of a page (the Site-wide Error Handling page).
Page 218
Chapter 11 Preventing and Handling Errors How ColdFusion handles errors The following pseudo-code program illustrates how ColdFusion handles errors. The rest of this expands on this outline: Case missing template error ColdFusion displays either a standard error page or an error page that you specify as the Missing Template Handler in the Administrator Server Settings Missing Template Handler field.
Generating Custom Error Messages with cferror Generating Custom Error Messages with cferror By default, ColdFusion uses a standard page for most errors. Custom error pages allow you to control the error information that users see. You can specify custom error pages for different types of errors and handle different types of errors in different ways.
Chapter 11 Preventing and Handling Errors Creating an error application page Error application pages for validation and request errors cannot use ColdFusion tags; they can only use HTML tags. Error application pages for exception and monitor errors can use all of CFML, including tags, expressions, and functions. Even validation and request error pages have access to specific CFML error variables such as Error.Diagnostics (for request errors) and Error.InvalidFields (for validation errors).
Page 221
Generating Custom Error Messages with cferror Error type Error variable Description error.validationHeader Validation Text for header of default validation message. error.invalidFields Unordered list of validation errors that occurred. This includes any text that you specify in the value attribute or a hidden tag used to validate form input.
Chapter 11 Preventing and Handling Errors Example of a validation error page The following example shows a custom error page for a validation error: <html> <head> <title>Products - Error</title> </head> <body> <h2>Oops</h2> <p>You failed to correctly complete all the fields in the form.
Page 223
Logging Errors We apologize for the inconvenience. </p> <cflog file="myapp_errors" text="Exception error -- Exception type: #error.type# Template: #error.template#, Remote Address: #error.remoteAddress#, HTTP Rerference: #error.HTTPReferer# Diagnositcs: #error.diagnostics#" type="Error"> </body> </html> Reviewing the code The following table describes the highlighted code and its function: Code Description <cflog file=”myapp_errors”...
Chapter 11 Preventing and Handling Errors Handling Exceptions in ColdFusion Ordinarily, when ColdFusion encounters an error, it stops processing and displays an error message or error page (as specified by the tag). However, you can cferror use ColdFusion’s exception handling tags to catch and process exceptions in ColdFusion pages.
Handling Exceptions in ColdFusion Types of recoverable exceptions supported ColdFusion Server supports several types of recoverable exceptions. Use the type attribute in the tag to determine which type of exception to catch. You can cfcatch also use these types as the values of the attribute in exception cferror...
Chapter 11 Preventing and Handling Errors Applications can optionally use the tag to raise custom exceptions. Such cfthrow exceptions are caught with any of the following type specifications: type="custom_exception_type" " type="application type="any" The custom_exception_type type designates the name of a user-defined type specified in the tag.
Page 227
Handling Exceptions in ColdFusion The structure at position 1 of the array represents the outermost tag in the stack of tags that were executing when the interpreter detected the exception. The structure at position ArrayLen( .tagContext) represents the currently executing tag at cfcatch the time the interpreter detected the exception.
Chapter 11 Preventing and Handling Errors Locking exceptions The following additional information is available for exceptions related to cflock sections: Property variable Description cfcatch.lockName The name of the affected lock. This is set to "anonymous" if the lock name is unknown. cfcatch.lockOperation The operation that failed.
Page 229
Handling Exceptions in ColdFusion <!--- Wrap code you want to check in a cftry block ---> <cfset EmpID=3> <cftry> <cfquery name="test" datasource="CompanyInfo"> SELECT Dept_ID, FirstName, LastName FROM Employee WHERE Emp_ID=#EmpID# </cfquery> <html> <head> <title>Test cftry/cfcatch</title> </head> <body> <hr> <cfinclude template="includeme.cfm"> <cfoutput query="test">...
Chapter 11 Preventing and Handling Errors </cfcatch> <!--- Use cfcatch with TYPE="Any" ---> <!--- to find unexpected exceptions. ---> <cfcatch type="Any"> <cfoutput> <h1>Other Error: #cfcatch.Type#</h1> <ul> <li><b>Message:</b> #cfcatch.message# <li><b>Detail:</b> #cfcatch.Detail# </ul> </cfoutput> </cfcatch> </cftry> </body> </html> To test the code: Make sure there is no includeme.cfm file and display the page.
Page 231
Handling Exceptions in ColdFusion Naming conventions A naming convention for custom exception types follows a convention that is similar to Java class naming conventions: domain name in reverse order, followed by project identifiers, as in this example: <cfthrow type="Invalid_field.codeValue" errorcode="Dodge14B"> The predefined exception types, except for are reserved;...
Page 232
Chapter 11 Preventing and Handling Errors...
Chapter 12 Using the Application Framework The ColdFusion Web Application Framework is a powerful tool that you can use to help structure your ColdFusion applications. This chapter describes how to create and use the Application.cfm file, the application page that controls the application framework.
Chapter 12 Using the Application Framework 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.
Understanding the Web Application Framework Variable Scope Description Application Contains variables that are available to all pages in an application for all clients. Application variables are stored in memory and time out after a period of inactivity or when the server shuts down. You can access the Application scope as a data structure.
Chapter 12 Using the Application Framework Mapping an Application Framework An important step in designing a ColdFusion application is mapping its directory structure. Before you start building the application, establish a root directory for the application. You can store application pages in subdirectories of the root directory. Processing Application.cfm and OnRequestEnd.cfm ColdFusion uses similar but different rules to locate and process Application.cfm and OnRequestEnd.
Mapping an Application Framework Defining the directory structure Defining a root directory for an application has a number of advantages: Development The application is easier to develop and maintain because the application page files are well organized. Portability You can more easily move the application to another server or another part of a server without changing any code in the application page files.
Page 238
Chapter 12 Using the Application Framework...
Creating the Application.cfm File Creating the Application.cfm File The special application-wide page called Application.cfm defines application-level settings and functions such as: Application name Client state management options Application and Session variable management options Default variables Application-specific custom error pages Data sources Default style settings Exclusive locks Other application-level constants...
Page 240
Chapter 12 Using the Application Framework Example: Application.cfm The following example shows a complete Application.cfm file for the sample Products application: <!--- Set application name and enable Client variables, stored in a data source called mycompany ---> <cfapplication name="Products" clientmanagement="Yes" clientstorage="mycompany"...
Managing the Client State Managing the Client State Because the Web is a stateless system, each connection that a browser makes to a Web server is unique to the Web server. However, within an application it is important to be able to keep track of users as they move through the pages within the application.
This attribute specifies that the server-side copies of the CFID and CFToken variables used to identify the client to ColdFusion are stored at the domain level (for example, .macromedia.com). If CFID and CFToken combinations already exist on each host in the cluster, ColdFusion migrates the host-level variables on each cluster member to the single, common domain-level variable.
Configuring and Using Client Variables Configuring and Using Client Variables To use Client variables effectively, you set up the Client variable options and use the variables on your ColdFusion pages. Setting up Client variable options If you want to enable Client variables, you must do so on every page in an application.
Chapter 12 Using the Application Framework Consider these additional limitations before implementing cookie storage for Client variables: Many browsers allow only 20 cookies from a particular host to be set. ColdFusion uses two of these cookies for CFID and CFToken and also creates a cookie named to hold global data about the client, such as cfglobals HitCount...
Page 245
Configuring and Using Client Variables The following example shows how to use the tag to check for the existence cfparam of a client parameter and to set a default value if the parameter does not already exist: <cfparam name="Client.FavoriteColor" default="Red"> Accessing and changing Client variables You use the same syntax to access a Client variable as other types of variables.
Page 246
Chapter 12 Using the Application Framework Getting a list of Client variables To obtain a list of the custom client parameters associated with a particular client, use the function. GetClientVariablesList <cfoutput>#GetClientVariablesList()#</cfoutput> function returns a comma-separated list of the names GetClientVariablesList of the Client variables for the current application.
Page 247
Configuring and Using Client Variables Exporting the Client variable database If your Client variable database is stored in the Windows 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.
Chapter 12 Using the Application Framework Using Session Variables Use Session variables when you need the variables for a single site visit or set of requests. For example, you might use Session variables to store a user’s selections in a shopping cart application. (Use Client variables when you need the variable for future visits.) Caution You must use the...
Using Session Variables The default timeout for Session variables is set to 20 minutes. You can change the timeout on the Memory Variables page of the ColdFusion Administrator Server tab. For more information, see Advanced ColdFusion Administration. You can also set the timeout period for Session variables inside a specific application (thereby overruling the Administrator default setting) by using the cfapplication attribute.
Chapter 12 Using the Application Framework Getting a list of Session variables The variable Session scope is registered as a ColdFusion structure. This lets you use the ColdFusion Structure functions to get a list of Session variables. For example, you can use with the function to output a list of Session variables...
Using Application Variables variables, they are not useful for client-specific information. To target variables for specific clients, use Session or Client variables. Application variable timeouts Application variables have a specific lifetime. If no clients access the application within the specified timeout period, ColdFusion Server destroys its Application variables.
Chapter 12 Using the Application Framework Using Server Variables Server variables are associated with a single ColdFusion Server. They are available to all applications that run on the server. Use server variables for data that must be accessed across clients and applications. Server variables do not time out, but are lost when the server shuts down.
Locking Code with cflock Locking Code with cflock tag controls simultaneous access to ColdFusion code. The cflock cflock enables you to: Protect sections of code that access and manipulate shared data such as Session, Application, and Server variables. Ensure that file updates do not fail because files are open for writing by other applications or ColdFusion tags.
Page 254
Chapter 12 Using the Application Framework tag enables you to ensure that concurrently executing requests do not cflock access the same section of code simultaneously and thus manipulate shared data structures, files, or CFXs inconsistently. It is important to remember that cflock protects code sections not variables.
Page 255
Locking Code with cflock You can set the attribute to any of the following values: Scope Meaning Server All code sections with this attribute on the server share a single lock. Application All code sections with this attribute in the same application share a single lock.
Chapter 12 Using the Application Framework For example, if you want to assign the results of a query to a Session variable, first get the query results using a Variables scope variable in unlocked code. Then, assign the query results to a Session variable inside a locked code section. The following code illustrates this technique: <cfquery name="Variables.qUser"...
Locking Code with cflock Automatic read locking also adds overhead because ColdFusion must insert read locks and check variable access for locking. However, it can be useful if you already have a site that does not use locking properly. In this case, you must only lock all writes and do not have to add locks around all reads.
Chapter 12 Using the Application Framework Unlock the Application scope. Unlock the Session scope. Note You can skip any pair of lock/unlock steps in the preceding list if you do not need to lock a particular scope. For example, you can omit steps 3 and 4 if you do not need to lock the Server scope.
Page 259
Examples of cflock </cfif> </cflock> <!--- Always display the number of turtlenecks sold ---> <cflock scope="Application" timeout="10" type ="ReadOnly"> <cfoutput> E-Turtleneck is proud to say that we have sold #application.number# turtlenecks to date. </cfoutput> </cflock> The remaining sample code could appear inside the application page where customers place orders.
Page 260
Chapter 12 Using the Application Framework <!--- Lock Application Variable application.number to update the total number of turtlenecks sold. ---> <cflock scope="Application" timeout="30" type="Exclusive"> <cfset application.number=application.number + 1> </cflock> <!--- Show the form only if it has not been submitted. ---> <cfelse>...
Page 261
Examples of cflock Example of synchronizing access to a file system The following example shows how to use to synchronize access to a file cflock system. The tag protects a tag from attempting to append data to a cflock cffile file already open for writing by the same tag executing on another request.
Page 262
Chapter 12 Using the Application Framework...
Chapter 13 Extending ColdFusion Pages 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. You can also use CFScript to write custom functions that you can use anywhere a ColdFusion expression is allowed.
Chapter 13 Extending ColdFusion Pages with CFML Scripting 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 < > and < >...
The CFScript Language The CFScript Language This section explains the syntax of the CFScript language. Comments Comments in CFScript blocks begin with two forward slashes (//) and end at the line end. You can also enclose CFScript comments between /* and */. Note that you cannot nest /* and */ inside other comment lines.
Page 266
Chapter 13 Extending ColdFusion Pages with CFML Scripting if-else: if(expr) statement [else statement] ; if(score GT 1) result = "positive"; else result = "negative"; for loop: for (init-expr ; test-expr ; final-expr) statement ; 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...
Page 267
The CFScript Language do-while loop: do statement while (expr) ; // Complete do-while loop on a single line a = ArrayNew(1); loop = 1; do {a[loop] = loop + 5; loop = loop + 1;} while (loop LT 10); // Multiline do-while loop a = ArrayNew(1);...
Chapter 13 Extending ColdFusion Pages with CFML Scripting continue: skip to next loop iteration for ( loop=1; loop LT 10; loop = loop+1) if(a[loop] EQ 0) continue; a[loop]=1; break: break out of the current switch statement or loop indx = 0; for( ;...
Interaction of CFScript with CFML Interaction of CFScript with CFML You enclose CFScript regions inside tags. No other <cfscript> </cfscript> CFML tags are allowed inside a region. cfscript ColdFusion generates an error if a tag block does not contain at least one cfscript CFScript statement, and CFScript comments are not considered statements.
Chapter 13 Extending ColdFusion Pages with CFML Scripting Defining and Using Custom Functions You can define custom functions (also known as user-defined functions) and use them in your application pages as you do standard ColdFusion functions. This allows you to create a function for an algorithm or procedure that you use frequently, and then use the function wherever you need the procedure.
Defining and Using Custom Functions The following two statements are allowed only in function definitions. Each function must have a return statement: var variableName = initialValue; Creates and initializes a variable that is local to the function (function variable). This variable has meaning only inside the function and is not saved between calls to the function.
Page 272
Chapter 13 Extending ColdFusion Pages with CFML Scripting Each function has a built-in array containing all arguments passed to the Arguments function: the required arguments specified by the function parameters followed by any additional arguments included in the function call. The function can determine the number of arguments passed to it by using the ColdFusion function call ArrayLen(Arguments)
Defining and Using Custom Functions used elsewhere in your application. If a function must use a variable from another scope that has the same name as a function variable, just prefix the external variable with its scope identifier, such as Variables or Form. For example, if you use the variable name for a function scope ( ) variable and...
Chapter 13 Extending ColdFusion Pages with CFML Scripting Return DollarFormat(totalInterest); </cfscript> You could use the TotalInterest function in a tag of a form’s action page as cfoutput follows: <cfoutput> Loan amount: #Form.Principal#<br> Annual percentage rate: #Form.AnnualPercent#<br> Loan duration: #Form.Months# months<br> TOTAL INTEREST: #TotalInterest(Form.Principal, Form.AnnualPercent, Form.Months)#<br>...
Page 275
Defining and Using Custom Functions You can use functions that manipulate many rows of a query outside such tags. There you can pass in a query and loop over it in the function. The following example, which changes text in a query column to uppercase, illustrates using a function to modify multiple query rows.
Page 276
Chapter 13 Extending ColdFusion Pages with CFML Scripting function makes using the structure appears, but the change the function makes using the directly passed array does not affect the array outside the function. <CFScript> //Create a two-element array inside a structure mystruct = StructNew();...
Page 277
Defining and Using Custom Functions else // Need to return error value // Caller will look at value and then decide to look at errorInfo // Alternatively, caller can look at errorInfo and see whether // some pre-defined fields are available return -1;...
Page 278
Chapter 13 Extending ColdFusion Pages with CFML Scripting...
Page 279
Chapter 14 Using Regular Expressions in Functions This chapter describes how regular expressions work in the following ColdFusion functions: REFind REFindNoCase REReplace REReplaceNoCase This chapter does not apply to regular expressions used in the cfinput tags. These tags use JavaScript regular expressions, which have a cftextinput slightly different syntax than ColdFusion regular expressions.
Chapter 14 Using Regular Expressions in Functions About Regular Expressions Regular expressions allow you to perform very powerful and flexible string search and replace operations. In traditional search and replace operations, as in the Find functions of ColdFusion, you must provide the exact text to be searched Replace for.
Both ’a’ and ’]’ were Replaced with *<br></cfoutput> Character classes In ColdFusion regular expressions, you can specify a character using one of the POSIX character classes. You enclose the character class name inside two square brackets, as in this example: REReplace (“Macromedia Web Site”,”[[:space:]]”,”*”,”ALL”)
Page 282
Chapter 14 Using Regular Expressions in Functions This code replaces all the spaces with *, producing this string: Macromedia*Web*Site The following table shows the POSIX character classes that ColdFusion supports: Character Class Matches alpha Matches any letter. Same as [A-Za-z].
Multicharacter Regular Expressions Multicharacter Regular Expressions You can use the following rules to build multicharacter regular expressions: Parentheses group parts of regular expressions together into grouped subexpressions that you can be treat as a single unit; for example, (ha)+ matches one or more instances of “ha”.
Chapter 14 Using Regular Expressions in Functions An excellent reference on regular expressions is Mastering Regular Expressions, Jeffrey E. F. Friedl. O’Reilly & Associates, Inc., 1997. ISBN: 1-56592-257-3, http:// www.oreilly.com. Limiting input string size In CFML regular expression functions, large input strings (greater than approximately 20,000 characters) cause a debug assertion failure and a regular expression error occurs.
Using Backreferences Using Backreferences ColdFusion Server supports backreferencing, which allows you to match text in previously matched sets of parentheses. A slash followed by a digit n (\n) refers to the subexpression in parentheses. One use for backreferencing is in searching for doubled words; for example, to find instances of “the the”...
Chapter 14 Using Regular Expressions in Functions Returning Matched Subexpressions functions allow you to get information about REFind REFindNoCase matched subexpressions. If you set these functions’ fourth parameter, , to True, the function returns a CFML structure with two ReturnSubExpression arrays containing the positions and lengths of text strings that match the subexpressions of the first instance of a matched regular expression pattern.
Regular Expression Examples Regular Expression Examples The following examples show some regular expressions and describe what they match: Expression Description [\?&]value= A URL parameter value in a URL. [A-Z]:(\\[A-Z0-9_]+)+ An uppercase DOS/Windows full path that (a) is not the root of a drive, and (b) has only letters, numbers, and underscores in its text.
Page 288
Chapter 14 Using Regular Expressions in Functions Expression Returns REFind ("[Uu]\.?[Ss]\.?[Aa}\.?", The position in the variable Report of the Report ) first occurrence of the abbreviation USA. The letters can be in either case and the abbreviation can have a period after any letter.
Chapter 15 Indexing and Searching Data You can provide a full-text search capability for documents and data sources on a ColdFusion site by enabling the Verity search engine. ColdFusion 5 supports two Verity search engines: the default Verity search engine (VDK mode) and a restricted version of the Verity K2 Server.
Chapter 15 Indexing and Searching Data Searching a ColdFusion Web Site Until now, you have 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 you need full-text search capabilities. The Verity search engines are bundled with ColdFusion to provide full-text indexing and searching.
Supported File Types Supported File Types The ColdFusion Verity implementation supports a wide array of file and document types. As a result, you can index Web pages, ColdFusion applications, and many binary document types and produce search results that include summaries of these documents.
The ColdFusion International Language Search Pack is not shipped with ColdFusion, but is available on a separate CD-ROM free of charge. To order the Language Search Pack, contact Macromedia Customer Service or visit the online store at http://www.coldfusion.com/store. It can be installed to index data in any of...
Creating a Searchable Data Source Creating a Searchable Data Source You must do the following steps to create a searchable data source: Create a collection. You can do this either through the ColdFusion Administrator or programmatically. Populate and index the collection. You must select the data and generate the index.
Page 294
Chapter 15 Indexing and Searching Data If you checked the option to install the ColdFusion documentation, the documentation collection is listed by default. The Verity engine is used to search the online documents. In the top section of the page, enter a name for the collection. Enter a path for the directory location of the new collection.
Page 295
Creating a Searchable Data Source To create a simple collection form page: Open a new file in ColdFusion Studio. Modify the file so that it appears as follows: <html> <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"...
Creating a Searchable Data Source Selecting an indexing method Use the following guidelines to determine which method to use: Use the Administrator if Use the cfindex tag if You want to index document files. You want to index ColdFusion query results. The collection will not be updated Your collection needs to be updated frequently.
Page 298
Chapter 15 Indexing and Searching Data Using cfindex You can use a form page an action page similar to the following examples to select a collection and index it. To select which collection to index: Open a new file in ColdFusion Studio. Modify the file so that it appears as follows: <html>...
Creating a Searchable Data Source <cfoutput> The collection #Form.IndexColl# has been indexed. </cfoutput> </body> </html> Save the file as collectionindexaction.cfm. View in your browser, enter values, and then click collectionindexform.cfm Index. Building a search interface After you create and index a searchable data source, you need to build a search interface to allow users to access the data source.
Page 300
Chapter 15 Indexing and Searching Data value=simple checked> Simple<br> <input type=radio name=type value=explicit> Explicit<br> <p>Enter a search string:</p> <input type=text name=searchstring size=50> <p><input type=submit name=search1 value="Search"> <input type=reset value="Reset"> </form> </body> </html> Save the file as collectionsearchform.cfm Note To use to search a Verity K2 Server collection, the attribute cfsearch...
Page 301
Creating a Searchable Data Source <hr noshade> </body> </html> Save the file as collectionsearchaction.cfm. View the file in your browser, enter values in the collectionsearchform.cfm form, and then submit it. Creating summaries As part of the indexing process, Verity automatically produces a summary of every document file or every query result set that gets indexed.
Chapter 15 Indexing and Searching Data Indexing Query Results The following sections describe the reasons and procedures for indexing the results of database, LDAP, and pop queries. Indexing database query results The main advantage of performing searches against a Verity collection over using alone is that the database is indexed in a form that provides faster access.
Indexing Query Results body="MessageText" key="Message_ID" title="Subject" query="Messages"> This statement specifies the MessageText column as the information to be cfindex indexed and names the table’s primary key, the Message_ID column, as the value. Note that the attribute names the Subject column. You can use the title attribute to designate an output parameter.
Chapter 15 Indexing and Searching Data <cfindex action="update" collection="ldap_query" key="dn" type="custom" title="o" query="OrgList" body="telephonenumber"> <!--- Search the collection ---> <!--- Use the wildcard * to contain the search string ---> <cfsearch collection="ldap_query" name="s_ldap" criteria="*617*"> <!--- Output returned records ---> <cfoutput query="s_ldap"> #Key#, #Title#, #Body# <br>...
Using Query Expressions type="custom" title="subject" query="p_messages" body="body"> <!--- Search messages for the word "action" ---> <cfsearch collection="pop_query" name="s_messages" criteria="action"> <!--- Output search result set ---> <cfoutput query="s_messages"> #key#, #title# <br> </cfoutput> Using Query Expressions When you search a Verity collection, you use the tag in a ColdFusion cfsearch application page.
Chapter 15 Indexing and Searching Data A simple query automatically employs the STEM operator and the MANY modifier. STEM searches for words that derive from those entered in the query expression, so entering “find” returns documents that contain “find,” “finding,” “finds,” and so on. The MANY modifier presents the documents returned in the search as a list based on a relevancy score.
Using Query Expressions Verity Search Operators MATCHES STARTS > NEAR STEM >= NEAR/N SUBSTRING Accrue WILDCARD PARAGRAPH WORD Special characters The search engine handles a number of characters in particular ways as described in the following table: Characters Description , ( ) [ These characters end a text token.
Chapter 15 Indexing and Searching Data When you use prefix notation, the expression specifies precedence explicitly. The following example means: Look for documents that contain b and c first, then documents that contain a: OR (a, AND (b,c)) When you use infix notation, precedence is implicit in the expression. For example, the AND operator takes precedence over the OR operator.
Using Query Expressions Wildcard Description Curly braces. Matches any one of a set of patterns separated by a comma, as in “hoist{s, ing, ed}”, which locates “hoists,” “hoisting,” and “hoisted”. Caret. Matches any character not in the set, as in “sl[^ia]m”, which locates “slum”...
Chapter 15 Indexing and Searching Data Operators and modifiers The power of the tag is in the control it provides over the Verity search cfsearch engine. The engine offers users a high degree of specificity in setting search parameters. Operators An operator represents logic to be applied to a search element.
Page 311
Using Query Expressions The following tale describes the evidence operators: Operator Description STEM Expands the search to include the word you enter and its variations. The STEM operator is automatically implied in any simple query. For example, the explicit query expression: <STEM>believe yields matches such as “believe,”...
Page 312
Chapter 15 Indexing and Searching Data The following table describes the 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 313
Using Query Expressions You use the following operators for numeric and date comparisons: Operator Description Equals > Greater than >= Greater than or equal to < Less than <= Less than or equal to The following relational operators compare text and match words and parts of words: Operator Description...
Page 314
Chapter 15 Indexing and Searching Data Document fields You can specify the values for the attributes TITLE, KEY, URL, and CUSTOM cfindex as document fields for use with relational operators in the attribute. criteria Document fields are referenced in text comparison operators. They are identified as: CF_TITLE CF_KEY CF_URL...
Page 315
Using Query Expressions key="Identifier" body="TEXT" query="GetText"> <cfsearch name="GetText_Search" collection="testcollection" type="Explicit" criteria="1990 and CF_TITLE <SUBSTRING> Utah"> <cfoutput> Record Counts: <br> #GetText.RecordCount# <br> #GetText_Search.RecordCount# <br> </cfoutput> Query Results --- Should be 5 rows <br> <cfoutput query="Gettext"> #Identifier# <br> </cfoutput> Search Results -- should be 1 row <br> <cfoutput query="GetText_Search">...
Page 316
Chapter 15 Indexing and Searching Data Score operators Score operators govern how the search engine calculates scores for retrieved documents. The maximum score that a returned search element can have is 1.000. You can set the score percentage display to as many as four decimal places. When you use a score operator, the search engine first calculates a separate score for each search element found in a document, and then performs a mathematical operation on the individual element scores to arrive at the final score for each...
Using Query Expressions Modifiers You combine modifiers 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. The following table describes the available modifiers.
Chapter 15 Indexing and Searching Data Managing Collections As with any data source, the maintenance requirements of a Verity collection are dictated by the number, frequency, and type of changes that occur in the records. You can run maintenance routines directly from either the cfcollection cfindex tags or via the Administrator Verity Collections page.
Page 319
Managing Collections To restrict access to a collection, follow these steps: In the ColdFusion Administrator, click the Security tab and select Advanced Security > Security Configuration. Select the Use Advanced Server Security box. Click the Submit Changes button. Click the Security Contexts button. Enter a name for the secured collection and click Add Security Context.
Page 320
Chapter 15 Indexing and Searching Data...
Chapter 16 Sending and Receiving E-mail You can add interactive mail features to your ColdFusion applications, providing a complete two-way interface to mail servers via the tag and the tag. The cfmail cfpop boom in Internet mail services makes ColdFusion’s enhanced e-mail capability a vital link to your users.
Chapter 16 Sending and Receiving E-mail Using ColdFusion with Mail Servers Adding e-mail to your ColdFusion applications lets you respond automatically to user requests. You can use e-mail in your ColdFusion applications in many different ways. These are just a few examples: Trigger e-mail messages based on users’...
Sending E-mail Messages Sending SMTP mail with cfmail tag provides support for sending SMTP e-mail from within ColdFusion cfmail applications. The tag is similar to the tag, except that cfmail cfoutput cfmail outputs the generated text as SMTP mail messages rather than to a page. The cfmail tag supports all the attributes and commands that you use with , including...
Chapter 16 Sending and Receiving E-mail Sample Uses of cfmail An application page with the tag dynamically generates e-mail messages cfmail based on the tag’s settings. Some of the tasks you can accomplish with cfmail include the following: Sending a mail message whose recipient and contents are determined by data the user enters in an HTML form Using a query to send a mail message to a database-driven list of recipients Using a query to send a customized mail message, such as a billing statement to...
Sample Uses of cfmail #ProductRequests.FirstName# #ProductRequests.LastName# (#ProductRequests.Company#) - #ProductRequests.EMailAddress#&##013; </cfoutput> Regards, The WebMaster webmaster@MyCompany.com </cfmail> Note the use of the tag to present a dynamic list embedded within a cfoutput normal message. The text within the is repeated for each row in the cfmail cfoutput ProductRequests query, while the text above and below it serve as the header and...
Chapter 16 Sending and Receiving E-mail Customizing E-mail for Multiple Recipients In the following example, a query (GetCustomers) is run to retrieve the contact information for a list of customers. This query is then used to send an e-mail to each customer asking the person to verify that the contact information is still valid: <cfmail query="GetCustomers"...
Customizing E-mail for Multiple Recipients Attaching a MIME file You use the tag to attach a file or add a header to a mail message. In the cfmailparam following example, a MIME-encoded file is sent along with an e-mail message: <cfmail from="abeecho@MyCompany.com"...
Chapter 16 Sending and Receiving E-mail Advanced Sending Options The ColdFusion implementation of SMTP mail uses a spooled architecture. When a tag is processed in an application page, the messages that are generated are cfmail not sent immediately. Instead, they are spooled to disk and processed in the background.
Receiving E-mail Messages Receiving E-mail Messages the Post Office Protocol tag, , expands your ability to add Internet mail client cfpop features and e-mail consolidation to applications. While a conventional mail client provides an adequate interface for personal mail, there are many cases in which an alternative interface to some mailboxes is desirable.
Chapter 16 Sending and Receiving E-mail cfpop query variables Two variables are returned for each query that provide record number cfpop information: The total number of records returned by the query. RecordCount The current row of the query being processed by in a CurrentRow cfoutput...
Page 331
Handling POP Mail <h2>This example retrieves message header information:</h2> <cfpop server="mail.company.com" username=#myusername# password=#mypassword# action="GetHeaderOnly" name="Sample"> <cfoutput query="Sample"> MessageNumber: #HTMLEditFormat(Sample.messageNumber)# <br> To: #HTMLEditFormat(Sample.to)# <br> 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><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"...
Chapter 16 Sending and Receiving E-mail Retrieving an entire message When you use the tag with , ColdFusion returns the same cfpop action="GetAll" columns as with , plus two additional columns, getheaderonly body header To retrieve an entire message: Create a new file in ColdFusion Studio. Modify the file so that it appears as follows: <html>...
Handling POP Mail Note that this example does not use a CFML function to encode the body contents. As a result, the browser displays the formatted message as you would normally see it in a mail program that supports HTML messages. Retrieving attachments with messages When you use the tag with...
Chapter 16 Sending and Receiving E-mail <br> Body:<br> #Sample.body# <br> <br> Header:<br> HTMLCodeFormat(Sample.header)# <br> <hr> </cfoutput> </body> </html> Change the following line so that it refers to a valid POP mail server, as well as to a valid user name and password: <cfpop server="mail.company.com"...
Page 335
Handling POP Mail To delete messages: Create a new file in ColdFusion Studio. Modify the file so that it appears as follows: <html> <head> <title>POP Mail Message Delete Example</title> </head> <body> <h2>This example deletes messages:</h2> <cfpop server="mail.company.com" username=#username# password=#password# action="Delete" messagenumber="1,2,3">...
Page 336
Chapter 16 Sending and Receiving E-mail...
Chapter 17 Managing Files on the Server , and tags handle browser/server file cffile cfdirectory cfcontent management tasks. To perform server-to-server operations, use the CFFTP tag, described in “Performing File Operations with cfftp” on page 341. Contents Using cffile ....................... 318 Uploading Files......................
Chapter 17 Managing Files on the Server Using cffile tag gives you the ability to work with files on your server in a number of cffile 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 You use the...
Uploading Files Uploading Files File uploading requires that you create two files: An HTML form to enter file upload information An action page containing the file upload code To create an HTML file to specify file upload information: Create a new file in ColdFusion Studio. Modify the file so that it appears as follows: <html>...
Page 340
Chapter 17 Managing Files on the Server The user can enter a file path or browse the system and pick a file to send. To create an action page to upload the file: Create a new file in ColdFusion Studio. Modify the file so that it appears as follows: <html>...
Uploading Files Reviewing the code The following table describes the code and its function: Code Description <cffile action="upload" Prepare to upload a file to the server. destination="c:\temp" Specify the destination of the file. nameConflict="overwrite" If the file already exists, overwrite it. fileField="Form.FiletoUpload">...
Page 342
Chapter 17 Managing Files on the Server Note Not all browsers support MIME type associations. Example: Restricting file types This specification saves an image file only if it is in the GIF format: cffile <cffile action="Upload" fileField="Form.FiletoUpload" destination="c:\uploads\MyImage.GIF" nameConflict="Overwrite" accept="image/gif"> This specification saves an image file only if it is in GIF or JPEG format: cffile...
Setting File and Directory Attributes Setting File and Directory Attributes In Windows, you specify file attributes using the attribute. In cffile attributes UNIX, you specify file and directory permissions using the cffile cfdirectory attribute. mode Windows In Windows, you can set the following file attributes: ReadOnly Temporary Archive...
Chapter 17 Managing Files on the Server You enter permissions values in the attribute for each type of user: owner, mode group, and other in that order. For example, use the following code to assign read permissions for everyone: mode=444 To give a file or directory owner read/write/execute permissions and read only permissions for everyone else: mode=744...
Page 345
Evaluating the Results of a File Upload Variable Description fileWasAppended Indicates (Yes or No) whether ColdFusion appended the uploaded file to an existing file. fileWasOverwritten Indicates (Yes or No) whether ColdFusion overwrote a file. fileWasRenamed Indicates (Yes or No) whether the uploaded file was renamed to avoid a name conflict.
Chapter 17 Managing Files on the Server Moving, Renaming, Copying, and Deleting Server Files With , you can create application pages to manage files on your Web server. cffile You can use the tag to move files from one directory to another, rename files, copy a file, or delete a file.
Reading, Writing, and Appending to a Text File Reading, Writing, and Appending to a Text File In addition to managing files on the server, you can use to read, create, and cffile modify text files. As a result, you can do the following things: Create log files.
Chapter 17 Managing Files on the Server Writing a text file You can use to write a text file based on dynamic content. For example, you cffile could create static HTML files or log actions in a text file. To create a form in which to enter data for a text file: Open a new file in ColdFusion Studio.
Performing Directory Operations The text file is written to the location you specified. If the file already exists, it is replaced. You can use to append additional text to the end of an cffile action="Append" existing text file, for example, when you create log files. Performing Directory Operations Use the tag to return file information from a specified directory and to...
Page 350
Chapter 17 Managing Files on the Server <th>Modified</th> <th>Attributes</th> <th>Mode</th> </tr> <cfoutput query="mydirectory"> <tr> <td>#mydirectory.name#</td> <td>#mydirectory.size#</td> <td>#mydirectory.type#</td> <td>#mydirectory.dateLastModified#</td> <td>#mydirectory.attributes#</td> <td>#mydirectory.mode#</td> </tr> </cfoutput> </table> </body> </html> Modify the 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.
Chapter 18 Interacting with Remote Servers This chapter describes how ColdFusion wraps the complexity of Hypertext Transfer Protocol (HTTP) and File Transfer Protocol (FTP) communications in a simplified tag syntax that lets you easily extend your site’s offerings across the Web. Contents Using cfhttp to Interact with the Web..............
Chapter 18 Interacting with Remote Servers Using cfhttp to Interact with the Web tag, which enables you to retrieve information from a remote server, is cfhttp 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 tag: Get or Post.
Page 353
Using the cfhttp Get Method Reviewing the code The following table describes the code and its function: Code Description <cfhttp method="Get" Get the page specified in the URL and url="http://www.ci.newton.ma.us/ make the links absolute instead of relative main.htm/ so that they display properly. resolveurl="Yes">...
Page 354
Chapter 18 Interacting with Remote Servers To get a binary file and save it: Open a new file in ColdFusion Studio. Modify the file so that it appears as follows: <cfhttp method="Get" url="http://localhost/myapps/testfile.zip" path="c:\temp" file="MyTestFile.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.
Creating a Query from a Text File Creating a Query from a Text File You can create a query object from a delimited text file by using the tag and cfhttp specifying and the attribute. This is a powerful method for method="Get"...
Page 356
Chapter 18 Interacting with Remote Servers <!--- Now substitute different column names ---> <!--- by using the columns attribute ---> <hr> Now using replacement column names<br> <cfhttp method="Get" url="http://127.0.0.1/orders/june/orders.txt" name="juneorders" columns="ID,Number,ODate,SDate,Name,Address" delimiter=","> <cfoutput query="juneorders"> Order ID: #ID#<br> Order Number: #Number#<br> Order Date: #SDate#<br>...
Page 358
" name="mycgi"> <cfhttpparam type="URL" Send a URL in the request. value="theurl" name="myurl"> <cfhttpparam type="Formfield" Send a Form field in the request. value="wbfreuh@macromedia.com" name="emailaddress"> <cfhttpparam type="File" Send a file in the request. name="myfile" </cfhttp> tag ends the http request. file="c:\testImage.gif">...
Page 359
Using the cfhttp Post Method <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.emailaddress#. <br> The file was uploaded to #File.ServerDirectory#\#File.ServerFile#. </cfoutput> Replace C:\temp\Junk with an appropriate directory path on your hard drive. Save the file as under your Web root directory.
Page 360
Mime type and Length of the response. The search.exe program must expect a “search” parameter. <cfhttp method="Post" url="http://www.somesiteorother.com/search.exe" resolveurl="Yes"> <cfhttpparam type="Formfield" name="search" value="Macromedia ColdFusion"> </cfhttp> <cfoutput> Response Mime Type: #cfhttp.MimeType#<br> Response Length: #len(cfhttp.filecontent)# <br> Response Content: <br> #htmlcodeformat(cfhttp.filecontent)#<br> </cfoutput>...
Performing File Operations with cfftp Performing File Operations with cfftp tag lets you perform tasks on remote servers using File Transfer Protocol cfftp (FTP). You can use to cache connections for batch file transfers. cfftp Note To use , the Enable Tag option must be selected on the Tag Restrictions cfftp cfftp...
Page 362
Chapter 18 Interacting with Remote Servers <!--- Close the connection.---> <cfftp action="close" connection="Myftp"> <p>Did the connection close successfully? <cfoutput>#cfftp.succeeded#</cfoutput></p> <!--- output dirlist results ---> <hr> <p>FTP Directory Listing:</p> <cftable query="dirlist" colheaders="yes" htmltable> <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>"...
Performing File Operations with cfftp Code Description <cfftp connection=Myftp Use the Myftp connection to get a action="ListDir" directory listing. Use the value returned directory="#cfftp.returnvalue#" by the last call (the current cfftp name="dirlist" directory of the connection) to specify stoponerror="Yes"> the directory to list. Save the results in a variable named dirlist (a query object).
Chapter 18 Interacting with Remote Servers Assigning a connection to an Application variable could cause problems, since cfftp multiple users could access the same connection object at the same time. Creating a Session variable for a connection makes more sense, because the connection cfftp is available to only one client and does not last past the end of the session.
HTTP. Target platforms for WDDX include ColdFusion, Active Server Pages (ASP), JavaScript, Perl, Java, Python, COM, Macromedia Flash, and PHP. Unlike other approaches to creating XML-based generic distributed object systems for the Web, WDDX is not designed as an analog of traditional object programming languages.
Currently, WDDX offers some unique advantages not present in Web Services: It can be used by lightweight clients, such as browsers or the Macromedia Flash player. It can be used to store complex data structures in files and databases.
Moving Complex Data Structures Across the Web with WDDX types, and descriptors that allow the data to be manipulated on a target system between arbitrary application servers. When you use WDDX in ColdFusion pages, you typically use the ColdFusion cfwddx tag and the JavaScript utility classes that are installed as /CFIDE/scripts/wddx.js on your local host.
Chapter 18 Interacting with Remote Servers In the CFML implementation, is an attribute of the useTimezoneInfo cfwddx tag. In the JavaScript implementation, (note action=cfml2wddx useTimezoneInfo the case sensitivity of JavaScript) is a property of the object. WddxSerializer Date-time values in WDDX are represented using a subset of the ISO8601 format. Time zone information is represented as an hour/minute offset from UTC;...
Converting CFML Data to a JavaScript Object Converting CFML Data to a JavaScript Object The following example demonstrates the transfer of a result set from a cfquery CFML page executing on the server to a JavaScript object that is processed by the browser.
Chapter 18 Interacting with Remote Servers Transferring Data from Browser to Server This example serializes form field data, posts it to the server, deserializes it, and outputs the data. For simplicity, only a small amount of data is collected. In applications that generate complex JavaScript data collections, you can extend this basic approach very effectively.
Page 371
Transferring Data from Browser to Server // Person info record set with columns firstName and lastName // Make sure the case of field names is preserved var personInfo = new WddxRecordset(new Array("firstName", "lastName"), true); // Add next record to end of personInfo record set function doNext() // Extract data var firstName = document.personForm.firstName.value;...
Page 372
Chapter 18 Interacting with Remote Servers <!--- Navigation & submission bar ---> <input type="button" value="Next" onclick="doNext()"> <input type="button" value="Serialize" onclick="serializeData(personInfo, document.personForm.wddxPacket)"> <input type="submit" value="Submit"> <P> Names added so far:<br> <select name="names" size="5"> </select> <p></p> <!--- This is where the WDDX packet will be stored ---> <!--- In a real application this would be a hidden input field.
Storing Complex Data in a String Storing Complex Data in a String The following simple example uses WDDX to store complex data, a data structure that contains arrays as a string in a Client variable. It uses the tag to display cfdump the contents of the structure before serialization and after deserialization.
Page 374
Chapter 18 Interacting with Remote Servers...
Chapter 19 Application Security ColdFusion supports several levels of security. This chapter explains how to deploy user security, which offers runtime security for ColdFusion applications. It also describes the Remote Development Services security feature, which authenticates developers accessing server resources through ColdFusion Studio. For information on setting up security elements or using Administrator-controlled security features, see Advanced ColdFusion Administration.
Chapter 19 Application Security 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 the team. They can coordinate team development on shared servers with the assurance that sensitive data and applications are secure.
Overview of User 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 use ColdFusion to build and host your company’s intranet.
Chapter 19 Application Security Using Advanced Security in Application Pages Advanced Security makes it easier for developers to enforce application security. After your administrator sets up the appropriate security contexts for your application, you can start using ColdFusion security tags and functions to authenticate users and see whether they are authorized for the part of the application they are trying to access.
Using the cfauthenticate tag Using the cfauthenticate tag tag has several required attributes: cfauthenticate Describes which security context to use for authentication securityContext and authorization. This name matches the security context as defined on the Advanced Security page of the ColdFusion Administrator. The user name required to access the protected resources.
Chapter 19 Application Security Authentication and Authorization Functions After you use to check whether the user is defined for a particular cfauthenticate security context, you can use the following security functions throughout your applications any time you need to authenticate or authorize a user: checks whether the current session was authenticated by the IsAuthenticated tag.
Catching Security Exceptions Note The ColdFusion Server does not check user authorization unless you specifically request it with the function. It is up to you to decide what action to IsAuthorized take based on the results of the call. IsAuthorized Catching Security Exceptions You can use the tags to catch security exceptions.
Chapter 19 Application Security </cfcatch> </cftry> <cfapplication name="Personnel"> </body> </html> Using the cfimpersonate Tag tag gives ColdFusion developers a way to execute a segment of cfimpersonate code in a secure manner. This tag is useful when you want to briefly grant a type of access that you would normally withhold.
Example of User Authentication and Authorization Example The following example reads a protected file because the ColdFusion user pfoley has been granted access to the file by the security context MyContext. If the user cannot be authenticated, ColdFusion throws a Security exception. <cfimpersonate securitycontext="MyContext"...
Page 384
Chapter 19 Application Security response is checked against the list of valid users defined for the current security context. If the user passes the authentication step, the requested page appears. The application uses the CGI variables to keep track of script_name query_string the originally requested page so that it can display that page after the user is...
Example of User Authentication and Authorization <!--- The login form. Submitting the form re-requests the originally requested page using the recreated url ---> <cfoutput> <form action="#url#" method="Post"> <table> <tr> <td>username:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>password:</td> <td><input type="password" name="password"></td> </tr> </table>...
Page 386
Chapter 19 Application Security </cfif> <cfif IsAuthorized("DataSource", "Orders", "select")> <cfquery name="GetList" datasource="Orders"> SELECT * FROM Orders </cfquery> Authorization Succeeded. Order information follows: <cfoutput query="GetList"> #Customer# - #BalanceDue#<br> </cfoutput> <cfelse> <cfabort showerror="You cannot view order information."> </cfif>...
Page 387
Chapter 20 Using cfobject to Invoke Component Objects This chapter describes how to use the tag to invoke objects created by cfobject component technologies, including COM/DCOM, CORBA, and Java objects. Contents Component Object Overview................. 368 Invoking Component Objects ................369 Getting Started with COM/DCOM.................
Chapter 20 Using cfobject to Invoke Component Objects 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.
Invoking Component Objects Invoking Component Objects You use the tag to create an instance of an object. You use other cfobject ColdFusion tags, such as , to invoke properties (attributes), and cfset cfoutput methods (operations) on the object. An object created by or returned by cfobject other objects is implicitly released at the end of the ColdFusion page execution.
Chapter 20 Using cfobject to Invoke Component Objects 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 must invoke a property or method on that object, use the following syntax: <cfset objX = myObj.X>...
Getting Started with COM/DCOM Registering the object after you acquire the object you want to use, you must register it with Windows in order for ColdFusion (or any other program) to find it. Some objects might be deployed with their own setup programs that register objects automatically, while others might require manual registration.
Page 392
Chapter 20 Using cfobject to Invoke Component Objects 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.
Page 393
Getting Started with COM/DCOM If you view the TypeInfo, you see the object’s methods and properties. Some objects do not have access to the TypeInfo area. This is determined when an object is built and by the language used.
Chapter 20 Using cfobject to Invoke Component Objects Creating and Using COM Objects The following example uses to create the CDO (Collaborative Data cfobject Objects) for NTS NewMail object to send mail. <cfobject type="COM" action="Create" name="Mailer" class="CDONTS.NewMail"> Note CDO is installed by default on all Windows NT and 2000 operating systems that have installed the Microsoft SMTP server.
Creating and Using COM Objects An out-of-process server object (typically an exe file) that is running local outside the ColdFusion process space but running locally on the same server. An out-of-process server object (typically an exe file) that is running remote remotely on the network.
Language (IDL) specification must be registered in the IR. ColdFusion 5 loads ORB runtime libraries dynamically using a connector. Macromedia provides connectors for some of the popular ORBs. Each of these connectors requires the ORB runtime libraries provided by the vendor. You must license the libraries from the appropriate vendor before deploying them.
Page 397
Calling CORBA Objects Example Here is the IDL for an object: struct SimpleStruct 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); Here is the applicable ColdFusion code: <!—-- Declare a couple of structures --->...
Chapter 20 Using cfobject to Invoke Component Objects Exception handling You can catch exceptions thrown by the CORBA object methods with the cftry tags. However, you cannot extract information from the exception object. cfcatch Calling Java Objects tag can call any Java class that is available on the class path specified cfobject on the ColdFusion Administrator JVM and Java Settings page.
Page 400
Chapter 20 Using cfobject to Invoke Component Objects Example: CFML page that uses the Employee class Save the following text as JEmployee.cfm: <html> <body> <cfobject action=create type=java class=Employee name=emp> <!-- <cfset void = emp.init()> --> <cfset emp.firstname="john"> <cfset emp.lastname="doe"> <cfset firstname=emp.firstname> <cfset lastname=emp.lastname>...
Calling Java Objects Java method and field names are not case sensitive. Similarly, ColdFusion variables are not case sensitive. As a result, the sample code works even though the CFML uses emp.firstname and emp.lastname, while the Java source code uses FirstName and LastName for these fields. If you omit a call to the constructor (or, as in this example, comment it out) ColdFusion automatically invokes the default constructor when it first uses the class.
Chapter 20 Using cfobject to Invoke Component Objects Default data type conversion Whenever possible, ColdFusion matches Java types to ColdFusion types as listed in the following table. ColdFusion does not support direct conversion of Date/Time variables and structures. CFML Java type Character String Numeric...
Page 403
Calling Java Objects Example: exception-throwing class The following Java code defines the foo class that throws a sample exception. It also defines a fooException class that extends the Java built-in Exception class and includes a method for getting an error message. public class foo { public foo() { public void doException() throws fooException {...
Chapter 20 Using cfobject to Invoke Component Objects Code Description <cfcatch type="Any"> Catch any exceptions and handle them in this block. <cfset Get the exception data by calling the CFML exception=GetException(Obj)> function and passing it the GetException <cfset Obj object. Set the message variable to the message=exception.GetERrorMessage( string returned by the exception object’s )>...
Calling Java Objects To disable automatic class loading, put all classes in the normal Java class path. Classes located on the Java class path are loaded once per server lifetime and can only be reloaded by stopping and restarting ColdFusion Server. A more complex Java example The following code provides a more complete example of using Java with cfobject.
Page 406
Chapter 20 Using cfobject to Invoke Component Objects String[] ret = new String[arr.length]; for (int i=0; i < arr.length; i++) { ret[arr.length-i-1]=arr[i]; return ret; public int Add(int a, int b) { return (a+b); public float Add(float a, float b) { return (a+b);...
Page 407
Calling Java Objects The useExample CFML Page The following useExample.cfm page uses the class to manipulate numbers, Example strings, Booleans, and Example objects. Note the use of the CFML function JavaCast to ensure that CFML variables convert into the appropriate Java data types. <html>...
Page 408
Chapter 20 Using cfobject to Invoke Component Objects <!--- Create a two-element array, sum its values, and reverse its elements ---> <cfset intarray=ArrayNew(1)> <cfset intarray[1]=1> <cfset intarray[2]=2> <cfset IntVal=obj.sumarray(intarray)> <cfset reversedarray=obj.ReverseArray(intarray)> <!--- Display the results ---> <cfoutput> <br> IntVal1 :#IntVal#<br> array1: #reversedarray[1]#<br>...
Chapter 21 Building Custom CFXAPI Tags Sometimes, the best approach is to develop elements of your application by building executables to run with ColdFusion. Perhaps the application requirements go beyond what is currently feasible in CFML. Perhaps you can improve application performance for certain types of processing.
Chapter 21 Building Custom CFXAPI Tags What Are CFX Tags? CFX tags are custom tags written against the ColdFusion Extension Application Programming Interface. Generally, you create a CFX if you want to do something that is not possible in CFML, or if you want to improve performance of a repetitive task. CFXs can do the following: Handle any number of custom attributes.
Before You Begin Developing CFX Tags in Java Before You Begin Developing CFX Tags in Java While implementing CFX tags in Java is easy, you should consider the information in this section before you begin developing them. Sample Java CFXs Before you begin developing a CFX tag in Java, you might want to study sample CFX tags.
Chapter 21 Building Custom CFXAPI Tags directory created by the ColdFusion setup program serves two classes purposes: It contains the supporting classes required for developing and deploying Java CFXs. This is the package located in the archive. com.allaire.cfx cfx.jar It supports a feature that allows Java CFXs located in the directory to be reloaded every time they are changed.
Writing a Java CFX Writing a Java CFX To create a Java CFX, you create a class that implements the interface. CustomTag This interface contains one method, , which is passed processRequest Request objects that are then used to do the work of the tag. Response To create a Java CFX: Create a new source file in your editor.
Page 414
Chapter 21 Building Custom CFXAPI Tags This section provides an overview of these object types. For a complete example Java CFX that uses , and objects, see the “ZipBrowser Example” Request Response Query on page 397. Request object object is passed to the method of the Request processRequest...
Writing a Java CFX Method Description addRows Adds a new row to the query. setData Sets a data element within the query. For detailed reference information on each of these interfaces, see the CFML Reference. Loading Java CFX classes Each Java CFX class has its own associated that loads it and any ClassLoader dependent classes also located in the...
Chapter 21 Building Custom CFXAPI Tags The default value is . This is appropriate for most applications. Use reload="Auto" during the development process when you must ensure that you reload="Always" always have the latest class files, even when only a dependent class changed. Use to increase performance by omitting the check for changed classes.
ZipBrowser Example ColdFusion processes the page and returns a page that displays the text “Hello, Robert.” If an error is returned instead, check the source code to make sure you have entered it correctly. ZipBrowser Example The following example illustrates the use of the , and Request Response...
Chapter 21 Building Custom CFXAPI Tags // read the zip file and build a query from its contents ZipInputStream zin = new ZipInputStream( new FileInputStream(strArchive) ) ; ZipEntry entry ; while ( ( entry = zin.getNextEntry()) != null ) // add a row to the results int iRow = files.addRow() ;...
Approaches to Debugging Java CFXs If you need to debug a Java CFX while running against a live production server, this is the technique you must use. In addition to outputting debug text using the method, you can also call your Java CFX tag with the Response.write debug="On"...
Page 420
Chapter 21 Building Custom CFXAPI Tags Debugging classes example The following example demonstrates the use of the debugging classes: import java.util.Hashtable ; import com.allaire.cfx.* ; public class OutputQuery implements CustomTag // debugger testbed for OutputQuery public static void main(String[] argv) // initialize attributes Hashtable attributes = new Hashtable() ;...
Developing CFX Tags in C++ Developing CFX Tags in C++ The following sections provide some background to help you develop CFX tags in C++. Sample C++ CFXs Before you begin development of a CFX tag in C++, you might want to study the two CFX tags that are included to give you additional insight into working with the CFXAPI.
Chapter 21 Building Custom CFXAPI Tags To build a CFX tag: In Visual C++, select File > New, and then click the Projects tab. Select ColdFusion Tag Wizard and enter a tag name of the form CFX_MyNewTag the Project name box. Click OK to open the wizard. Enter the new tag name as the name of the custom tag.
Page 423
Developing CFX Tags in C++ On UNIX Use the following debuggers and settings for the supported UNIX operating systems: Debugger Other OS-specific requirements Solaris The environment variables must include LD_LIBRARY_PATH CFHOME Use “stop in main” to set a breakpoint in main. Linux The environment variables must include LD_LIBRARY_PATH...
Chapter 21 Building Custom CFXAPI Tags Registering CFXs To use a CFX tag in your ColdFusion applications, first register it in the Extensions, CFX Tags page in the ColdFusion Administrator. To register a Java CFX: On the ColdFusion Administrator Server tab, select Extensions > CFX Tags to opent the CFX Tags page.
Distributing CFX Tags To delete a CFX tag: Click the Delete Applet (right-most) icon in the Controls column of the Registered CFX Tags list for the tag you want to delete. On Windows NT only, the Visual C++ Custom Tag Wizard automatically registers custom tags so that they can be tested and debugged.
Page 426
Chapter 21 Building Custom CFXAPI Tags To import a Java 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\CurrentVer sion\ CustomTags\CFX_TEST] "ClassName"="ProcessTagRequest" "Description"="Sample CFX tag." In the install script, import the registry entry by including the following command in the install script: regedit importfilename To import a C++ custom tag:...
Index Special processing ArrayNew CFML function saving ArrayPrepend CFML function #,using viewing Arrays , in search expressions Application scope 2-dimensional Application servers, data exchange 3-dimensional across adding data to Accessing Application variables adding elements to Client variables description associative collections lifetime of creating data sources...
Page 428
Index cfauthenticate tag creating queries and Web security Get method Backreferences example Post method about syntax using in regular expression using cfhttpparam tag searches using setcookie CFID in replacement strings cfcatch tag Cookie Bar charts, specifying cfcollection tag managing without cookies appearance cfcontent tag Server-side variable...
Page 429
Index interaction with CFScript cfmodule tag handling failed validaton syntax checker cfoutput tag validating with Javascript syntax errors and pound signs cfstoredproce tag, and queries CFML expressions,in example cftextinput tag CFScript populating list boxes browser considerations CFML functions use with cfquery tag handling failed validaton ArrayAppend use with component...
Page 430
Index Class path managing data sources Conditions, in queries configuring ODBC driver list Connections, caching FTP Java objects and ColdFusion functions. See CFML Constructors, using alternate Class reloading, automatifc Functions continue, CFScript statement Classes, debugging ColdFusion Markup Language. See Cookie scope, catching errors Client cookies CFML Cookies...
Page 431
Index arguments converting to JavaScript Debugging calling object C++ CFX tags defining exchanging across application custom pages and tags described servers full lock checking error handling exchanging with WDDX Java CFX tags evaluating strings filtering Java classes for examples graphing Declaring identifying passing between nested...
Page 432
Index Editions of ColdFusion caching a connection Explicit search query E-mail catching security expressions attachments exceptions Exporting Client variable checking for spooled CFML Java exception database customizing handling Expression exceptions deleting declaring CORBA Expressions error logging structures CFScript for multiple recipients dynamically linking from a pie search syntax form-based...
Page 433
Index referring to GetException CFML function methods scope of query results Formatting Graphing summary of data items individual data points Web sites query results queries Indexing collections Forms query results about about Graphs with Administrator action pages appearance attributes with cfindex check boxes bar charts Infix notation, search string...
Page 434
Index class loading Looping through structures query debugging Request example Response importing Mail servers, and ColdFusion using properties life cycle of Managing ODBC writing client state configuration problems Java objects client state, in clusters data sources calling client state, without described considerations cookies...
Page 435
Index Post cfhttp method indexing Renaming server files Pound signs, using layout Replace CFML function Precedence rules, search LDAP Replacing using regular Prefix notation, search strings no records expressions preservedata cfform attribute records returned Request object Problems, troubleshooting returning Request scope Processing returning incrementally Requirements for COM...
Page 436
Index Scopes string values application defaults and custom functions SUBSTRING operator bar chart characteristics Application wildcards as literals Client variable options Attributes with wildcards COM properties Caller Securing file and directory attributes Client a collection line graph characteristics File custom tags pie chart characteristics Form Security...
Page 437
Index CFScript expression User edits, returning User-defined functions. See Custom Strings functions evaluating in functions Tables Users, keeping track of limiting size of displaying queries storing complex data in using HTML StructClear CFML function Tag Wizard, using Validating StructCopy CFML function Tags, context information at runtime StructCount CFML function...
Page 438
Index types of Windows file attributes Windows NT, debugging C++ CFX using pound signs tags validating Wizards See also Scope, Built-in variables Verbs, SQL Verity Verity WriteOutput CFML function about See also Searching, Search expressions XML, and WDDX Verity wizard Viewing application pages online documentation...