background image

384

Chapter 20 Using cfobject to Invoke Component Objects

Note that after you call GetException, the exception object is just like any other Java 
component object, and you can call any methods on it.

The class loading mechanism

In ColdFusion prior to version 5, Java classes were loaded on demand and they were 
not unloaded until the server restarted. This is the way a typical Java application 
works and is appropriate for production systems. However, if you change a Java 
method implementation, you must shut down the server and restart it before 
ColdFusion can use the new class implementation. 

In version 5, ColdFusion Server uses a custom class loader to load Java classes on the 
fly, similar to Java Servlet engines. This enables you to modify Java method 
implementations and use the new code from ColdFusion without restarting the 
server.

ColdFusion 5 introduces the concept of 

dynamic load path

, a directory that you can 

specify on Cold Fusion Administrator JVM and Java Settings page. You deposit your 
Java class files in this directory when you update the class implementation. 
ColdFusion checks the class file time stamp when an object of the class is created. If 
ColdFusion detects a new class file, it loads the class from that directory. 

To use this feature, make sure that the Java implementation classes that you modify 
are not in the general JVM class path. In addition, do not package the classes into jar 
files or zip files. In all other ways, ColdFusion Class loader follows Java conventions 
including those for package names and directory name mapping. 

Suppose the directory “C:\classes” is the designated “hot” dynamic class path and 
you have a class com.Allaire.Employee. You put the Employee.class file in the 
following location:

C:\ classes\com\Allaire\Employee.class 

The dynamic class-loading feature is meant for development uses, and incurs a 
slight performance penalty associated with checking time stamps during disk IO 
operations. For that reason, you do not use this feature in a production environment 
where there might be high volume of traffic.

<cfcatch type="Any">

Catch any exceptions and handle them in 
this block.

<cfset 
exception=GetException(Obj)>
<cfset
message=exception.GetERrorMessage(
)>

Get the exception data by calling the CFML 

GetException

 function and passing it the 

Obj object. Set the message variable to the 
string returned by the exception object’s 

GetErrorMessage

 method.

<cfoutput>

<br>The exception message is:

#message#<br>

</cfoutput>

Output the message string.

Code

Description

Summary of Contents for COLDFUSION 5-DEVELOPING

Page 1: ...Macromedia Incorporated Developing ColdFusion Applications MacroMedia ColdFusion 5 ...

Page 2: ...system or transmitted in any form or by any means electronic mechanical recording or otherwise without the prior written permission of Macromedia Incorporated ColdFusion HomeSite and Macromedia are registered trademarks of Macromedia Incorporation in the United States and internationally Allaire Spectra the Allaire Spectra logo Generator Macromedia Generation and JRun are trademarks of Macromedia ...

Page 3: ...to ColdFusion 1 A Quick Web Overview 2 Before You Begin 3 HTML 3 Relational database design and management 3 SQL 3 What is ColdFusion 4 Editions of ColdFusion 4 ColdFusion Features and Components 5 About the features 5 About the components 6 How ColdFusion Server Works 8 Chapter 2 Writing Your First ColdFusion Application 9 The Development Process 10 Working with ColdFusion Application Pages 10 Ab...

Page 4: ...ies 28 Query notes and considerations 29 Outputting Query Data 30 Query output notes and considerations 31 Getting Information About Query Results 32 Query properties notes and considerations 33 Using Query Results in Queries 34 Query of query benefits 34 Creating queries of queries 34 Performing a query on a query 35 Chapter 4 Retrieving and Formatting Data 39 Using Forms to Specify the Data to R...

Page 5: ...ance 67 Common graph characteristics 67 Setting bar and horizontal bar chart characteristics 68 Setting pie chart characteristics 71 Setting line and area graph characteristics 74 Linking Dynamically from Graphs 77 Chapter 6 Making Variables Dynamic 81 Dynamically Populating List Boxes 82 Creating Dynamic Check Boxes and Multiple Selection List Boxes 84 Check boxes 84 Multiple selection lists 86 E...

Page 6: ... an array with cfloop 121 Using nested loops for 2D and 3D arrays 122 Populating an array from a query 123 Array Functions 124 About Structures 125 Structure notation 126 Creating and Using Structures 127 Creating structures 127 Adding data elements to structures 127 Updating values in structures 128 Getting information about structures 129 Copying structures 130 Deleting structures 130 Structure ...

Page 7: ... edits are returned 156 Editing data in cfgrid 157 Updating the database with cfgridupdate 159 Updating the database with cfquery 160 Building Slider Bar Controls 164 Building Text Entry Boxes 165 Building Drop Down List Boxes 166 Embedding Java Applets 167 Registering a Java applet 167 Using cfapplet to embed an applet 169 Handling form variables from an applet 169 Chapter 10 Reusing Code 171 Way...

Page 8: ... information for an individual query 192 Error messages 192 CFML Code Validation 194 Runtime validation 194 The CFML syntax checker 194 Troubleshooting Common Problems 195 ODBC data source configuration 195 HTTP URL 195 CFML syntax errors 195 Error Handling in ColdFusion 197 Understanding ColdFusion errors 197 Generating Custom Error Messages with cferror 199 Creating an error application page 200...

Page 9: ...ng Client Variables 223 Setting up Client variable options 223 Using Client variables 224 Using Session Variables 228 Enabling Session variables 228 What is a session 228 Storing session data in Session variables 229 Standard Session variables 229 Getting a list of Session variables 230 Using Application Variables 230 Storing application data in Application variables 230 Application variable timeo...

Page 10: ...essions 263 Limiting input string size 264 Anchoring a regular expression to a string 264 Using Backreferences 265 Using backreferences in replacement strings 265 Returning Matched Subexpressions 266 Regular Expression Examples 267 Regular expressions in CFML 267 Chapter 15 Indexing and Searching Data 269 Searching a ColdFusion Web Site 270 Advantages of using Verity 270 Supported File Types 271 S...

Page 11: ...mail 303 Sample Uses of cfmail 304 Sending form based e mail 304 Sending query based e mail 304 Sending e mail to multiple recipients 305 Customizing E mail for Multiple Recipients 306 Attaching a MIME file 307 Advanced Sending Options 308 Sending mail as HTML 308 Error logging and undelivered messages 308 Receiving E mail Messages 309 Using cfpop 309 cfpop query variables 310 Handling POP Mail 31...

Page 12: ...s Across the Web with WDDX 345 An overview of distributed data for the Web 345 WDDX and Web Services 346 WDDX components 346 Working with application level data 347 Data exchange across application servers 347 How WDDX works 348 Converting CFML Data to a JavaScript Object 349 Transferring Data from Browser to Server 350 Storing Complex Data in a String 353 Chapter 19 Application Security 355 ColdF...

Page 13: ...ing to COM objects 374 Setting properties and invoking methods 375 Getting Started with CORBA 376 Calling CORBA Objects 376 Declaring structures and sequences 376 Exception handling 378 Calling Java Objects 378 Getting Started with Java 378 Java and Cold Fusion Data Type Conversions 381 Exception Handling 382 The class loading mechanism 384 A more complex Java example 385 Chapter 21 Building Custo...

Page 14: ...n 398 Using the debugging classes 399 Developing CFX Tags in C 401 Sample C CFXs 401 Setting up your C development environment 401 Using the Tag Wizard to create CFXs in C 401 Compiling C CFXs 402 Implementing C CFX tags 402 Debugging C CFXs 402 Registering CFXs 404 Distributing CFX Tags 405 Index 407 ...

Page 15: ...ers 20 through 23 explain how to extend ColdFusion s capabilities Because of the power and flexibility of ColdFusion you can create many different types of Web applications of varying complexity As you become more familiar with the material presented in this manual and begin to develop your own applications you will want to refer to the CFML Reference for details about various tags and functions C...

Page 16: ...ng table lists the new features in ColdFusion 5 Benefit Feature Description Breakthrough productivity User defined functions Create reusable functions to accelerate development Query of queries Easily integrate data from heterogeneous sources by merging and querying data in memory using standard SQL Server analysis and troublshooting Quickly detect and diagnose server errors with built in server r...

Page 17: ...ivity using new drivers Easy managment Application deployment services Effortlessly and reliably deploy archive or restore entire applications using ColdFusion archive files Enhanced application monitoring Keep track of server performance and availability with customizable alerts and recovery SNMP support Monitor ColdFusion applications from enterprise management systems Expanded integration Expan...

Page 18: ...ss to experienced ColdFusion developers through participation in the Online Forums where you can post messages and read replies on many subjects relating to ColdFusion http forums coldfusion com spectraconf Installation Support Support for installation related issues for all Macromedia products www coldfusion com support installation Professional Education Information about classes on site trainin...

Page 19: ...http localhost coldfusion docs AcrobatDocs index htm Book Description Installing and Configuring ColdFusion Server Describes system installation and basic configuration for Windows NT Windows 2000 Solaris Linux and HP UX Advanced ColdFusion Server Administration Describes how to connect your data sources to the ColdFusion Server configure security for your applications and how to use ClusterCATS t...

Page 20: ...learning ColdFusion but it is also a great place to see the ColdFusion developer community in action Contacting Macromedia Corporate headquarters Macromedia Inc 600 Townsend street San Francisco CA 4103 Tel 415 252 2000 Fax 415 626 0554 Web www macromedia com Technical support Macromedia offers a range of telephone and Web based support options Go to http www coldfusion com support for a complete ...

Page 21: ...en 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 4 ColdFusion Features and Components 5 How ColdFusion Server Works 8 ...

Page 22: ...rnal business processes For example a static HTML page allows a bookstore to publish its location list services such as the ability to place special orders and advertise upcoming events like book signings A dynamic site for the same bookstore allows customers to order books online write reviews of books they read and even get suggestions for purchasing books based on their reading preferences Cold...

Page 23: ...esign and management If you plan on creating applications that use data from existing data sources you should understand how the data is organized In most cases this means understanding how tables are organized to prevent unnecessary duplication of data For example if you have data about employees rather than repeating the department number and name in each employee s record you most likely have a...

Page 24: ...tic HTML pages in the following ways They are saved and referenced with a specific file extension The default ColdFusion file extension is cfm They contain ColdFusion Markup Language Editions of ColdFusion There are two editions of ColdFusion Enterprise and Professional Using ColdFusion Enterprise or Professional Edition and ColdFusion Studio you can build Web applications that leverage existing t...

Page 25: ... intuitive Two way visual programming and database tools Remote interactive debugging for quickly identifying and fixing problems Web application wizards to automate common development tasks Source control integration to enable team development Secure file and database access using HTTP for remote development A tag based component architecture for flexible code reuse Scalable deployment A multithr...

Page 26: ...e much more dynamic and powerful They are the functional parts of a ColdFusion application including the user interface pages and forms that handle Open integration Database connectivity using native database drivers Enterprise Edition only ODBC or OLE DB Embedded support for full text indexing and searching Standards based integration with directory mail HTTP FTP and file servers Connectivity to ...

Page 27: ...pplication pages It runs as a service under Windows NT and as a process under UNIX For information on installing and configuring ColdFusion Server see Installing and Configuring ColdFusion Server ColdFusion Administrator You use the Administrator to configure various ColdFusion Server options including ColdFusion data sources Debugging output Server settings Application security Server clustering ...

Page 28: ...erver processes the request retrieves any data if necessary and routes the data through the Web server back to your browser The following steps describe in more detail what happens when you open a ColdFusion page 1 The client requests a page that contains CFML tags 2 The Web server passes files to ColdFusion Server if a page request contains a ColdFusion file extension 3 ColdFusion Server scans th...

Page 29: ...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 13 Development Considerations 16 ...

Page 30: ...icaton pages From a coding perspective the major difference between a static HTML page and a ColdFusion application page is that ColdFusion pages contain ColdFusion Markup Language CFML CFML is a markup language that is very similar in syntax to HTML so Web developers find it intuitive Unlike HTML which defines how things are displayed and formatted on the client CFML identifies specific operation...

Page 31: ... save the page 1 Select File Save 2 Save your page as calldept cfm in myapps under the Web root directory For example the directory path on your machine might be on Windows NT c inetpub wwwroot myapps on UNIX mywebserverdocroot myapps Viewing application pages You view the application page on the Web server to ensure that the code is working as expected Presently your page is very simple But as yo...

Page 32: ...er html head title Call Department title head body strong Call Department strong br Set all variables cfset department Sales Display results cfoutput I d like to talk to someone in Department cfoutput body html html head title Call Department title head body strong Call Department strong br I d like to talk to someone in Sales body html Code Description Set all variables CFML comment which is not ...

Page 33: ...resents a string a number a Boolean value Yes No a date and time or a more complex object such as an array or structure ColdFusion automatically uses the appropriate internal data representation when you assign its value However ColdFusion does provide methods to examine and change the type of data that a variable represents For a complete list of data types see the CFML Reference For example use ...

Page 34: ...utput and cfquery tag blocks You do not need to use pound signs when you create a variable assign it a value or use it in a ColdFusion expression or as a parameter in a ColdFusion function Note Remember that ColdFusion cannot interpret anything including variables that is not inside a ColdFusion tag or tag block The following table illustrates the basic use of pound signs For a detailed descriptio...

Page 35: ...3 Save the file cfoutput I d like to talk to someone in Department cfoutput ColdFusion replaces the variable Department with its value The HTML page displays I d like to talk to someone in Sales cfoutput The department name spelled backward is Reverse Department cfoutput ColdFusion sees Reverse Department as text and displays it unchanged The HTML page displays The department name spelled backward...

Page 36: ... Comment your code as you go HTML comments use this syntax html comment CFML comments add an extra dash cfml comment ColdFusion removes CFML comments from the HTML that it sends to the browser so users do not see them if they view the HTML source ColdFusion does send HTML comments to the browser Filenames should be all one word begin with a letter and can contain only letters numbers and the under...

Page 37: ...a data source and enable debugging use the cfquery tag to query a data source and use the cfoutput tag to output the query results to a Web page Contents Publishing Dynamic Data 18 Understanding Database Basics 19 Understanding Data Sources 20 Accessing Data Sources 21 Retrieving Data 25 Writing SQL 26 Building Queries 28 Outputting Query Data 30 Getting Information About Query Results 32 Using Qu...

Page 38: ...of structured content accessible locally or across a network You can query Web sites LDAP servers POP mail servers and documents in a variety of formats Most commonly though a database drives your applications and for this discussion a data source means the entry point from ColdFusion to a database In this chapter you build a query to retrieve data from the CompanyInfo data source which accesses a...

Page 39: ...n the names street addresses and phone numbers of individuals Think of a table as a grid of columns and rows In this case one column contains names a second column contains street addresses and the third column contains phone numbers Each row constitutes one data record In this case each row is unique because it applies to one individual Rows are also referred to as records Columns are also referr...

Page 40: ...es the changing data needs within an organization The best way to familiarize yourself with the capabilities of your database product or database management system DBMS is to review the product documentation Understanding Data Sources A database is a file or server that contains a collection of data A data source defines the properties which ColdFusion uses to connect to a specific database You ad...

Page 41: ...ng Data Sources There are two ways to access data sources Add data sources in the ColdFusion Administrator You assign a data source name and set all the information required to establish an ODBC connection You then use the data source name in any CFML tags that establish database connections This technique puts all the information about a ColdFusion Server s database connections in a single easy t...

Page 42: ...ples in this book Note By default the ColdFusion setup installs the CompanyInfo and cfsnippets databases used in examples in this book and adds them to the available ODBC data sources Therefore this procedure should not be necessary to work with examples in this book To add a data source 1 Start the ColdFusion Administrator On Windows select Start Programs ColdFusion Server ColdFusion Administrato...

Page 43: ...ee this message The connection to the data source was verified successfully 11 Click Go Back to return to the data sources list For more information about managing data sources see Advanced ColdFusion Administration Specifying a connection string You can dynamically override ODBC connection information that you set in the ColdFusion Administrator You can also specify connection attributes that are...

Page 44: ...fying data sources dynamically To specify a data source dynamically use the following attribute in the cfquery tag dbtype dynamic Specify all the required ODBC connection information including the ODBC driver and the database location in the connectstring attribute For example you could use the following code for a query that dynamically specifies the pubs database on a local Microsoft SQLServer c...

Page 45: ...nclosed within the block Returns result set values to the page in a special kind of variable called a query object You specify the query object s name in the cfquery tag s name attribute Often we refer to the query object simply as the query The cfquery tag syntax cfquery name EmpList datasource CompanyInfo You ll type SQL here cfquery In this example the query code tells ColdFusion to Use the Com...

Page 46: ...L statements by graphically selecting the tables and records within those tables that you want to retrieve When the database processes the SQL it creates a data set a structure containing the requested data that is returned to ColdFusion Server ColdFusion places the data set in memory and assigns it the name that you defined for the query in the name attribute of the cfquery tag You can reference ...

Page 47: ... reference must exist in order to perform a successful query 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 Operator Description AND Both conditions must be met OR At least one condition must be met NOT Exclude ...

Page 48: ...l head title Employee List title head body h1 Employee List h1 cfquery name EmpList datasource CompanyInfo SELECT FirstName LastName Salary Contract FROM Employee cfquery body html 3 Save the page as emplist cfm in myapps under the Web root directory For example the directory path on your machine might be C INETPUB WWWROOT myapps on Windows NT 4 Return to your browser and enter the following URL t...

Page 49: ...use the dbtype dynamic and queryString attributes to dynamically specify a database The SQL that you write is sent to the database and performs the actual data retrieval Columns and tables that you refer to in your SQL statement must exist otherwise the query will fail Reference the query data by naming the query in one of the presentation tags such as cfoutput cfgrid cftable cfgraph or cftree lat...

Page 50: ... the Firstname column in the Emplist query as either Emplist Firstname or just Firstname The cfoutput tag accepts a variety of optional attributes but ordinarily you use the query attribute to define the name of an existing query To output query data on your page 1 Return to empList cfm in ColdFusion Studio 2 Edit the file so that it appears as follows html head title Employee List title head body...

Page 51: ...ttribute you can optionally prefix the query variables with the name of the query for example Emplist FirstName As with other attributes surround the query attribute value with double quotes As with any variables that you reference for output surround column names with pound signs to tell ColdFusion to output the column s current values Add a br tag to the end of the variable references so that Co...

Page 52: ...ract FROM Employee cfquery cfoutput query EmpList FirstName LastName Salary Contract br cfoutput br cfoutput The query returned EmpList RecordCount records cfoutput body html 3 Save the file as emplist cfm 4 View the page in a browser The number of employees now appears below the list of employees Note The variable cfquery executionTime contains the amount of time in milliseconds it took for the q...

Page 53: ...round the query property reference with pound signs so that ColdFusion knows to replace the property name with its current value Do not use the cfoutput tag query attribute when you output the RecordCount or ColumnList property If you do you will get one copy of the output for each row Instead prefix the property with the name of the query Code Description cfoutput Display what follows The query r...

Page 54: ...y a database once and then use the results to generate several different summary tables For example if you need to summarize the total salary by department by skill and job you can make one query to the database and use its results in three separate queries to generate the summaries You can make drill down master detail like functionality where you do not go to the database for the details For exa...

Page 55: ... page request and does not query the database again until the specified time expires Note that you must use the CreateTimeSpan function to specify the cachedwithin attribute value Note You cannot add a literal value as a column to the SELECT list in a query of queries Your query generates a new query results set identified by the value of the name attribute The following example illustrates the us...

Page 56: ...Query using query results cfquery dbtype query name QueryFromQuery SELECT Emp_ID FirstName LastName FROM EmpList WHERE LastName LastNameSearch cfquery Output using a query of query br cfoutput query QueryFromQuery Emp_ID FirstName LastName br cfoutput br Columns in the Emplist database query br cfoutput Emplist columnlist br cfoutput br Columns in the QueryFromQuery query br cfoutput QueryFromQuer...

Page 57: ...Cache the query data between requests to this page and do not query the database if the cached data is less than an hour old cfquery dbtype query name QueryFromQuery SELECT Emp_ID FirstName LastName FROM Emplist WHERE LastName LastNameSearch cfquery Use the EmpList query as the source of the data in a new query This query selects only entries that match the last name specified by the LastNameSearc...

Page 58: ...38 Chapter 3 Querying a Database ...

Page 59: ...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 40 Working with Action Pages 45 Working with Queries and Data 49 Returning Results to the User 55 ...

Page 60: ...called an action page where some type of processing takes place Note Because forms are standard HTML the syntax and examples that follow provide you with just enough detail to begin using ColdFusion form tag syntax Use the following syntax for the create a form tag form action actionpage cfm method post form You can override the server request timeout set on the ColdFusion Administrator Server Set...

Page 61: ...ld provide The following table illustrates the format of form control tags Control Code Text control input type Text name ControlName size Value maxlength Value Radio buttons input type Radio name ControlName value Value1 DisplayName1 input type Radio name ControlName value Value2 DisplayName2 input type Radio name ControlName value Value3 DisplayName3 List box select name ControlName option value...

Page 62: ... br Last Name input type Text name LastName size 20 maxlength 35 br Salary input type Text name Salary size 10 maxlength 10 p list box p City select name City option value Arlington Arlington option value Boston Boston option value Cambridge Cambridge option value Minneapolis Minneapolis option value Seattle Seattle select p radio buttons p Department br input type radio name Department value Trai...

Page 63: ...he highlighted code and its function Code Description form action actionpage cfm method post Gather the information from this form using the Post method and do something with it on the page actionpage cfm input type Text name FirstName size 20 maxlength 35 Create a text box called FirstName where users can enter their first name Make it 20 characters wide but allow input of up to 35 characters inp...

Page 64: ... populate drop down select lists using query data See Dynamically Populating List Boxes on page 82 for details select name City option value Arlington Arlington option value Boston Boston option value Cambridge Cambridge option value Minneapolis Minneapolis option value Seattle Seattle select Create a drop down list box named City and populate it with the values Arlington Boston Cambridge Minneapo...

Page 65: ...x them with Form to explicitly tell ColdFusion that you are referring to a form variable For example the following code references the LastName form variable for output on an action page cfoutput Form LastName cfoutput Dynamically generating SQL statements As you have already learned you can retrieve a record for every employee in a database table by composing a query like this cfquery name GetEmp...

Page 66: ...yee Data Based on Criteria from Form title head body cfquery name GetEmployees datasource CompanyInfo SELECT FirstName LastName Salary FROM Employee WHERE LastName Form LastName cfquery h4 Employee Data Based on Criteria from Form h4 cfoutput query GetEmployees FirstName LastName Salary br cfoutput br cfoutput Contractor Form Contractor cfoutput body html 3 Save the page as actionpage cfm within t...

Page 67: ...name GetEmployees datasource CompanyInfo Query the data source CompanyInfo and name the query GetEmployees SELECT FirstName LastName Salary FROM Employee WHERE LastName Form LastName Retrieve the FirstName LastName and Salary fields from the Employee table but only if the value of the LastName field matches what the user entered in the LastName text box in the form on formpage cfm cfoutput query G...

Page 68: ...oldFusion Administrator The Administrator debugging information shows which variables are being passed to your application pages Form variable notes and considerations When using form variables keep the following guidelines in mind A Form variable s scope is the action page Prefix form variables with Form when referencing them on the action page Surround variable values with pound signs for output...

Page 69: ...s to specify how the results of a query appear on a page To do so you put the cfoutput tag inside the table tags You can also use the HTML th tag to put column labels in a header row To create a row in the table for each row in the query results put the tr block inside the cfoutput tag To put the query results in a table 1 Return to the file actionpage cfm in ColdFusion Studio 2 Modify the page so...

Page 70: ...rmat number To change the format of the Salary 1 Open the file actionpage cfm in ColdFusion Studio 2 Change the line td Salary td to td DollarFormat Salary td Code Description table Put data into a table tr th First Name th th Last Name th th Salary th tr In the first row of the table include three columns with the headings First Name Last Name and Salary cfoutput query GetEmployees Get ready to d...

Page 71: ... that column that contains AL Surround strings in SQL statements with single quotes To return information from the Departmt table on all departments except the sales department you would build a query that looks like this cfquery name GetDepartments datasource CompanyInfo SELECT FROM Departmt WHERE Dept_Name NOT LIKE Ss ales cfquery The first character in the match can be either upper case S or lo...

Page 72: ...wing criteria joins the two tables Departmt Dept_ID Employee Dept_ID It ensures that each row of the query results contains the department name from the Departmt table that corresponds to the Department ID in this employee s row in the Employee table Without this statement the query returns a row for every employee in the Employee table and all rows have the Dept_Name HR even if the employee is no...

Page 73: ...t_Name Employee FirstName Employee LastName Employee StartDate Employee Salary FROM Departmt Employee WHERE Departmt Dept_ID Employee Dept_ID cfif IsDefined FORM Department AND Departmt Dept_Name Form Department cfif cfif Form LastName IS NOT AND Employee LastName Form LastName cfif cfquery h4 Employee Data Based on Criteria from Form h4 table tr th First Name th th Last Name th th Salary th tr cf...

Page 74: ...the Dept_ID field in each table cfif IsDefined FORM Department AND Departmt Dept_Name Form Department cfif If the user specified a department on the form only retrieve records where the department name is the same as the one the user specified Note that you need the pound signs in the SQL AND statement to identify Form Department as a ColdFusion variable but not in the IsDefined function cfif Form...

Page 75: ...tEmployees query insert the following code before displaying the data cfif GetEmployees RecordCount IS 0 No records match your search criteria BR cfelse You mst do the following Prefix RecordCount with the query name Add a procedure after the cfif tag that displays a message to the user Add a procedure after the cfelse tag to format the returned data Follow the second procedure with a cfif tag end...

Page 76: ...s allows you to give the user quick feedback when it takes a long time to complete processing a request For example you can use cfflush to display the message Processing your request please wait when a request takes time to return You can also use it to incrementally display a long list as it gets retrieved The first time you use the cfflush tag on a page it sends to the browser all of the HTML he...

Page 77: ...es the cfloop tag and the rand random number generating function to artificially delay the generation of data for display It simulates a situation in which it takes time to retrieve the first data and additional information becomes available slowly html head title Your Magic numbers title head body H1 Your Magic numbers H1 P It will take us a little while to calculate your ten magic numbers It tak...

Page 78: ... 1 to 200000 step 1 cfset random Rand cfloop Insert an artificial delay by using the Rand function to calculate many random numbers cfloop index Myindex from 1 to 10 step 1 cfloop index randomindex from 1 to 100000 step 1 cfset random rand cfloop cfoutput Magic number number Myindex is nbsp nbsp RandRange 100000 999999 br br cfoutput cfloop Generate and display ten random numbers This code uses tw...

Page 79: ...ways that you can graph data and gives you the tools you need to create effective graphs The cfgraph tag requires the JRun server and the Macromedia Generator server which install with ColdFusion Contents Creating a Graph 60 Graphing Data 62 Controlling Graph Appearance 67 Linking Dynamically from Graphs 77 ...

Page 80: ...arge number of attributes let you customize the graph appearance to meet your needs Graph types You can create the following types of graphs Bar Horizontal bar Line Area a line graph with the area below the line filled in Pie The following illustrations show one sample of each type of graph ...

Page 81: ... resulting graph looks like this Later sections in this chapter provide information on how you can specify the data differently and how you can change and enhance graph appearance Attribute Description type Must be one of the following values bar horizontalbar pie or line An area graph is a kind of line graph query The query containing the data valueColumn The query column containing the values to...

Page 82: ...is empty However you must still provide the cfgraph end tag For example a simple cfgraph tag for a bar chart might look like this cfgraph type bar title Salaries by Department query DataTable itemColumn Dept_Name valueColumn AvgByDept cfgraph This tag displays the values in the AvgByDept column of the DataTable query It displays the Dept_Name column value as the item label by each bar The title Sa...

Page 83: ...panyInfo SELECT Departmt Dept_Name Employee Salary FROM Departmt Employee WHERE Departmt Dept_ID Employee Dept_ID cfquery URL 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 Use this attribute to ...

Page 84: ...DeptSalaries AvgByDept i 1000 1000 cfloop html head title Employee Salary Analysis title head body h1 Employee Salary Analysis h1 Bar graph from DeptSalaries Query of Queries cfgraph type bar query DeptSalaries valueColumn AvgByDept itemColumn Dept_Name cfgraph br body html 3 Save the page as graphdata cfm in myapps under the Web root directory For example the directory path on your machine might ...

Page 85: ...he Salary is in the Employee table you need a table join in the WHERE clause The raw results of this query could be used elsewhere on the page cfquery dbtype query name DeptSalaries SELECT Dept_Name AVG Salary AS AvgByDept FROM GetSalaries GROUP BY Dept_Name cfquery Generate a new query from the GetSalaries query Use the AVG aggregating function to get statistical data on the employees Use the GRO...

Page 86: ...ft on a bar chart the data from a query For example if the database is missing data for one department you can add the information manually cfgraph type bar title Salaries by Department query DataTable itemColumn Dept_Name valueColumn AvgByDept cfgraphdata item Facilities value 35000 cfgraph Attribute Description value The data value to be graphed item Optional The description for this data point ...

Page 87: ...including the legend and background area around the graph You cannot use these attributes to change the ratio of the data area height to width For example you cannot set a large graphWidth value to stretch just the horizontal dimension To change the overall graph size specify both the graphHeight and graphWidth Background backgroundColor The background color to use for the entire graph area includ...

Page 88: ...axis scaleFrom scaleTo The minimum and maximum points on the data axis vertical axis for bar charts horizontal axis for horizontal bar charts By default the minimum is 0 and the maximum is the largest data value Grid lines gridLines The number of grid lines between the top and bottom of the graph The value of each grid line appears along the value axis The cfgraph tag displays horizontal grids onl...

Page 89: ...ation horizontal colorList red orange green teal purple gridLines 4 barSpacing 15 cfgraph 3 Save the page Data point colors colorList A comma separated list of colors to use for 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 These colors replace the standard sys...

Page 90: ...hadow scaleTo 100000 Set the maximum value of the vertical axis to 100000 The minimum value is the default 0 itemLabelSize 16 Make the labels on the horizontal axis 16 points itemLabelOrientation horizontal Make the labels horizontal on the horizontal axis colorList red orange green teal purple Get the bar colors from a custom list In this example the graph does not use purple because there are on...

Page 91: ...A legend relating the pie slice colors to the data point Item descriptions from the itemColumn attribute or cfgraphdata tag itemColumn attribute By default the legend appears to the left of the chart You can also specify above below right and none You can specify the font type as Arial the default Courier or Times Data point colors colorList A comma separated list of colors to use for each bar You...

Page 92: ...usands cfloop index i from 1 to DeptSalaries RecordCount cfset DeptSalaries SumByDept i Round DeptSalaries SumByDept i 1000 1000 cfset DeptSalaries AvgByDept i Round DeptSalaries AvgByDept i 1000 1000 cfloop 3 Add the following cfgraph tag before the end of the body Pie graph from DeptSalaries Query of Queries cfgraph type pie query DeptSalaries valueColumn SumByDept itemColumn Dept_Name title Tot...

Page 93: ...ry itemColumn Dept_Name Use the contents of the Dept_Name column for the item labels displayed in the chart legend title Total Salaries by Department titleFont Times Put a title above the graph Format it in Times font showvalue rollover valueLabelFont Times Display the data value in Times font only when the user points to a pie slice borderWidth 0 Do not put a border around the chart backgroundCol...

Page 94: ...emLabelSize itemLabelOrientation Labels to show on the horizontal axis of the chart By default item labels are on if you specify an itemColumn or for cfgraphdata tags item attribute You can specify the label font type Arial Courier or Times point size and orientation horizontal or vertical Line characteristics lineColor lineWidth These attributes specify the line format For the line color you can ...

Page 95: ...atePart yyyy GetSalaries StartDate i 9999 cfloop Query of Queries for average salary by start year cfquery dbtype query name HireSalaries SELECT StartDate AVG Salary AS AvgByStart FROM GetSalaries GROUP BY StartDate cfquery Round average salaries to thousands cfloop index i from 1 to HireSalaries RecordCount cfset HireSalaries AvgByStart i Round HireSalaries AvgByStart i 1000 1000 cfloop 4 Add the...

Page 96: ...Y StartDate cfquery Create a second query from the GetSalaries query This query contains the average salary for each start year cfloop index i from 1 to HireSalaries RecordCount cfset HireSalaries AvgByStart i Round HireSalaries AvgByStart i 1000 1000 cfloop Round the salaries to the nearest thousand cfgraph type line query HireSalaries valueColumn AvgByStart itemColumn StartDate Create a line gra...

Page 97: ...L attribute In the URL attribute include the name of a parameter but not its value in the form ParameterName In the URLColumn attribute specify a query column that contains the value of the parameter being passed In the target page determine the data to be displayed based on the parameter that gets passed The example code in the following procedure illustrates this technique Example dynamically li...

Page 98: ... Salary Details cfoutput h1 table border cellspacing 0 cellpadding 5 tr th Employee Name td th StartDate td th Salary td th Contract td tr cfoutput query GetSalaryDetails tr td FirstName LastName td td dateFormat StartDate mm dd yyyy td td numberFormat Salary 999 999 td td Contract td tr cfoutput table body html 3 Save the page as Salary_details cfm in myapps under the Web root directory ...

Page 99: ... FROM Departmt Employee WHERE Departmt Dept_Name URL Dept_Name AND Departmt Dept_ID Employee Dept_ID ORDER BY Employee LastName Employee Firstname cfquery Get the salary data for the department whose name was passed in the URL parameter string Sort the data by the employee s last and first names table border cellspacing 0 cellpadding 5 tr th Employee Name td th StartDate td th Salary td th Contrac...

Page 100: ...fm Click the slices of the pie chart Reviewing the code The following table describes the highlighted code and its function Code Description URL Salary_Details cfm Dept_Name When the user clicks a data point call the Salary_Details cfm page in the current directory and pass it the parameter named Dept_Name The parameter value must come from the URLColumn attribute URLColumn Dept_Name Complete the ...

Page 101: ... It also discusses ways to make sure that variables exist and have valid data because this information is important to effectively use dynamic data Contents Dynamically Populating List Boxes 82 Creating Dynamic Check Boxes and Multiple Selection List Boxes 84 Ensuring that Variables Exist 88 Validating Data Types 90 Dynamic SQL 96 ...

Page 102: ... form control To dynamically populate a list box 1 Open the file formpage cfm in ColdFusion Studio 2 Modify the file so that it appears as follows html head title Input form title head body cfquery name GetDepartments datasource CompanyInfo SELECT DISTINCT Location FROM Departmt cfquery Define the action page in the form tag The form variables will pass to this page when the form is submitted form...

Page 103: ...rmpage cfm in a browser The changes that you just made appear in the form Remember that you need an action page to submit values Reviewing the code The following table describes the highlighted code and its function Code Description cfquery name GetDepartments datasource CompanyInfo SELECT DISTINCT Location FROM Departmt cfquery Get the locations of all departments in the Departmt table The DISTIN...

Page 104: ...he form field For more information see the Ensuring that Variables Exist and Dynamic SQL sections later in this chapter Check boxes When you put a series of check boxes with the same name in an HTML form the variable that is created contains a comma delimited list of values The values can be either numeric values or alphanumeric strings These two types of values are treated slightly differently Se...

Page 105: ... database field containing string values instead of numeric you must modify the checkbox and cfquery syntax The first example searched for department information based on a numeric primary key field called Dept_ID Suppose instead that the primary key is a database field called Dept_Name that contains string values In that case your code for check boxes should look like this input type checkbox nam...

Page 106: ...er for example a list box could contain the four entries Training Marketing HR and Sales If the user selects Marketing and Sales the form field variable value is Marketing Sales You use multiple selection lists to search a database in the same way that you use check boxes Searching numeric values Suppose you want the user to select departments from a multiple selection list box The query retrieves...

Page 107: ...ning Training option value Marketing Marketing option value HR HR option value Sales Sales select If the user selects the Marketing and Sales items the SelectDepts form field value is Marketing Sales Just as you did when using check boxes to search database fields containing string values use the ColdFusion ListQualifyfunction with multiple selection list boxes SELECT FROM Departmt WHERE Dept_Name...

Page 108: ...fparam name VariableName type data_type default DefaultValue Note For information on using the type attribute to validate the parameter data type see the Using cfparam to validate the data type section of this chapter There are two ways to use the cfparam tag to test for variable existence depending on how you want the validation test to proceed With only the name attribute to test that a required...

Page 109: ...tion page could have the following code to ensure that a SelectDepts variable exists cfparam name Form SelectedDepts default Marketing Sales Requiring users to enter values in form fields One of the limitations of HTML forms is the inability to define input fields as required Because this is a particularly important requirement for database applications ColdFusion provides a server side mechanism ...

Page 110: ...rs Note The data validation discussed in this chapter is done by the ColdFusion Server Validation using cfform tags is done using JavaScript in the user s browser before any data is sent to the server Using cfparam to validate the data type The cfparam type attribute lets you validate the type of a parameter You can specify that the parameter type must be any of the following values For example yo...

Page 111: ... a form page and its action page Because the only action is to display the values of the two variables that you enter the action is on the same page as the form Field Suffix Value Attribute Description _integer Custom error message Verifies that the user entered a number If the user enters a floating point value it is rounded to an integer _float Custom error message Verifies that the user entered...

Page 112: ...atest cfm method Post input type hidden name StartDate_required value You must enter a start date input type hidden name StartDate_date value Enter a valid date as the start date input type hidden name Salary_required value You must enter a salary input type hidden name Salary_float value The salary must be a number Start Date input type text name StartDate size 16 maxlength 16 br Salary input typ...

Page 113: ...npage cfm method post Gather the information from this form using the Post method and do something with it on the page dataform cfm which is this page input type hidden name StartDate_required value You must enter a start date input type hidden name StartDate_date value Enter a valid date as the start date Require input into the StartDate input field If there is no input display the error informat...

Page 114: ...SQL statement substitution variable For more information on cfqueryparam and its use see the CFML Reference The cfqueryparam tag can have any of several additional advantages depending on the database system and Web server software that you are using Some Web servers have security issues in which SQL appended to URL strings can evade system security cfqueryparam can help prevent this problem Some ...

Page 115: ...yparam Example title head body h3 cfqueryparam Example h3 cfset course_id 12 cfquery name getFirst datasource cfsnippets SELECT FROM courses WHERE Course_ID cfqueryparam value Course_ID cfsqltype CF_SQL_INTEGER cfquery cfoutput query getFirst p Course Number number br Description descript p cfoutput body html Reviewing the code The following table describes the code and its function Code Descripti...

Page 116: ...fif cfelse cfelseif tags to control how the SQL statement is constructed for example cfquery name queryname datasource datasourcename Base SQL statement s cfif value operator value additional SQL statement s cfif cfquery The following code creates an application that lets a user search the CompanyInfo database for employees by first name last name minimum salary contract status or any combination ...

Page 117: ...mployees datasource CompanyInfo SELECT FirstName LastName Salary Contract FROM Employee cfquery define the action page in the form tag The form variables will pass to this page when the form is submitted form action getemp cfm method post text box p First Name input type Text name FirstName size 20 maxlength 35 br Last Name input type Text name LastName size 20 maxlength 35 br Salary input type Te...

Page 118: ... title Get Employee Data title head body cfquery name GetEmployees datasource CompanyInfo SELECT FROM Employee WHERE cfif form firstname is not Employee FirstName LIKE form FirstName AND cfif cfif form lastname is not Employee LastName LIKE form LastName AND cfif cfif form salary is not Employee Salary form Salary AND cfif cfif isdefined Form Contract Employee Contract Yes AND cfelse Employee Cont...

Page 119: ...ions cfif Form FirstName is not Employee FirstName LIKE form FirstName AND cfif If the user entered anything in the FirstName text box in the form add AND Employee FirstName LIKE what the user entered in the FirstName text box to the SQL statement You can use the FirstName variable without ensuring its existence because text boxes pass an empty string if you do not enter text cfif Form LastName is...

Page 120: ...tence of the Form Contract variable is needed because the variable only exists if they select the Contractor box 0 0 If none of the conditions are true the 0 0 statement ensures that the WHERE clause does not result in a SQL syntax error Instead the SELECT statement returns the entire table Putting this statement at the end of the WHERE clause improves security by making it harder to attach extra ...

Page 121: ...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 ...

Page 122: ...ert form The following procedure creates a form using standard HTML tags To create an insert form 1 Create a new application page in ColdFusion Studio 2 Edit the page so that it appears as follows html head title Insert Data Form title head body H2 Insert Data Form H2 form action insertaction cfm method post Employee ID input type text name Emp_ID size 4 maxlength 4 br First Name input type Text n...

Page 123: ...to specify the fields you want to insert Creating an action page to insert data You can use the cfinsert tag or cfquery tag to create an action page that inserts data into a database Creating an insert action page with cfinsert The cfinsert tag is the easiest way to handle simple inserts from either a cfform or an HTML form This tag inserts data from all the form fields with names that match datab...

Page 124: ...field validation functions for these fields to display a custom error message Code Description cfif not isdefined Form Contract cfset Form contract No cfif If the user clears the Contractor check box no value gets passed to the action page The database field must have a value so check the Form contract variable and set it to No if it is not defined cfinsert datasource CompanyInfo tablename Employe...

Page 125: ... 3 Enter the following code Make the contract variable be No if it is not set check box is empty cfif not isdefined Form Contract cfset form contract No cfif Insert the new record cfquery name AddEmployee datasource CompanyInfo INSERT INTO Employee VALUES Form Emp_ID Form FirstName Form LastName Form Dept_ID Form StartDate Form Salary Form Contract cfquery html head title input form title head bod...

Page 126: ...bination of fields in a database table that uniquely identifies each record in the table For example in a table of employee names and addresses only the Emp_ID would be unique to each record An update form is usually populated with existing record data because the form s purpose is to update data The easiest way to designate the primary key in an update form is to include a hidden input field with...

Page 127: ...rstName value FirstName br Last Name input type text name LastName value LastName br Department Number input type text name Dept_ID value Dept_ID br Start Date input type text name StartDate value StartDate br Salary input type text name Salary value Salary br Contractor cfif Contract IS Yes input type checkbox name Contract checked Yes br cfelse input type checkbox name Contract Yes br cfif br in...

Page 128: ...ame value FirstName br Last Name input type text name LastName value LastName br Department Number input type text name Dept_ID value Dept_ID br Start Date input type text name StartDate value StartDate br Salary input type text name Salary value Salary br Populate the fields of the update form This example does not use any ColdFusion formatting functions to clean up the form As a result the start...

Page 129: ...en uses the remaining form fields that are submitted to update the corresponding fields in the record Your form only needs to have fields for the database fields that you want to change To create an update page with cfupdate 1 Create a new application page in ColdFusion Studio 2 Enter the following code cfif not isdefined Form Contract cfset form contract No cfelse cfset form contract Yes cfif cfu...

Page 130: ...me Form LastName Dept_ID Form Dept_ID StartDate Form StartDate Salary Form Salary WHERE Emp_ID Form Emp_ID cfquery Code Description cfif not isdefined Form Contract cfset Form contract No cfelse cfset form contract Yes cfif If the user clears the Contractor check box no value gets passed to the action page Also the database field must have a value of Yes or No Test the Form contract variable and s...

Page 131: ...Employee table and the message displays Reviewing the code The following table describes the highlighted code and its function Code Description cfquery name UpdateEmployee datasource CompanyInfo UPDATE Employee SET FirstName Form Firstname LastName Form LastName Dept_ID Form Dept_ID StartDate Form StartDate Salary Form Salary WHERE Emp_ID Form Emp_ID cfquery Update the record in the database that ...

Page 132: ...it is not used so you can use a table to display the record to be deleted instead To delete one record from a database 1 Open the file updateform cfm in ColdFusion Studio 2 Change the title to Delete Form and the text on the submit button to Delete Record 3 Change the form tag so that it appears as follows form action deleteaction cfm method Post 4 Save the modified file as deleteform cfm 5 Create...

Page 133: ...has Dept_ID number 4 from the Employee table DELETE FROM Employee WHERE Dept_ID 4 To delete all the records from the Employee table you use the following code DELETE FROM Employee Note Deleting records from a database is not reversible Use DELETE statements carefully Code Description cfquery name DeleteEmployee datasource CompanyInfo DELETE FROM Employee WHERE Emp_ID Form Emp_ID cfquery Delete the...

Page 134: ...114 Chapter 7 Updating Your Database ...

Page 135: ...es 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 Contents About Arrays 116 Basic Array Techniques 118 Populating Arrays with Data 121 Array Functions 124 About Structures 125 Creating and Using Structures 127 Structure Functions 133 ...

Page 136: ...tents in an array This allows you to make changes easily without committing the information which the user can change before completing the transaction to a database Conventional fixed size 2D array A 2D array is like a cube made up of individual cells as the following figure shows ColdFusion arrays differ somewhat from traditional arrays because they are dynamic For example in a conventional arra...

Page 137: ...scussions of ColdFusion arrays Array dimension The relative complexity of the array structure Index The position of an element in a dimension ordinarily surrounded by square brackets my1Darray 1 my2Darray 1 1 my3Darray 1 1 1 Array element Data stored in an array index The syntax my2darray 1 3 Paul is the same as saying My2dArray is a two dimensional array and the value of the array element index 1...

Page 138: ... ArrayLen firstname temp 3 If you remove data from an array the array resizes dynamically Use the ArrayDeleteAt function to delete data from the array at a particular index rather than set the data value to 0 or the empty string cfset temp ArrayDeleteAt firstname 2 Charlie has been removed from the array cfoutput The firstname array is ArrayLen firstname indexes in length cfoutput Now the array ha...

Page 139: ...ut you can also use a number of array functions to add data to an array You can use the following functions When you insert an array index with ArrayInsertAt all indexes to the right of the new index are recalculated to reflect the new index count For more information about these array functions see the CFML Reference Note Because ColdFusion arrays are dynamic if you add or delete an element from ...

Page 140: ...mes using reference to the fullname array cfset fullname 2 1 Hawkins cfset fullname 2 2 Parker cfset fullname 2 3 Gordon cfoutput fullname 1 1 fullname 2 1 br fullname 1 2 fullname 2 2 br fullname 1 3 fullname 2 3 br fullname 1 1 fullname 2 3 br cfoutput Note that because this is a full 2D array you can easily output names that do not make sense in the real world Additional referencing methods You...

Page 141: ... to add data to it right away One reason to do this is so that you can refer to all the array indexes If you refer to an array index that does not contain some value such as an empty string you get an error The ArraySet function has the following form ArraySet arrayname startrow endrow value This example initializes the array myarray indexes 1 to 100 with an empty string ArraySet myarray 1 100 Pop...

Page 142: ...nt from 1 to 12 cfloop index loopcount2 from 1 to 2 cfset my2darray loopcount loopcount2 loopcount loopcount2 cfloop cfloop p The values in my2darray are currently p cfloop index OuterCounter from 1 to ArrayLen my2darray cfloop index InnerCounter from 1 to ArrayLen my2darray OuterCounter cfoutput b OuterCounter InnerCounter b my2darray OuterCounter InnerCounter br cfoutput cfloop cfloop Nesting CF...

Page 143: ...llowing example cfset arrayname x column row In the following example a cfloop places four columns of data from a sample data source into an array myarray Do the query cfquery name test datasource cfsnippets SELECT Emp_ID LastName FirstName Email FROM Employees cfquery Declare the array cfset myarray arraynew 2 Populate the array row by row cfloop query test cfset myarray currentrow 1 Emp_ID curre...

Page 144: ...Len Returns the length of the specified array ArrayMax Returns the largest numeric value in the specified array ArrayMin Returns the smallest numeric value in the specified array ArrayNew Creates a new array of specified dimension ArrayPrepend Adds an array element to the beginning of the specified array ArrayResize Resets an array to a specified minimum number of elements ArraySet Sets the elemen...

Page 145: ...a collection of individual variables A structure s key must be a string The values associated with the key can be anything for example a string an integer an array or another structure Because structures can contain both structures and arrays they provide a very powerful and flexible mechanism for representing complex data You can use structures as associative arrays When used as associative array...

Page 146: ...ith no special characters numbers or spaces You cannot use the dot notation when the property or key is dynamic Associative arrays If you do not know the key name is in advance or it contains spaces numbers or special characters you can use associative array notation This notation uses structures as arrays with string indexes for example depts John or depts John Doe Sales Structure functions Use s...

Page 147: ...tInsert function cfset value StructInsert structure_name key value AllowOverwrite The AllowOverwrite parameter is optional and can be either True or False You can use it to specify whether an existing key should be overwritten The default is False When adding string values to a structure enclose the string in quotation marks For example to add a key John with a value Sales to an existing structure...

Page 148: ...ohn Facilities cfoutput After the second change John is in the departments John Department br cfoutput Updating a structure with StructUpdate You can also use the StructUpdate function to change the value associated with a specific key Because StructUpdate is a ColdFusion function you must use it inside a ColdFusion tag In some cases you can use the cfoutput or cfset tag You can also use the cfscr...

Page 149: ...re_name key If the name of the key is known in advance you can use the ColdFusion function IsDefined as in this example cfset temp IsDefined structure_name key But if the key is dynamic or contains special characters you must use the StructKeyExists function cfset temp StructKeyExists structure_name key You can also use the StructFind function to find a key and return its value as in this example ...

Page 150: ...t exist The default is False which means that the function returns Yes regardless of whether key exists If you specify True for this parameter the function returns Yes if key exists and No if it does not You can also use the StructClear function to delete all the data in a structure but keep the structure instance itself StructClear structure_name Structure example Structures are particularly usef...

Page 151: ...t employee phone FORM phone StructInsert employee department FORM department cfscript Display results of creating the structure p First name is StructFind employee firstname p p Last name is StructFind employee lastname p p EMail is StructFind employee email p p Phone is StructFind employee phone p p Department is StructFind employee department p cfoutput Call the custom tag that adds employees cf...

Page 152: ...ts INSERT INTO Employees FirstName LastName Email Phone Department VALUES cfoutput StructFind attributes empinfo firstname StructFind attributes empinfo lastname StructFind attributes empinfo email StructFind attributes empinfo phone StructFind attributes empinfo department cfoutput cfquery cfif cfoutput hr Employee Add Complete cfoutput Looping through structures You can loop through a structure ...

Page 153: ... and values of the specified structure StructCount Returns the number of keys in the specified structure StructDelete Removes the specified item from the specified structure StructFind Returns the value associated with the specified key in the specified structure StructInsert Inserts the specified key value pair into the specified structure StructIsEmpty Indicates whether the specified structure c...

Page 154: ...Handling Complex Data with Structures Note that in all cases except StructDelete an exception is thrown if the referenced key or structure does not exist For more information on these functions see the CFML Reference ...

Page 155: ...ne of Java code Contents Creating Forms with the cfform Tag 136 Input Validation with cfform Controls 139 Input Validation with JavaScript 144 Building Tree Controls with cftree 147 Structuring Tree Controls 150 Embedding URLs in a cftree 152 Creating Data Grids with cfgrid 153 Creating an Updateable Grid 155 Building Slider Bar Controls 164 Building Text Entry Boxes 165 Building Drop Down List Bo...

Page 156: ...gs and HTML form tags to reference ColdFusion variables in your forms In addition most cfform controls offer input validation attributes you can use to validate a user s entry selection or interaction This means you do not have to write separate CFML code specifically for input validation as you do in HTML forms Using HTML and cfform ColdFusion generates HTML forms dynamically from cfform tags and...

Page 157: ... it continues to display any text that you enter after you submit it cfform action preserve cfm method POST preservedata Yes p Please enter your name cfinput type Text name UserName required Yes p input type Submit name input type RESET 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 cell...

Page 158: ...dependent of the level of Java support provided by the browser ColdFusion downloads and installs the browser plug in if necessary Some browsers display a single permission dialog box asking you to confirm the plug in install Other browsers particularly older versions of Netscape require you to navigate some simple option screens Because the controls use JavaScript to return data to ColdFusion if y...

Page 159: ...the form dd mm yyyy where the year can have one through four digits Time Verifies a time entry in the form hh mm ss Float Verifies a floating point entry Integer Verifies an integer entry Telephone Verifies a telephone entry You must enter telephone data as You can replace the hyphen separator with a blank The area code and exchange must begin with a digit between 1 and 9 Zipcode U S formats only ...

Page 160: ...and cftextinput tags only These rules differ from those used by the ColdFusion functions REfind REreplace REfindnocase and RERplacenocase and in ColdFusion Studio For information on regular expressions used in ColdFusion functions see Using Regular Expressions in Functions on page 259 Special characters Because special characters are the operators in regular expressions in order to represent a spe...

Page 161: ... regular expression or grouped subexpression followed by an asterisk matches zero or more occurrences of the regular expression For example a z matches zero or more lowercase characters Escape Seq Matches Escape Seq Meaning b Backspace s Any of the following white space characters space tab form feed and line feed b A word boundary such as a space S Any character except the white space characters ...

Page 162: ...ires at least m occurrences of the preceding regular expression The form m requires exactly m occurrences of the preceding regular expression The syntax n is not allowed Backreferences Backreferencing allows you to match text in previously matched sets of parentheses A slash followed by a digit n n refers to the nth parenthesized subexpression One example of how you can use backreferencing is sear...

Page 163: ...y 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 1 9 0 9 An integer that does not begin with a zero and has an optional sign 1 9 0 9 0 9 A real number 1 9 0 9 E 0 9 A real number in engineering notation a 2 4 A string containing two to four occurrences of a aa aaa a...

Page 164: ...pt function to execute if a validation fails For example if you use the onvalidate attribute to specify a JavaScript function to handle input validation you can also use the onerror attribute to specify a JavaScript function to handle a failed validation that is when onvalidate returns a false value If you are using the validate attribute you can also use the onerror attribute to specify a JavaScr...

Page 165: ...trl value indexOf 1 1 Ctrl value indexOf 3 1 return false else return true script head body h2 JavaScript validation test h2 p Please enter your email address p cfform name UpdateForm preservedata Yes action validjs cfm cfinput type text name inputbox1 required YES onvalidate testbox message Sorry your entry is not a valid email address size 15 maxlength 30 input type Submit value Update cfform bo...

Page 166: ... indexOf 1 1 Ctrl value indexOf 3 1 return false else return true script JavaScript code to test for valid entry in the text box The if statement checks to making sure that the field is not empty and contains an at sign that at least the second character and a period that is at least the fourth character onvalidate testbox Calls the JavaScript testbox function to validate entries in this control m...

Page 167: ...oyee cfquery cfform name form1 action submit cfm method Post cftree name tree1 required Yes hscroll No cftreeitem value fullname query engquery queryasroot Yes img folder document cftree cfform 3 Save the page and view it in your browser Reviewing the code The following table describes the highlight code and its function Code Description cftree name tree1 Create a tree and name it tree1 required Y...

Page 168: ... cfm in ColdFusion Studio 2 Modify the page so that it appears as follows CFQUERY with an ORDER BY clause cfquery name deptquery datasource CompanyInfo SELECT Dept_ID FirstName LastName AS FullName FROM Employee ORDER BY Dept_ID cfquery Build the tree control cfform name form1 action submit cfm method Post cftree name tree1 hscroll No border Yes height 350 required Yes cftreeitem value Dept_ID Ful...

Page 169: ...h value starts with the first node If you specify a root name in queryastroot that value gets returned as the root In the previous example if the user selects the name John Allen in the tree the following form variables are returned by ColdFusion Form tree1 node John Allen Form tree1 path Dept_ID 3 John Allen You can specify the character used to delimit each element of the path form variable in t...

Page 170: ...Submit cfform Example multilevel tree control When populating a cftree you manipulate the structure of the tree by specifying a cftreeitem parent In this example every cftreeitem except the top level specifies a parent The parent attribute allows your cftree to show the relationships between elements in the tree control This example populates the tree directly not with a query cfform name form2 ac...

Page 171: ...m value Finance parent Divisions img element cftree cfform Image names in a cftree When you use the img attribute ColdFusion displays the specified image beside the tree items You can specify a built in ColdFusion image name or the URL of an image of your choice such as http localhost Myapp Images Level3 gif As a general rule your custom images should be less than 20 pixels high The built in image...

Page 172: ...ef Yes height 100 width 200 hspace 100 vspace 6 hscroll No vscroll No border No cftreeitem value Important Links cftreeitem value Macromedia Home parent Important Links img document href http www macromedia com cftreeitem value ColdFusion Home parent Important Links img document href http www coldfusion com cftree cfform 3 Save the page and view it in your browser Reviewing the code The following ...

Page 173: ...rmatting options as well as the option of validating user selections with a JavaScript validation script You can also do the following with cfgrid Sort data in the grid alphanumerically Update insert and delete data Display images in the grid Users can sort the grid entries in ascending order by double clicking any column header Double clicking again sorts the grid in descending order You can also...

Page 174: ...attribute to include columns such as the table s primary key column in the results returned by cfgrid without exposing this data to the user 3 Save the file and view it in your browser Reviewing the code The following table describes the highlight code and its function Code Description cfgrid name employee_grid query empdata Create a grid named employee_grid and populate it with the results of the...

Page 175: ...ta source Using cfquery gives you complete control over interactions with your data source The cfgridupdate tag provides a much simpler interface for operations that do not require the same level of control Navigating and entering data in a grid Navigating and using the cfgrid control is fairly straightforward but here are a few tips To sort grid rows so that a column is in ascending order by doub...

Page 176: ...nts see the attribute descriptions in the CFML Reference How user edits are returned ColdFusion creates the following arrays as Form variables to return edits to grid rows and cells When a user selects and changes data in a row ColdFusion creates arrays to store the following information for rows that are updated inserted or deleted The original values for all columns The new column values The typ...

Page 177: ...tatus Action 1 BR Form mygrid col1 1 BR Form mygrid original col1 1 Form mygrid col3 1 BR Form mygrid original col3 1 Form mygrid RowStatus Action 2 BR Form mygrid col2 2 BR Form mygrid original col2 2 Editing data in cfgrid To enable grid editing specify the selectmode edit attribute When enabled a user can edit cell data and insert or delete grid rows When the user submits a cfform containing a ...

Page 178: ...ndle_grid cfm cfgrid name employee_grid height 300 width 250 vspace 10 selectmode edit query empdata insert Yes delete Yes cfgridcolumn name Emp_ID header Emp ID width 50 headeralign center headerbold Yes select No cfgridcolumn name LastName header Last Name width 100 headeralign center headerbold Yes cfgridcolumn name Dept_ID header Dept width 35 headeralign center headerbold Yes cfgrid br input ...

Page 179: ...d name employee_grid height 300 width 250 vspace 10 selectmode edit query empdata insert Yes delete Yes Populate a cfgrid control with data from the empdata query Selecting a grid cell enables you to edit it Rows can be inserted and deleted The grid is 300 X 250 pixels and has 10 pixels of space above and below it cfgridcolumn name Emp_ID header Emp ID width 50 headeralign center headerbold Yes se...

Page 180: ...ides you with full control over how the updates are made and allows you to handle any errors that arise To update the data source with cfquery 1 Open a new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head title Catch submitted grid values title head body h3 Grid values for Form employee_grid row updates h3 cfif isdefined Form employee_grid rowstatus action cfloop...

Page 181: ...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 INSERT into Employee LastName Dept_ID VALUES Form employee_grid LastName Counter Form employee_grid Dept_ID Counter cfquery cfif cfloop cfif body...

Page 182: ...tion code for this row U I or D 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 If the action is to delete a row generate a SQL DELETE query specifying the Emp_ID the primary key of the row to be deleted cfelseif Form employee_grid rowstatus action c...

Page 183: ...uery to insert the Employee s last name and department ID from the grid row into the database The Insert operation assumes that the DBMS automatically increments the Emp_ID primary key If you use the Dbase version of the CompanyInfo database that is provided for UNIX installations the record is inserted without an Emp_ID number cfif cfloop cfif Close the cfif tag used to select among deleting upda...

Page 184: ...e they are highly visual and users cannot enter invalid values To create a slider control 1 Create a new file in ColdFusion Studio 2 Modify the file so that it appears a follows cfform name Form1 action submit cfm method Post cfslider name myslider bgcolor cyan bold Yes range 0 1000 scale 100 value 600 fontsize 14 label Slider value height 60 tickmarkmajor True width 400 cfform 3 Save the file as ...

Page 185: ...control This example validates a date entry which means that a user must enter a valid date in the form mm dd yy the year can be up to four digits For a complete list of validation formats see the CFML Reference Please enter a date br cfform name Form1 action submit cfm method Post cftextinput name entertext value mm dd yy maxlength 10 validate date font Trebuchet MS br br input type Submit value ...

Page 186: ...h query data using cfselect 1 Open a new file in ColdFusion Studio 2 Modify the file so that it appears as follows cfquery name getNames datasource CompanyInfo SELECT FROM Employee cfquery cfform name Form1 action submit cfm method Post cfselect name employees query getNames value Emp_ID display FirstName required Yes multiple Yes size 8 cfselect br input type Submit value Submit cfform 3 Save the...

Page 187: ...value pairs you defined in the Administrator You can override these values by specifying parameter value pairs in cfapplet When an applet is registered you enter just the applet source and the form variable name cfapplet appletsource Calculator name calc_value By contrast with the HTML applet tag you must declare all the applet s parameters every time you want to use it in a ColdFusion page Regist...

Page 188: ...name If the applet has no method leave this field blank Height Enter a measurement in pixels for the vertical space for the applet Width Enter a measurement in pixels for the horizontal space for the applet Vspace Enter a measurement in pixels for the space above and below the applet Hspace Enter a measurement in pixels for the space on each side of the applet Align Choose the alignment that you w...

Page 189: ...s in the Administrator by providing new values for any parameter In order to override a parameter you must have already defined the parameter and a default value for it in the ColdFusion Administrator Applets page cfapplet appletSource myapplet name applet1_var Param1 registered parameter1 Param2 registered parameter2 Handling form variables from an applet The cfapplet tag requires you to specify ...

Page 190: ...e method in the Add Registered Java Applet page of the ColdFusion Administrator 2 Specify the method name in the name attribute of the cfapplet tag when you code your cfform When your page executes the applet a form variable is created with the name that you specified If you do not specify a method no form variable is created ...

Page 191: ... create 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 180 Passing Data Between Nested Custom Tags 181 Executing Custom Tags 185 Installing Custom Tags 187 Managing Custom Tags 188 ...

Page 192: ...rom page to page ColdFusion allows you to store the code in one page and then refer to it in many pages This way you can modify one file the changes appear throughout an entire application Use the cfinclude tag to automatically include an existing file in the current page The page that calls the included page is sometimes referred to as the calling page Each time the calling page is requested the ...

Page 193: ...ate a happy birthday message as follows CF_HappyBirthday name Ted Cantor birthDate December 5 1987 A custom tag can also have a body and end tag for example CF_HappyBirthdayMessge name Ellen Janes birthDate June 8 1993 P Happy Birthday Ellen P P May you have many more P CF_HappyBirthdayMessage You call custom tags by adding the cf_ prefix to the filename without the cfm suffix For example use the ...

Page 194: ...he right tag Note While tag names in ColdFusion pages are case insensitive custom tag filenames must be lowercase on UNIX Variable scopes and special variables ColdFusion provides several variable scope types and built in variables that help you pass information between calling pages and custom tag pages Use the Attributes scope in the custom tag page to refer to the attributes passed by the calli...

Page 195: ...n passes any attributes in the Attributes scope Use the cfparam tag with a default attribute at the top of a custom tag to test for and assign defaults for optional attributes that are passed from a calling page Use the cfparam tag without a default attribute or a cfif tag with an IsDefined function at the top of a custom tag to test for required attributes that must be passed from a calling page ...

Page 196: ...mple to pass the value of the NameYouEntered variable to the cf_getMD tag you can call the custom tag as follows cf_getMD Name NameYouEntered In the getmd cfm file you refer to the passed attribute as Attributes Name To pass values back to the calling page use the Caller scope The custom tag page can also access variables already set on the calling by simply prefixing the calling page s local vari...

Page 197: ...r example as Attributes CustomerName or Attributes Department_number If the called custom tag uses a cfassociate tag to save its attributes in the base tag the attributes passed via structure are saved as independent attribute values with no indication that they were aggregated into a structure by the custom tag s caller Custom tag processing reserves attributecollection to refer to the structure ...

Page 198: ...ag CF_GetMD Name NameYouEntered Come back from the Custom tag display the results of the custom tag cfoutput You are now Variables Doctor br cfoutput body html 3 Save the page as callingpage cfm 4 Create another new page the custom tag in ColdFusion Studio 5 Enter the following code The value of the variable Attributes Name comes from the calling page If the calling page does not set it make it Wh...

Page 199: ...the calling page display the value of the NameYouEntered variable before calling the custom tag CF_GetMD Name NameYouEntered In the calling page call the GetMD custom tag and pass it the Name attribute whose value is the value of the local variable NameYouEntered cfparam name Attributes Name default Who The custom tag page normally gets the Name variable in the Attributes scope from the calling pa...

Page 200: ...ough the variable thisTag ExecutionMode The start mode in which the base tag is processed for the first time The inactive mode in which sub tags and other code contained within the base tag are processed No processing occurs in the base tag during this phase The end mode in which the base tag is processed a second time The end mode occurs when ColdFusion reaches the custom tag s end tag Associatin...

Page 201: ...ariable MyQueryResults in a tag s implementation holds an important query result set and expecting users of the custom tag to manipulate MyQueryResults directly create another nested custom tag that manipulates MyQueryResult This protects the users of the custom tag from changes in the tag s implementation Where is data accessible Two custom tags can be related in a variety of ways in a page Ances...

Page 202: ...et collection_Name data dataCollection Create the attribute collection if necessary cfif not isDefined collectionName cfset collection_Name arrayNew 1 cfif Append the current attributes to the array cfset temp arrayAppend evaluate collectionName attributes The CFML code accessing sub tag attributes in the base tag could look like the following Protect against no sub tags cfparam Name thisTag assoc...

Page 203: ...nestag1 hr Call cf_nestag2 directly br cf_nestag2 hr Using a loop to call call cf_nestag2 br cfloop index i from 1 to 2 cf_nestag2 cfloop 3 Save the page as nesttest cfm To create the first custom tag page 1 Create a new application page the calling page in ColdFusion Studio 2 Put the following single line in the file cf_nestag2 3 Save the page as nestag1 cfm To create the second custom tag page 1...

Page 204: ...e of the custom tag I m in cfset incustomtag cfloop index elem list listrest listrest ancestorlist cfif left elem 3 eq cf_ cfset incustomtag elem cfbreak cfif cfloop cfif incustomtag neq Say you are there cfoutput I m running in the context of a custom tag named inCustomTag p cfoutput Get the tag instance data cfset tagdata getbasetagdata incustomtag Find out the tag s execution mode I m located i...

Page 205: ...g execution to validate this The same CFML page is executed for both the start and end tag of a custom tag Specifying execution modes A variable with the reserved name thisTag ExecutionMode will specify the mode of invocation of a custom tag page The variable has one of the following values Start start tag execution End end tag execution When the body of the custom tag not the custom tag page or t...

Page 206: ... that processing continues from the first child of the tag or continues immediately after the end tag marker You can also use the method attribute to specify that the tag body executes again This enables custom tags to act as high level iterators emulating cfloop behavior The following table summarizes cfexit behavior method attribute value Location of cfexit call Behavior ExitTag default Base pag...

Page 207: ...ould look something like this cfif thisTag ExecutionMode is end cfset thisTag GeneratedContent thisTag GeneratedContent cfif Installing Custom Tags Custom tags are just like other cfm files except that they must be installed in a specific location to be accessible from the calling page Because ColdFusion loads the first instance it finds of the custom tag called by a page you should avoid placing ...

Page 208: ... can be an important safeguard in team development To avoid name conflicts you can register custom tags as a security resource on the ColdFusion Administrator Advanced Security page For details see Advanced ColdFusion Administration Attribute Description template Required if the name attribute is not used Specifies a relative path to the cfm file Same as template attribute in cfinclude Note that t...

Page 209: ...ription input file Name of the file you want to encode cfencode does not process an encoded file output file Path and filename of the output file Warning If you do not specify an output filename a warning message asks if you want to continue in which case the encoded file will overwrite the source file r Recursive when used with wildcards recurses through subdirectories to encode files q Suppresse...

Page 210: ...190 Chapter 10 Reusing Code ...

Page 211: ...aches to troubleshooting common problems ColdFusion Studio also provides interfaces for debugging application pages and for dynamically validating multiple levels of HTML and CFML code This chapter does not discuss debugging in ColdFusion Studio Contents Debug Settings in the ColdFusion Administrator 192 CFML Code Validation 194 Troubleshooting Common Problems 195 Error Handling in ColdFusion 197 ...

Page 212: ... Simply append the parameter mode debug to the end of the URL www myserver com cfdocs test cfm mode debug Note If you do not restrict access to debugging information any browser can use this parameter to get debugging information To restrict access to specific IP addresses use the Debugging IPs page of the ColdFusion Administrator to specify the addresses that can receive debugging messages Genera...

Page 213: ...curred System related errors such as out of memory conditions or file or disk access errors You must select the Display the template path in error messages option on the ColdFusion Administrator Debug Options page to include the path of the page that encounters the problem in each error message Tip If you get a message that does not explicitly identify the cause of the error check on key system pa...

Page 214: ...re validated during execution Validation of such attributes causes a slight performance penalty Although dynamically providing an action can save a few lines of code you should avoid this practice in the interest of a more complete validation and faster application performance Tip If a commercially purchased custom tag fails to run try turning off the Enforce Strict Attribute Validation setting in...

Page 215: ... ColdFusion cannot correctly decode the contents of your form submission The method attribute in forms sent to the ColdFusion Server must be Post for example form action test cfm method Post Problem The browser complains when you include spaces in URLs URLs cannot have embedded spaces Use a plus sign wherever you want to include a space ColdFusion correctly translates the sign into a space A commo...

Page 216: ...sions for proper placement of single and double quotes Color coding in ColdFusion Studio can help you spot improper quote placement Problem You suspect that there are problems with the structure or contents of a complex data variable such as a structure array query object or WDDX encoded variable Use the cfdump tag to generate a table formatted display of the variable s structure and contents For ...

Page 217: ...ow ColdFusion handles them How to use the cferror tag to specify error handling pages Logging errors How to handle ColdFusion exceptions Understanding ColdFusion errors Before you can effectively managee ColdFusion errors you must understand the error types and how ColdFusion handles them ColdFusion error types ColdFusion errors can help you to debug your application and provide feedback to users ...

Page 218: ...cfm specifies a monitor error handler for the exception type Use the Monitor error page when the page exits continue handling the error as follows Endif If code with error is inside a cftry tag and the exception type is specified in a cfcatch tag see Note Execute code in cfcatch tag Else If a cferror tag specifies an exception error handler for the exception type Use error page specified by cferro...

Page 219: ... Application cfm page For more information see Understanding the Web Application Framework on page 214 For detailed information on the cferror tag see the CFML Reference Type Description Validation Handles server side form field data validation errors The validation error page cannot include CFML tags but can display special error page variables Exception Handles exception errors You can specify d...

Page 220: ...tered p error InvalidFields br Error page variables The following variables are available on error pages Error type Error variable Description Exception Request Monitor error type The exception type For a list of error types see Types of recoverable exceptions supported on page 205 error diagnostics Detailed error diagnostics from ColdFusion Server error mailTo E mail address of administrator who ...

Page 221: ...border 1 tr td b Error Information b br Date and time error DateTime br Page error template br Remote Address error remoteAddress br HTTP Referer error HTTPReferer br br Diagnostics br error diagnostics td tr table cfoutput body html Validation error validationHeader Text for header of default validation message error invalidFields Unordered list of validation errors that occurred This includes an...

Page 222: ...t error handlers If a cferror handler of type Request handles the error Otherwise you must use the cflog tag in your error handling code to generate log entries The cflog tag lets you specify the following information A custom file or standard ColdFusion log file in which to write the message Text to write to the log file Message severity type Information Warning Fatal or Error Whether to log any ...

Page 223: ...and its function Code Description cflog file myapp_errors text Exception error Exception type error type Template Error Template Remote Address Error RemoteAddress Diagnositcs Error Diagnostics type Error When this page is processed log an error message to the file myapp_errors log file in the ColdFusion log directory containing the thread ID date and time application and an error message that inc...

Page 224: ...ype of exception Note For cases when the error handler is not able to successfully handle the thrown error use the cfrethrow tag within a cfcatch block Here is an outline for using cftry and cfcatch to handle errors cftry Put your page s application code here cfcatch type exception type1 Add exception processing code here cfcatch cfcatch type exception type2 Add exception processing code here cfca...

Page 225: ...enerate a template exception Missing included file errors cfcatch type missingInclude Catch errors where included files are missing Object exceptions cfcatch type Object Catch exceptions in ColdFusion code that works with objects Security exceptions cfcatch type Security Raise catchable exceptions in ColdFusion code that works with security Expression exceptions cfcatch type Expression Catch excep...

Page 226: ...s one level of the ColdFusion runtime s active tag context at the time when the ColdFusion interpreter detected the exception Property variable Description cfcatch type The exception s type returned as a string cfcatch message The exception s diagnostic message if one was provided If no diagnostic message is available this is an empty string cfcatch detail A detailed message from the CFML interpre...

Page 227: ...ray Database exceptions The following additional variables are available whenever the exception type is database Expression exceptions The following variable is only available for expression exceptions Property variable Description cfcatch nativeErrorCode The native error code associated with this exception Database drivers typically provide error codes to assist in the diagnosis of failing databa...

Page 228: ...r to use cftry with cfcatch type Any at a main processing level to gracefully terminate a subsystem s processing in case of an unexpected error Exception handling example The following example shows cftry and cfcatch using the CompanyInfo data source used in many of the examples in this book and a sample included file includeme cfm If an exception occurs during the cfquery statement s execution th...

Page 229: ...issing included files Print Message and Detail error messages Block executes only if a MissingInclude exception is thrown cfcatch type MissingInclude h1 Missing Include File h1 cfoutput ul li b Message b cfcatch Message li b Detail b cfcatch Detail li b File name b cfcatch MissingFilename ul cfoutput cfcatch Use cfcatch to test for database errors Print error messages Block executes only if a Data...

Page 230: ...roperly you should see an employee entry and not get any error 3 In the cfquery tag change the line FROM Employee to FROM Employer Display the page This time the cfcatch type Database block displays an error message 4 Correct Employer back to Employee Change the cfoutput line p Department Dept_ID br to p Department DepartmentID br Display the page This time the cfcatch type Any block displays an e...

Page 231: ..._field codeValue ColdFusion uses the catch type as a pattern to find a catch handler For example cfthrow type MyApp BusinessRuleException InvalidAccount would be handled by any of the following cfcatch error handlers cfcatch type MyApp BusinessRuleException InvalidAccount cfcatch type MyApp BusinessRuleException cfcatch type MyApp The handler that matches most exactly handles the error Therefore i...

Page 232: ...212 Chapter 11 Preventing and Handling Errors ...

Page 233: ...ication cfm file the application page that controls the application framework Contents Understanding the Web Application Framework 214 Mapping an Application Framework 216 Creating the Application cfm File 219 Managing the Client State 221 Configuring and Using Client Variables 223 Using Session Variables 228 Using Application Variables 230 Using Server Variables 232 Locking Code with cflock 233 E...

Page 234: ...features in ColdFusion You specify application level settings in the Application cfm and OnRequestEnd cfm files Application cfm is executed when ColdFusion starts processing each page in your application and OnRequestEnd cfm is processed after all other processing is completed for the page Client Session Application and Server scope variables ColdFusion provides four variable scopes that let you t...

Page 235: ...llows you to optionally suppress the display of error information For more information see Generating Custom Error Messages with cferror on page 199 Web server security integration You can integrate your applications with the user authentication and security provided by your Web server In addition the ColdFusion Server offers a security framework that controls access to applications pages data sou...

Page 236: ...application page as if by a cfincludetag If the Application cfm page it is present in the directory tree there is no way not to include it For this reason it is the ideal location to set application level variables If an application page has a cfinclude tag pointing to an additional application page ColdFusion does not initiate another search for an Application cfm page when it includes the additi...

Page 237: ...eb server security settings You can use a single Application cfm file for your application or use different Application cfm files that govern individual sections of the application The following directory trees illustrate two approaches to implementing the Application Framework In the first example a company named Web Wonders Inc uses a single Application cfm file installed in their application ro...

Page 238: ...218 Chapter 12 Using the Application Framework ...

Page 239: ...fapplication tag you define a set of pages as part of the same logical application Note The value you set for the name attribute in cfapplication is limited to 64 characters To name the application 1 Open ColdFusion Studio and create a new file 2 Modify the file so that it appears as follows This example illustrates cfapplication Name the application cfapplication NAME SearchApp 3 Save the file as...

Page 240: ...UEST template requesterr cfm mailto admin company com cferror type VALIDATION template validationerr cfm Set application specific constants These are put in the Variables scope of every page in the application cfset homepage http www mycompany com cfset primarydatasource CompanyDB set global error handling for this application set Session variable for this application Note that the cfset tag is su...

Page 241: ...n You should reserve Client variables for client specific data that you want available for multiple browser sessions such as client preferences Variable Type Description Client Data saved as cookies database entries or Registry entries but is accessed more slowly than data stored in memory Each type of data storage has its own timeout period You can specify the database and Registry data timeouts ...

Page 242: ...ecifies 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 Following the setting or migration of host l...

Page 243: ...ing a Client variable storage method After you enable client state management you must determine where you want to store Client variables The system wide default is to store Client variables in the Registry But you can choose to store them instead in a SQL database or in cookies The ColdFusion Administrator Server Client Variables page controls the default Client variable location You can override...

Page 244: ...ement using a sample database called mydatasource To specify the Client variable storage method 1 Open the file Application cfm in ColdFusion Studio and modify it so that it appears as follows This example illustrates cfapplication Name the application and enable client management cfapplication NAME SearchApp clientmanagement Yes clientstorage mydatasource 2 Save the file as Application cfm in the...

Page 245: ... information variables in customizing behavior depending on how often users visit your site and when they last visited For example the following code shows the date of a user s last visit to your site cfoutput Welcome back to the Web SuperShop Your last visit was on DateFormat Client LastVisit cfoutput Variable Description Client CFID The client ID normally stored on the client system as a cookie ...

Page 246: ...ion if any For more information on this function see the CFML Reference Also using the Client Variables page of the ColdFusion Administrator Server tab you can edit the Client variable storage to remove Client variables stored in either the Registry or a database after a set number of days The default value is 90 days when Client variables are stored in the registry 10 days when stored in a data s...

Page 247: ...export your Client variable database from the registry in Windows 1 Open the Registry editor 2 Find and select the following key HKEY_LOCAL_MACHINE SOFTWARE Allaire ColdFusion CurrentVersion Clients 3 On the Registry menu click Export Registry File 4 Enter a name for the registry file After you create a registry file you can copy it to a new machine and import it by selecting Import Registry File ...

Page 248: ...d turn on Session management with a 45 minute timeout cfapplication name GetLeadApp sessionmanagement Yes sessiontimeout CreateTimeSpan 0 0 45 0 What is a session A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application Sessions are specific to individual users As a result every user has a separate se...

Page 249: ...n application This information remains available throughout that user s session thereby avoiding the overhead of retrieving the preferences again and again Like Client variables Session variables require a client name client ID and are always scoped within that client ID Session variables also work within the scope of an application name if one is supplied in which case their scope is the combinat...

Page 250: ... the same application name Also you do not need to use the cfapplication tag to enable Application variables Using the ColdFusion Administrator you can enable or disable Application variables in all applications you cannot override this setting for an individual application Like Session variables ColdFusion stores Application variables in the ColdFusion Server s memory and you can set timeout valu...

Page 251: ...tion that you seldom write but read often In most cases the values of these variables are set once most often when an application first starts Then the values of these variables are referenced many times throughout the life of the application or the course of a session When using Application variables keep in mind that these variables are shared by all instances of an application that might be run...

Page 252: ...wing standard read only Server variables Variable Description Server ColdFusion ProductName The name of the product that is ColdFusion Server Server ColdFusion ProductVersion The version number for the server that is running such as 5 0 0 Server ColdFusion ProductLevel The server product level such as Enterprise Server ColdFusion SerialNumber The serial number assigned to this server installation ...

Page 253: ...k in these circumstances can result in data corruption and can result in hanging the ColdFusion Server Symptoms of this corruption include the following Unexpected error messages particularly Unknown Exception errors cfserver process crashing or stopping and restarting Unexpected values in shared variables Excessive growth in memory used by the cfserver process Operating system instability Using c...

Page 254: ...ad only lock tag you lose the advantages of locking As a result you must be careful not to set any Session Application or Server variables inside a read only cflock tag body Enclose code that reads or tests Session Application or Server variables in exclusive cflock tags You specify a read only lock by setting the type readOnly attribute in the cflock tag Lock scopes and names The cflock tag preve...

Page 255: ...e lock if it is not available By default if the lock does not become available within the timeout period ColdFusion generates an exception error which you can handle using cftry and cfcatch If you set the cflock throwOntTmeout attribute to No processing continues after the timeout at the line after the cflock end tag Under normal circumstances it should not take more than a few seconds to obtain a...

Page 256: ...ng or locking option results in the most efficient code but requires you to follow the full rules of locking You should only select this option after you finish debugging your program Full checking is very useful for debugging your code You get errors to help indicate missing locks You can leave this feature on in production code to protect against inadvertently unlocked variable accesses but it a...

Page 257: ...ch no request can execute the locked section of the page Thus all requests to the protected section of the page are blocked until there is a timeout The following table shows one scenario that would cause a deadlock Once a deadlock occurs neither of the users can do anything to break the deadlock because the execution of their requests is blocked until the deadlock is resolved by a lock timeout In...

Page 258: ...e if a lock times out As a result users see the default exception error page on lock timeouts The following sample code might be part of the Application cfm file cfapplication name ETurtle sessiontimeout createtimespan 0 1 30 0 sessionmanagement yes Initialize the session and application variables that will be used by E Turtleneck Use the session lock scope for the Session variables cflock scope S...

Page 259: ...oblem is by using the OnRequestEnd cfm page to display the value at the bottom of each page in the application html head title cflock Example title head body h3 cflock Example h3 cfif isdefined form submit Lock Session variables Note that we use the automatically generated Session ID as the order number cflock scope Session timeout 10 type ReadOnly cfoutput Thank you for shopping E Turtleneck Toda...

Page 260: ...tions You have just selected the longest wearing most comfortable turtleneck in the world Please indicate the color and size you want to buy p table cellspacing 2 cellpadding 2 border 0 tr td Select a color td td select type Text name color option red option white option blue option turquoise option black option forest green select td tr tr td Select a size td td select type Text name size option ...

Page 261: ... locking access to one file does not delay access to any other file cflock name filename timeout 30 type Exclusive cffile action Append file fileName output textToAppend cflock Example of protecting ColdFusion Extensions The following example illustrates how you can build a custom tag wrapper around a CFX tag that is not thread safe The wrapper forwards attributes to the non thread safe CFX tag th...

Page 262: ...242 Chapter 12 Using the Application Framework ...

Page 263: ...pt 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 This chapter describes the CFScript language s functionality and syntax Contents About CFScript 244 The CFScript Language 245 Interaction of CFScript with CFML 249 Defining and Using Custom Functions 250 ...

Page 264: ...mail Form email cfset employee phone Form phone cfset employee department Form department cfoutput About to add Form firstname Form lastname br cfoutput Using CFScript cfscript employee StructNew employee firstname Form firstname employee lastname Form lastname employee email Form email employee phone Form phone employee department Form department WriteOutput About to add Form firstname Form lastn...

Page 265: ... CFML expressions CFML expressions include operators such as EQ and so on as well as all CFML functions For information about CFML expression operators and functions see the CFML Reference Note You cannot use CFML tags in CFScript Statements In CFScript semicolons define the end of a statement Line breaks are insignificant Enclose multiple statements in curly braces to group them for use in an exp...

Page 266: ...etVariable a a 1 Empty The test expr can be one of the following Any ColdFusion expression for example A LT 5 loop LE x or Y EQ not found AND loop LT end Empty Here are some examples of for loops for Loop 1 Loop LT 10 Loop Loop 1 a loop loop Complete for loop in a single line for loop 1 loop LT 10 loop loop 1 a loop loop Use braces to indicate multiple statements to loop over for indx indx 1 if Fi...

Page 267: ...nt that is not a variable a function or other expression Only one default statement is allowed You can use multiple case statements You cannot mix Boolean and numeric case values in a switch statement No two constants can be the same inside a switch statement switch name case John male true found true break case Mary male false found true break default found false break end switch for in loop for ...

Page 268: ...iables or identifiers in your scripting code Differences from JavaScript CFScript is similar to JavaScript however there are some key differences in CFScript It uses ColdFusion expressions which are neither a subset nor a superset of JavaScript expressions For example there is no operator in CFScript It does not have user defined variable declarations It is case insensitive All statements end in a...

Page 269: ...ipt comments are not considered statements To comment out all the contents of a cfscript tag block put ColdFusion comment tags around the entire block including the cfscript and cfscript tags You can read and write ColdFusion variables inside CFScript as this example shows cfoutput query patients cfscript testres is a column in the patients query if testres EQ 1 result positive else result negativ...

Page 270: ...the page where it is called even after it is called although this is not recommended On a page that you include using a cfinclude tag The cfinclude tag must be executed before the function gets called For example you can define all your application s functions on a single page and place a cfinclude tag at the top of pages that use the functions Syntax Use the following syntax inside a cfscript tag...

Page 271: ...e type including structures queries and arrays Each function must execute a return statement Calling functions You can call a function anywhere that you can use an expression including in the body of a cfoutput tag in a ColdFusion Script or in a tag attribute value One function can call another function and you can use a function as a parameter to another function You call custom functions the sam...

Page 272: ...ou change the value of a query or structure argument variable in the function it changes the value of the variable that the calling page used in calling the function However if you change the value of an array or string argument variable in the function it does not change the value of the string variable in the calling page Using variables A function can access all variables that are available in ...

Page 273: ...ists you should use the isDefined function to ensure that it is defined For example cfscript if IsDefined MyFunc if IsCustomFunction MyFunc WriteOutput MyFunc is a custom function else WriteOutput Myfunc is defined but is NOT a custom function else WriteOutput MyFunc is not defined cfscript Note that the you do not surround the argument to IsCustomFunction in quotation marks Examples of custom fun...

Page 274: ... arg_count ArrayLen Arguments var opt_arg 3 for opt_arg LTE arg_count opt_arg opt_arg 1 sum sum Arguments opt_arg return sum cfscript Using custom functions effectively These notes provide information that will help you use custom functions more effectively Using Application cfm Consider putting custom functions that you use frequently on the Application cfm page Queries as function parameters Whe...

Page 275: ...ion local variable value if you pass the argument unqualified as myname CFScript myname globalName function readname name var myname localName return Evaluate name CFScript cfoutput The result of calling readname with myname is readname myname br whoops collides with local variable name The result of calling readname with variables myname is readname variables myname ok Finds the name passed in cf...

Page 276: ...e NEW element one Change the seond element of the directly passed array array_param 2 This is the NEW element two return success Call the function passing the structure and the array setarray mystruct mystruct myarray CFScript CFOutput The element one is changed br mystruct myarray 1 Element two is unchanged because the function got a copy br mystruct myarray 2 CFoutput Error handling You can hand...

Page 277: ...t errorInfo Alternatively caller can look at errorInfo and see whether some pre defined fields are available return 1 or or whatever we have agreed to errorInfo structNew result bigCalc x y errorInfo if result eq 1 use information from errorInfo or if structKeyExists errorInfo errorMsg error anotherResult bigCalc x 10 y 30 ...

Page 278: ...258 Chapter 13 Extending ColdFusion Pages with CFML Scripting ...

Page 279: ...ular expressions which have a slightly different syntax than ColdFusion regular expressions For information on JavaScript regular expressions see Input Validation with cfform Controls in Chapter 9 For detailed descriptions of the ColdFusion functions that use regular expressions see the CFML Reference Contents About Regular Expressions 260 Basic Regular Expression Rules 261 Multicharacter Regular ...

Page 280: ...ficult if not impossible For example how can you find the first occurrence in a string of any word that consists entirely of capital letters that has spaces around it Using regular expressions the task is trivial cfset IndexOfOccurrence REFind A Z Some BIG string The value of IndexOfOccurrence is 5 You often process large amounts of dynamic textual data Regular expressions can be invaluable in wri...

Page 281: ...haracter 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 To make a regular expression case insensitive substitute individual characters with character sets for example Nn Ii Cc Kk If you want to include closing square bracket in square brackets it must be...

Page 282: ... a z digit Matches any digit Same as 0 9 alnum Matches any alphanumeric character Same as A Za z0 9 xdigit Matches any hexadecimal digit Same as 0 9A Fa f space Matches a tab new line vertical tab form feed carriage return or space print Matches any printable character punct Matches any punctuation character that is one of S _ graph Matches any of the characters defined as a printable character ex...

Page 283: ...so on until the empty string before o is matched This result might be unexpected The workarounds for these types of problems are specific to each case In some cases you can use T which requires at least one T instead of T Alternatively you might be able to specify an additional pattern after T In the following example the regular expression has a W at the end cfoutput REReplace Hello World T W 7 A...

Page 284: ...50000 cfset test mid input 1 20000 cfset out1 REReplace test Chr 9 Chr 13 Chr 10 Chr 13 Chr 10 chr 10 ALL cfset test mid input 20001 20000 cfset out2 REReplace test Chr 9 Chr 13 Chr 10 Chr 13 Chr 10 chr 10 ALL cfset test mid input 40001 len input 40000 cfset out3 REReplace test Chr 9 Chr 13 Chr 10 Chr 13 Chr 10 chr 10 ALL cfset result out1 out2 out3 Anchoring a regular expression to a string You c...

Page 285: ...ences of the and replaces them with an asterisk resulting in the following text There coffee in kitchen Using backreferences in replacement strings You can use backreferences in replacement strings Backreferences in the replacement string refer to matched subexpressions in the regular expression search For example to replace all repeated words in a text string with a single word use the following ...

Page 286: ...ts If there are no occurrences of the regular expression the pos and len arrays each contain 1 element with a value of 0 In the following example the first match for the expression A Aa z is is is The expression A Za z is a subexpression of the complete regular expression cfset subExprs REFind A Za z 1 There is is a cat in in the kitchen 1 True When ColdFusion executes the ReFind function subExprs...

Page 287: ...0 9_ A Za z A Za z0 9_ A ColdFusion variable with no more than one qualifier for example Form VarName but not Form Image VarName 1 9 0 9 An integer that does not begin with a zero and has an optional sign 1 9 0 9 0 9 A real number 1 9 0 9 E 0 9 A real number in engineering notation a 2 4 Two to four occurrences of a aa aaa aaaa ba 3 At least three ba pairs bababa babababa and so on Expression Retu...

Page 288: ...ce of the abbreviation USA The letters can be in either case and the abbreviation can have a period after any letter REFindNoCase a c ABCAACCDD 4 REReplace There is is coffee in the the kitchen A Za z 1 ALL There coffee in kitchen REReplace report All Removes all HTML tags from a string value of the report variable Expression Returns ...

Page 289: ... administration documentation provides information about using both engines ColdFusion CFML tags for the two engines are identical except for how you specify the collection and external tag attributes This chapter provides and overview of how use the Verity search engines to index and search data for your application Contents Searching a ColdFusion Web Site 270 Supported File Types 271 Support for...

Page 290: ...ecified in the index command Index e mail generated by ColdFusion application pages and create a searching mechanism for the indexed messages Build collections of inventory data and make those collections available for searching from your ColdFusion application pages Support international users in a range of languages from the cfindex cfcollection and cfsearch tags Advantages of using Verity Verit...

Page 291: ...2000 Corel WordPerfect Microsoft Word Microsoft Excel Lotus AMI Pro and Lotus 1 2 3 The Verity KeyView filters support the following formats Word Processing Applix Words v4 2 4 3 4 4 HTML Verity Zone Filter Lotus AmiPro v2 3 Lotus Ami Professional Write Plus Lotus Word Pro v96 97 Microsoft RTF Microsoft Word v2 6 95 97 2000 Microsoft Word Mac v4 5 6 Microsoft Word PC v4 5 6 Microsoft Works Microso...

Page 292: ...anguage of the collection you are searching If you do not specify a language in these tags ColdFusion checks the registry for the collection s language If this is defined ColdFusion uses the language Otherwise it assumes that the language is English By default the dictionaries are installed in cfusion verity common in Windows and in opt coldfusion verity common in UNIX ColdFusion supports Verity L...

Page 293: ...st collections A collection is a special database created by Verity that contains pointers to the indexed data that you specify for that collection ColdFusion s Verity implementation supports collections of three basic data types Text files such as HTML pages and CFML pages Binary documents see Supported File Types on page 271 Result sets returned from cfquery cfldap and cfpop queries You can buil...

Page 294: ...ess to an existing collection You can easily enable access to a collection on the network by creating a local reference an alias for that collection The collection only needs to be a valid Verity collection it does not matter whether the collection was created within ColdFusion or another tool Use the following procedure to enable access to an existing collection To add an existing collection 1 Op...

Page 295: ...io name CollectionAction value Create checked Create br input type radio name CollectionAction value Repair Repair br input type radio name CollectionAction value Optimize Optimize br p input type submit name submit value Submit form body html 3 Save the file as collectioncreateform cfm Note that this file simply shows how the form variables are used and does not perform error checking To create a...

Page 296: ...zed cfcase cfcase value Delete cfcollection action Delete collection Form CollectionName p Collection deleted cfcase cfswitch cfoutput body html 3 Save the file as collectioncreateaction cfm 4 View the file collectioncreateform cfm in your browser enter values and submit the form Populating and indexing a collection When you create a new collection it is just an empty shell You can use either of t...

Page 297: ...d 8 Click Submit Changes to begin the indexing process The time required to generate the index depends on the number and size of the selected files in the path This interface lets you easily build a very specific index based on the file extension and path information you enter In most cases you do not need to change your server file structures to accommodate the generation of indices In your ColdF...

Page 298: ...nter the collection you want to populate input type text name IndexColl size 25 maxLength 35 p p Enter the location of the files in the collection input type text name IndexDir size 50 maxLength 100 p input type submit name submit value Index form body html 3 Save the file as collectionindexform cfm To use cfindex to index a collection 1 Open a new file in ColdFusion Studio 2 Modify the file so th...

Page 299: ...udio To quickly create a search application for an existing collection select File New in ColdFusion Studio and select the Verity Wizard in the CFML tab of the New Document dialog box The wizard creates a set of application pages based on the entries you make in the wizard pages You can customize the search interface by adding instructional text for users and applying styles to the form pages Basi...

Page 300: ...n attribute must be the collection s unique alias name as defined in the k2server ini and the external attribute must be No the default To present the results of the search to the user 1 Create a new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head title Search output page title head body cfsearch name Search1 collection form collection form type form type criter...

Page 301: ...e cfsearch tag returns the summary for each found document in the query variable search_query Summary For example to add a summary for each search result returned by the collectionsearchaction cfm page change the cfoutput query tag as follows cfoutput query Search1 a href Search1 URL Search1 title a br Summary br cfoutput For information on an advanced summarization technique see the Knowledge Bas...

Page 302: ...ate database tables Indexing the result set from a ColdFusion query involves an extra step not required when you index documents You must code the query and output parameters and then point the cfindex tag at the result set from a cfquery cfldap or cfpop query To index a ColdFusion query 1 Create a collection on the ColdFusion Administrator Verity Collections page 2 Execute a query and output the ...

Page 303: ...ion or other data from an LDAP accessible server and allow users to search it When creating an index from an LDAP query remember the following considerations Because LDAP structures vary greatly you must know the server s directory schema and the exact name of every LDAP attribute you intend to use in a query The records on an LDAP server can be subject to frequent change You might want to re inde...

Page 304: ...number identifiers on the server and in the Verity collection you should re index the collection before processing a search As with the other query types you need to provide a unique value for the key attribute and enter the data fields to index in the body attribute The following example updates the pop_query collection with the current mail for user1 and searches and returns the message number a...

Page 305: ...t You can assemble an explicit query expression programmatically or you can pass a simple query expression to the search engine directly from an HTML input form The Verity query language provides many operators and modifiers for composing queries You can use the following search techniques to search a Verity collection Word searches Proximity searches Concept based searches Field searches in which...

Page 306: ...rds as if they were modified by the MANY and STEM operators By implicitly applying the MANY operator the search engine calculates each document s score based on the density of the search term in the searched documents The more frequent is the occurrence of a word in a document the higher is the document s score As a result the search engine ranks documents according to word density as it searches ...

Page 307: ...osed in parentheses are evaluated first When the search engine encounters nested parentheses it starts with the innermost term Prefix and infix notation You use can using prefix notation or infix notation to define search strings that use any operator other than an evidence operator As a result either of the following expressions is valid AND a b This is prefix notation a AND b This is infix notat...

Page 308: ... the following table Searching with wildcards The following table shows the wildcard characters that you can use to search Verity collections Angle brackets Left and right angle brackets are reserved for designating operators and modifiers They are optional for the AND OR and NOT operators but required for all other operators Double quotation marks You use double quotation marks in expressions to ...

Page 309: ...s literals For example to search for the wildcard string a b you can surround the string with backquotes as follows a b To search for a wildcard string that includes the literal backquote character you must use two backquotes together and surround the whole string in backquotes n t You can use paired backquotes or backslashes to escape special characters There is no functional difference between t...

Page 310: ...t searches as shown here operator search_string The following operator types are available Evidence operators Evidence operators let you specify a basic word search or an intelligent word search A basic word search finds documents that contain only the word or words specified in the query An intelligent word search expands the query terms to create an expanded word list so that the search returns ...

Page 311: ...Certain characters automatically indicate a wildcard specification such as apostrophe and question mark For example the query expression spam yields matches such as spam spammer and spamming WORD Performs a basic word search selecting documents that include one or more instances of the specific word you enter The WORD operator is automatically implied in any SIMPLE query THESAURUS Expands the sear...

Page 312: ...her The closer the search terms are within a document the higher the document s score You can specify multiple search terms using multiple instances of NEAR N as long as the value of N is the same commute NEAR 10 bicycle NEAR 10 train NEAR 10 PARAGRAPH Selects documents that include all of the words you specify within the same paragraph To search for three or more words or phrases in a paragraph y...

Page 313: ...Selects documents by matching the query string with values stored in a specific document field Documents are selected only if the search elements specified match the field value exactly If a partial match is found a document is not selected for example god matches a document field containing only god and does not match gods godliness or a god among men STARTS Selects documents by matching the char...

Page 314: ...ontains the table YearPlaceText which itself contains three columns Year Place and Text Year and Place make up the primary key The following table shows the TEST1 schema The following application page matches records that have 1990 in the TEXT column and are in the Place Utah The search is performed against the collection that contains the TEXT column and then is narrowed further by searching for ...

Page 315: ...ing table describes each concept operator Operator Description AND Selects documents that contain all the search elements you specify OR Selects documents that show evidence of at least one of the search elements you specify ACCRUE Selects documents that include at least one of the search elements you specify Documents are ranked based on the number of search elements found ALL Selects documents t...

Page 316: ... cfoutput The following table describes the score operators Operator Description YESNO Forces the score of an element to 1 if the element s score is non zero YESNO mainframe If the retrieval result of the search on mainframe is 0 75 the YESNO operator forces the result to 1 You can use YESNO to avoid relevance ranking PRODUCT Multiplies the scores for the search elements in each document matching ...

Page 317: ... MANY Counts the density of words stemmed variations or phrases in a document and produces a relevance ranked score for retrieved documents Use with the following operators WORD WILDCARD STEM PHRASE SENTENCE PARAGRAPH Here is an example PARAGRAPH MANY javascript AND vbscript You cannot use the MANY modifier with the following AND OR ACCRUE Relational operators NOT Use to exclude documents that con...

Page 318: ...enance You should not use the Optimize action in a cfindex tag except to maintain legacy code The cfcollection tag is recommended instead For more information on this command see the Knowledge Base article How To Optimize Your Verity Collection ID 416 at http www coldfusion com Support KnowledgeBase SearchForm cfm Purge Removes all data marked for deletion from a collection Delete as the cfindex a...

Page 319: ...anced Server Security box 3 Click the Submit Changes button 4 Click the Security Contexts button 5 Enter a name for the secured collection and click Add Security Context 6 Optional Enter a description for the secured collection 7 Select Collection on the Enable Security for Resource Types list 8 Click Add You can then develop an appropriate authentication interface to allow access to the secured c...

Page 320: ...300 Chapter 15 Indexing and Searching Data ...

Page 321: ...the cfmail tag and the cfpop tag The boom in Internet mail services makes ColdFusion s enhanced e mail capability a vital link to your users Contents Using ColdFusion with Mail Servers 302 Sending E mail Messages 302 Sample Uses of cfmail 304 Customizing E mail for Multiple Recipients 306 Advanced Sending Options 308 Receiving E mail Messages 309 Handling POP Mail 310 ...

Page 322: ...s you use the cfmail and cfpop tags to send and receive mail respectively The following sections describe ColdFusion e mail features and offer examples of these tags Sending E mail Messages Before you set up ColdFusion to send e mail messages you must have access to an SMTP e mail server Also before you run application pages that refer to the e mail server you might want to configure the ColdFusio...

Page 323: ...new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head title Sending a simple e mail title head body h1 Sample e mail h1 cfmail from Sender Company com to URL email subject Sample e mail This is a sample e mail to show basic e mail capability cfmail The e mail was sent body html 3 Save the file as sendmail cfm in myapps under the Web root directory 4 Open your brow...

Page 324: ...ple the contents of a customer inquiry form submittal are forwarded to the marketing department Note that the same application page could also insert the customer inquiry into the database cfmail from Form EMailAddress to marketing MyCompany com subject Customer Inquiry A customer inquiry was posted to our Web site Name Form FirstName Form LastName Subject Form Subject Form InquiryText cfmail Send...

Page 325: ...e a query BetaTesters retrieves a list of people who are beta testing ColdFusion This query is then used to send a notification to each of these testers that a new version of the beta release is available cfmail query BetaTesters from beta MyCompany com to TesterEMail subject Widget Beta Four Available To all Widget beta testers Widget Beta Four is now available for downloading from the MyCompany ...

Page 326: ... firm Our current information is as follows Company Name Company Contact FirstName LastName Address Address1 Address2 City State Zip Phone Phone Fax Fax Home Page HomePageURL Please let us know if any of the above information has changed or if we need to get in touch with someone else in your organization regarding this request Thanks Customer Service service MyCompany com cfmail Note that in the ...

Page 327: ...or add a header to a mail message In the following example a MIME encoded file is sent along with an e mail message cfmail from abeecho MyCompany com to bobm supercomputer com subject File you requested Dear Bob Here is a copy of the file you requested Regards A Beech cfmailparam file c photos asdl_photo jpg cfmail ...

Page 328: ...Most newer Internet mail applications are capable of reading and interpreting HTML code in a mail message The cfmail tag lets you specify the message type as HTML The type HTML attribute the only valid value the default is plain text informs the receiving e mail client that the message has embedded HTML tags that need to be processed This feature is useful only when you are sending messages to mai...

Page 329: ...r For more information on cfpop syntax and variables see the CFML Reference Using cfpop Use the followig steps to add POP mail to your application To implement the cfpop tag in your ColdFusion application 1 Choose which mail boxes you want to access within your ColdFusion application 2 Determine what mail message components you must process message header message body attachments and so on 3 Decid...

Page 330: ...cordCount messages cfoutput Handling POP Mail This section gives an example of each of the following usages Retrieving only message headers Retrieving a message body Retrieving attachments Deleting messages Retrieving only message headers The header includes the following information When you use cfpop to get the header or the entire message ColdFusion returns the values of each these fields in a ...

Page 331: ...ave the file as hdronly cfm in myapps under the Web root directory and view it in the ColdFusion Studio Browse tab or your Web browser This code retrieves the message headers and stores them in a cfpop query result set called Sample The ColdFusion function HTMLEditFormat replaces characters that have meaning to HTML such as the and signs that can surround detailed e mail address information with e...

Page 332: ...ssword action GetAll name Sample cfoutput query Sample MessageNumber HTMLEditFormat Sample messageNumber br To 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 Body br Sample body br br Header br HTMLCodeFormat Sample header br hr cfoutput body html ...

Page 333: ...g to get attachments ColdFusion generates an error if it tries to write an attachment file to a nonexistent directory Not all messages have attachments If a message has no attachments attachments and attachmentfiles are empty strings To retrieve all parts of a message including attachments 1 Create a new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head title POP ...

Page 334: ...messages By default retrieved messages are not deleted from the POP mail server If you want to delete retrieved messages you must set the action attribute to Delete You must also specify use the messagenumber attribute to specify the numbers of the messages to delete Using cfpop to delete a message permanently removes it from the server If the messagenumber does not correspond to a message on the ...

Page 335: ...me username password password action Delete messagenumber 1 2 3 body html 3 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 username username password password 4 Save the file as hdrbody cfm in myapps under the Web root directory Caution When you view this page in your browser or the ColdFusion Studio...

Page 336: ...316 Chapter 16 Sending and Receiving E mail ...

Page 337: ...rations use the CFFTP tag described in Performing File Operations with cfftp on page 341 Contents Using cffile 318 Uploading Files 319 Setting File and Directory Attributes 323 Evaluating the Results of a File Upload 324 Moving Renaming Copying and Deleting Server Files 326 Reading Writing and Appending to a Text File 327 Performing Directory Operations 329 ...

Page 338: ...ve rename copy delete read readBinary write and append The required attributes depend on the action specified For example if action write ColdFusion expects the attributes associated with writing a text file Note Consider the security and logical structure of directories on the server before allowing users access to them You can disable the cffile tag on the Tag Restrictions page of the ColdFusion...

Page 339: ...ze 45 p input type submit value Upload form body html 3 Save the file as uploadfileform cfm in myapps under the Web root directory Reviewing the code The following table describes the code and its function Code Description form action uploadfileaction cfm enctype multipart form data method post Create a form that contains file selection fields for upload by the user The enctype attribute value tel...

Page 340: ...ad destination c temp nameConflict overwrite fileField Form FiletoUpload cfoutput You uploaded the file cffile ClientFileName cffile ClientFileExt successfully to cffile ServerDirectory cffile ServerFileName cffile ServerFileExt cfoutput body html 3 Change the following line to point to an appropriate location on your server destination c temp 4 Save the file as uploadfileaction cfm in myapps unde...

Page 341: ...ccept graphic files in a document library You use the accept attribute to restrict the type of file that you allow in an upload When an accept qualifier is present the uploaded file s MIME content type must match the criteria specified or an error occurs The accept attribute takes a comma separated list of MIME data names optionally with wildcards A file s MIME type is determined by the browser Co...

Page 342: ...pt image gif This cffile specification saves an image file only if it is in GIF or JPEG format cffile action Upload fileField Form FiletoUpload destination c uploads MyImage GIF nameConflict Overwrite accept image gif image jpeg This cffile specification saves any image file regardless of the format cffile action Upload fileField Form FiletoUpload destination c uploads MyImage GIF nameConflict Ove...

Page 343: ... file s existing attributes are maintained If you specify any other attributes with Normal the additional attribute overrides the Normal setting Example Setting file attributes This example sets the archive bit for the uploaded file cffile action Copy source c files upload keymemo doc destination c files backup attributes Archive Note Make sure you include the trailing slash when you specify the d...

Page 344: ... variables anywhere that you use ColdFusion variables The following table describes the file status variables that are available after an upload Variable Description attemptedServerFile Initial name ColdFusion used attempting to save a file for example myfile txt See Resolving conflicting filenames on page 321 clientDirectory Directory on the client s system from which the file was uploaded client...

Page 345: ...o avoid a name conflict fileWasSaved Indicates Yes or No whether ColdFusion saved a file oldFileSize Size of a file that was overwritten in the file upload operation Empty if no file was overwritten serverDirectory Directory where the file was saved on the server serveFile Full name of the file saved on the server with the file extension for example myfile txt serverFileName Name of the file saved...

Page 346: ...es for many of the attributes However the value of all or part of any attribute in a cffile tag can be a dynamic parameter This makes cffile a very powerful tool Action Example code Move a file cffile action Move source c files upload KeyMemo doc destination c files memo Rename a file cffile action Rename source c files memo KeyMemo doc destination c files memo OldMemo doc Copy a file cffile actio...

Page 347: ...cal variable that you can use anywhere in the application page For example you could read a text file and then insert its contents into a database Or you could read a text file and then use one of the string replacement functions to modify the contents To read a text file 1 Create a new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head title Read a Text File title...

Page 348: ...ze 25 p Enter the name of the file input type text name FileName size 25 p Enter your message p textarea name message cols 45 rows 6 textarea p input type submit name submit value Submit form body html 3 Save the file as writetextfileform cfm in myapps under the Web root directory To write a text file 1 Open a new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head ...

Page 349: ...file information When you use the action list attribute setting cfdirectory returns five result columns that you can reference in a cfoutput tag name Directory entry name size Directory entry size type File type F or D for File or Directory dateLastModified Date an entry was last modified attributes File attributes if applicable mode UNIX only The octal value representing the permissions setting f...

Page 350: ... td td mydirectory mode td tr cfoutput table body html 3 Modify the line directory c inetpub wwwroot mine so that it points to a directory on your server 4 Save the file as directoryinfo cfm and view it in your browser Note that depending on whether your server is on a UNIX system or a Windows system either the Attributes column or the Mode column is empty Also you can specify a filename in the fi...

Page 351: ...y extend your site s offerings across the Web Contents Using cfhttp to Interact with the Web 332 Using the cfhttp Get Method 332 Creating a Query from a Text File 335 Using the cfhttp Post Method 337 Performing File Operations with cfftp 341 Moving Complex Data Structures Across the Web with WDDX 345 Converting CFML Data to a JavaScript Object 349 Transferring Data from Browser to Server 350 Stori...

Page 352: ...ceived For example when you use cfhttp to Post to another ColdFusion page that page does not display It processes the request and returns the results to the original ColdFusion page which then uses the information as appropriate Using the cfhttp Get Method You use Get to retrieve files including text and binary files from a specified server The retrieved information is stored in a special variable...

Page 353: ...pecified Web page It does not save the frame image or other files that the page might include Reviewing the code The following table describes the code and its function Code Description cfhttp method Get url http www ci newton ma us main htm resolveurl Yes Get the page specified in the URL and make the links absolute instead of relative so that they display properly cfoutput cfhttp fileContent BR ...

Page 354: ...point to a binary file you want to download 4 Change the path to point to a path on your hard drive 5 Save the file as savebinary cfm in myapps under your Web root directory and view it in your browser Reviewing the code The following table describes the code and its function Code Description cfhttp method Get url http localhost myapps testfile zip path c temp file MyTestFile zip Get a binary file...

Page 355: ...he text qualifier character To include the text qualifier character in a field use a double character For example if the text qualifier is use to include a quotation mark in the field The first row of text is always interpreted as column headings so that row is skipped You can override the file s column heading names by specifying a different set of names in the columns attribute You must specify ...

Page 356: ...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 cfoutput 3 Substitute the URL with the location of your text file 4 Substitute the name of a text file and the column headers to those in your text file 5 Save the file as querytextfile cfm in myapps under your Web root directory and view it i...

Page 357: ... the Post method in cfhttp in a similar way However with cfhttp the page that receives the Post does not itself display anything To pass variables to a ColdFusion page 1 Open a new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head title HTTP Post Test title head body H1 HTTP Post Test H1 cfhttp method Post url http 127 0 0 1 myapps server cfm cfhttpparam type Cook...

Page 358: ... specified page cfhttpparam type Cookie value cookiemonster name mycookie6 Send a cookie in the request cfhttpparam type CGI value cgivar name mycgi Send a CGI variable in the request cfhttpparam type URL value theurl name myurl Send a URL in the request cfhttpparam type Formfield value wbfreuh macromedia com name emailaddress Send a Form field in the request cfhttpparam type File name myfile file...

Page 359: ... file using the cfhttpparam type File attribute but the receiving page gets it as a Form variable not a File variable This cffile tag creates File variables as follows cfoutput Output information The results are not displayed by this page They are passed back to the posting page in its cfhttp filecontent variable The URL variable is URL myurl br Output the value of the URL variable sent in the HTT...

Page 360: ...lts including both the 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 fil...

Page 361: ...isting directories and performing other operations For a complete list of attributes that support FTP operations and additional details on using the cfftp tag see the CFML Reference To open an FTP connection and retrieve a file listing 1 Open a new file in ColdFusion Studio 2 Modify the file so that it appears as follows html head title FTP Test title head body h1 FTP Test h1 Open ftp connection c...

Page 362: ...word To establish an anonymous connection enter anonymous as the username and an e mail address by convention for the password 5 Save the file as ftpconnect cfm in myapps under your Web root directory Reviewing the code The following table describes the code and its function Code Description cfftp connection Myftp server MyServer username MyUserName password MyPassword action Open stoponerror Yes ...

Page 363: ...n Myftp action ListDir directory cfftp returnvalue name dirlist stoponerror Yes Use the Myftp connection to get a directory listing Use the value returned by the last cfftp call the current directory of the connection to specify the directory to list Save the results in a variable named dirlist a query object Stop processing if there is an error cfftp action close connection Myftp p Did the connec...

Page 364: ...pplication for this approach to work and you must lock code that uses Session variables For information on locking see Locking Code with cflock on page 233 Note Changing a connection s characteristics such the retrycount or timeout values might require you to re establish the connection Connection actions and attributes The following table shows the available cfftp actions and the attributes they ...

Page 365: ...a free download of the WDDX SDK and a number of resources including a WDDX FAQ and a developer forum An overview of distributed data for the Web WDDX is an XML vocabulary for describing complex data structures such as arrays associative arrays and record sets in a generic fashion so you can move them between different application server platforms and between application servers and browsers using ...

Page 366: ...b Service Description Language WSDL and Universal Description Discovery and Integration UDDI The importance of Web Services will increase as the technology matures WDDX does not compete with Web services It is a complementary technology focused on solving simple problems of application integration on the Web in a pragmatic productive manner at very low cost WDDX is a proven technology that has bee...

Page 367: ...structures generally differ from data exposed by traditional data sources such as databases These structures are generally more complex and ad hoc with dynamic structure WDDX lets you work with this data without the overhead of setting up a data source for every type of data needed Therefore it integrates nicely with and complements other approaches that rely on existing data sources Data exchange...

Page 368: ...uring deserialization to JavaScript expressions time zone information is not taken into account Complications arise because of the difficulty of determining the time zone of the browser How WDDX works The WDDX vocabulary describes a data object with a high level of abstraction For instance a simple structure with two string variables might have the following form after it is serialized into a WDDX...

Page 369: ...he following example uses the cfsnippets data source that is installed with ColdFusion Create a simple query cfquery name q datasource cfsnippets SELECT Message_Id Thread_id Username Posted FROM messages cfquery Load the wddx js file which includes the dump function requests to the server script type text javascript src CFIDE scripts wddx js script script Use WDDX to move from CFML data to JS cfwd...

Page 370: ...rst name and last name in the form fields 4 Click Next The name appears in the Names added so far box 5 Repeat steps 3 and 4 to add as many names as you wish 6 Click Serialize to serialize the resulting data The resulting WWDX packet appears in the WDDX packet display box This step is intended only for test purposes Real applications handle the serialization automatically 7 Click Submit to submit ...

Page 371: ...stName personInfo lastName nRows lastName Clear input fields document personForm firstName value document personForm lastName value Show added names on list This gets a little tricky because of browser differences var newName firstName lastName if navigator appVersion indexOf MSIE 1 document personForm names length new Option newName false false else IE version var entry document createElement OPT...

Page 372: ...his would be a hidden input field WDDX packet display p textarea name wddxPacket rows 10 cols 80 wrap Virtual textarea form Server side processing hr p B Server side processing B p cfif isdefined form wddxPacket cfif form wddxPacket neq Deserialize the WDDX data cfwddx action wddx2cfml input form wddxPacket output personInfo Display the query The submitted personal information is P cfoutput query ...

Page 373: ... a complex data structure cfscript relatives structNew relatives father Bob relatives mother Mary relatives sisters arrayNew 1 arrayAppend relatives sisters Joan relatives brothers arrayNew 1 arrayAppend relatives brothers Tom arrayAppend relatives brothers Jesse cfscript A dump of the original relatives structure br br cfdump var relatives br br Convert data structure to string form and save it i...

Page 374: ...354 Chapter 18 Interacting with Remote Servers ...

Page 375: ... ColdFusion Studio For information on setting up security elements or using Administrator controlled security features see Advanced ColdFusion Administration Contents ColdFusion Security Features 356 Remote Development Services RDS Security 356 Overview of User Security 357 Using Advanced Security in Application Pages 358 Using the cfauthenticate tag 359 Authentication and Authorization Functions ...

Page 376: ...e core of the security framework in a team oriented ColdFusion development environment in which groups of developers working in ColdFusion Studio require different levels of access to ColdFusion files and data sources When you are working in ColdFusion Studio you access these ColdFusion resources remotely opening cfm files or accessing data sources RDS security authenticates you and grants access ...

Page 377: ...oyee but you would want managers to be able to see and possibly update information about their direct reports User security authenticates and authorizes users each time that they try to access or work with sensitive data User security is made up of two components Security contexts configured on the Advanced Security page of the ColdFusion Administrator A security context provides the framework aga...

Page 378: ...cfauth to contain authentication information If you choose not to use this cookie you must check authentication for each request Use the IsAuthenticated function to check if the current user is authenticated Use the IsAuthorized function to check whether the user is authorized to access resources This function lets developers offer or deny access to protected resources based on a user s authorizat...

Page 379: ...has two optional attributes setCookie Indicates whether ColdFusion sets a cookie to contain authentication information This cookie is encrypted and includes the user name security context browser remote address and the HTTP user agent Default is Yes throwOnFailure Indicates whether ColdFusion throws an exception of type Security if authentication fails Default is Yes Example cfauthenticate securit...

Page 380: ...icated for the current request otherwise it returns False If you call IsAuthenticated with the optional security_context_name parameter the function returns True if the user is authenticated in the named security context otherwise it returns False The IsAuthenticated function has the following form IsAuthenticated security_context_name Using the IsAuthorized function After a user is authenticated ...

Page 381: ...ndling strategies in ColdFusion see Exception handling strategies on page 208 Example This example shows the use of exception handling with cfauthenticate in an Application cfm file The cfauthenticate tag authenticates a user and sets the security context for an application If the user is not already defined in the system you can either reject the page request that the user respecify the username ...

Page 382: ...o the customer s home page You can provide the hit counter in a custom tag that uses the cffile tag To ensure that the custom tag can access the cffile tag it needs a way to impersonate a trusted user while the tag is executing and then to revert back to the nontrusted user after the trusted piece of code executes The cfimpersonate tag has the following required attributes securitycontext Describe...

Page 383: ...urity is generally handled in two steps 1 The Application cfm page checks to see whether the current user is authenticated If not the page presents a login form and the user must submit a username and password for authentication If the user passes the authentication test ColdFusion passes the cfauth cookie to carry the user s authentication state to subsequent application pages governed by this Ap...

Page 384: ... the application name and security context name to match your application and security names Example Application cfm cfapplication name Orders cfif NOT IsAuthenticated The user is not authenticated cfset showlogin No cfif IsDefined form username AND IsDefined form password The login form was submitted Try authenticating cftry cfauthenticate securityContext Orders username form username password fo...

Page 385: ...en display only the authorized resources The following sample page appears to users who pass the authentication test in the previous Application cfm page It uses the IsAuthorized function to test whether authenticated users are allowed to update or select data from a data source Example orders cfm First check whether a form button was submitted cfif IsDefined Form btnUpdate Is user is authorized t...

Page 386: ... 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: ...nvoke objects created by component technologies including COM DCOM CORBA and Java objects Contents Component Object Overview 368 Invoking Component Objects 369 Getting Started with COM DCOM 370 Creating and Using COM Objects 374 Getting Started with CORBA 376 Calling CORBA Objects 376 Calling Java Objects 378 ...

Page 388: ...ows NT 3 51 4 0 and Windows 95 98 Resources To find out more about COM DCOM go toMicrosoft s COM site http www microsoft com com About CORBA CORBA Common Object Request Broker Architecture is a specification for a distributed component object system defined by the Object Management Group OMG In this model an object is an encapsulated entity whose services are accessed only through well defined int...

Page 389: ...a property cfset value obj property Note that parentheses are not used on the right side of the equation for property gets Calling methods Object methods usually take zero or more arguments Arguments can be sent by value in arguments or by reference out and in out Arguments sent by reference usually have their value changed by the object Some methods return values while others may not Methods with...

Page 390: ...on invokes an object with a graphical interface in a window the component might appear on the Web server desktop not on the user s desktop This can take up ColdFusion Server threads and result in further Web server requests not being serviced ColdFusion can call Inproc Local or Remote COM objects The attributes specified in the cfobject tag determine which type of object is called Requirements for...

Page 391: ...laining each of the component s methods and the ProgID With this information you are ready to use the cfobject tag If you do not have documentation use the Object Viewer to view the component s interface Using the OLE COM Object Viewer The OLE COM Object Viewer installation installs the executable by default as mstools bin oleview exe You use the Object Viewer to retrieve a COM object s Program ID...

Page 392: ...fobject to Invoke Component Objects To view an object s properties 1 Open the Object Viewer and scroll to the object you want to examine 2 Select and expand the object in the Object Viewer 3 Right click the object to view it ...

Page 393: ...rted with COM DCOM 373 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 ...

Page 394: ...e range of mail handling tasks In the OLE COM Viewer methods and properties might be grouped together so you might find it difficult to distinguish between them at first The CDO for NTS NewMail object includes the following properties Body string Cc String From String Importance Long Subject String To String You use these properties to define elements of the mail message you want to send The CDO f...

Page 395: ...es In the example form variables provide method parameters and properties such as the name of the recipient the desired e mail address and so on First create the object cfobject type COM action Create name Mailer class CDONTS NewMail Then use the form variables from the user entry form to populate a number of properties necessary to create and send the message cfset Mailer From Form fromName cfset...

Page 396: ...ttribute shows how the object reference is obtained Set context to IOR for a file containing the object s unique Interoperable Object Reference or to NameService If you set the context attribute to IOR set the class attribute to the file containing the stringified version of the IOR ColdFusion must be able to read this IOR file at all times so make it local to the server or on the network in an ac...

Page 397: ...Declare a couple of structures cfset x StructNew cfif IsStruct x cfset temp StructInsert x s 3 cfset temp StructInsert x l 256 cfset temp StructInsert x d 93 45 cfif cfset NestedStruct StructNew cfif IsStruct NestedStruct cfset temp StructInsert NestedStruct f x cfset temp StructInsert NestedStruct c b cfset temp StructInsert NestedStruct s Test cfif Declare a sequence cfset FixedSeq ArrayNew 1 cf...

Page 398: ...an be any valid Java type for example simple arrays and objects ColdFusion does the appropriate conversions when strings are passed as arguments but not when they are received as return values The following sections provide more details on calling Java objects in ColdFusion Getting Started with Java Java is a strongly typed language unlike ColdFusion which does not enforce data types As a result t...

Page 399: ...st float salary int grade FirstName First LastName Last Salary salary JobGrade grade public void SetSalary float Dollars Salary Dollars public float GetSalary return Salary public void SetJobGrade int grade JobGrade grade public void SetJobGrade String Grade if Grade equals CEO JobGrade 3 if Grade equals MANAGER JobGrade 2 if Grade equals DEVELOPER JobGrade 1 public int GetJobGrade return JobGrade...

Page 400: ... Keep the following points in mind when you write a ColdFusion page that uses a Java class object The Java class name is case sensitive You must make sure that both the Java code and the CFML code use Employee as the class name Code Description cfobject action create type java class Employee name emp Load an instance of the Employee Java class named emp cfset void emp init Do not call a constructo...

Page 401: ... Employee salary and Job Grade Salary grade cfoutput html In this example the constructor takes four arguments the first two are strings and third is a float and the fourth is an integer Java and Cold Fusion Data Type Conversions Cold Fusion is a typeless scripting language that is it does not use explicit data types while Java is strongly typed Under most situations when the method names are not ...

Page 402: ... which method implementation to use When a ColdFusion encounters such an ambiguity it throws a user exception The ColdFusion JavaCast function helps you resolve such issues by specifying the Java type of a variable as in the following line cfset emp SetJobGrade JavaCast int 1 The JavaCast function takes two parameters a string representing the Java data and the variable whose type your are setting...

Page 403: ...eption method The cfcatch block handles the resulting exception by calling the CFML GetException function to retrieve the Java exception object and then calling the object s GetErrorMessage method to get the error information cfobject action create type java class foo name Obj cftry cfset VOID Obj doException cfcatch type Any cfset exception GetException Obj cfset message exception GetErrorMessage...

Page 404: ...e class is created If ColdFusion detects a new class file it loads the class from that directory To use this feature make sure that the Java implementation classes that you modify are not in the general JVM class path In addition do not package the classes into jar files or zip files In all other ways ColdFusion Class loader follows Java conventions including those for package names and directory ...

Page 405: ...he following public methods public class Example public int mPublicInt public Example mPublicInt 0 public Example int IntVal mPublicInt IntVal public String ReverseString String s StringBuffer buffer new StringBuffer s return new String buffer reverse public String ReverseStringArray String arr Method Description ReverseString Reverses the order of a string ReverseStringArray Reverses the order of...

Page 406: ...ple a mPublicInt b mPublicInt static public int SumArray int arr int sum 0 for int i 0 i arr length i sum arr i return sum static public Example SumObjArray Example arr Example sum new Example for int i 0 i arr length i sum mPublicInt arr i mPublicInt return sum static public int ReverseArray int arr int ret new int arr length for int i 0 i arr length i ret arr length i 1 arr i return ret static p...

Page 407: ...ct to reverse them cfset myarray ArrayNew 1 cfset myarray 1 First cfset myarray 2 Second cfset myarray 3 Third cfset ra obj ReverseStringArray myarray Display the results cfoutput br original array element 1 myarray 1 br original array element 2 myarray 2 br original array element 3 myarray 3 br after reverse element 1 ra 1 br after reverse element 2 ra 2 br after reverse element 3 ra 3 br br cfou...

Page 408: ...rray 2 br br cfoutput br Create a ColdFusion array containing two Example objects Use the SumObjArray method to add the objects in the array Get the public member of the resulting object cfset oa ArrayNew 1 cfobject action create type java class Example name obj1 cfset VOID obj1 init JavaCast int 5 cfobject action create type java class Example name obj2 cfset VOID obj2 init JavaCast int 10 cfset ...

Page 409: ... types of requirements you can use the ColdFusion Extension Application Programming Interface CFXAPI to access ColdFusion functions This chapter documents custom tag development using Java or C however it is also possible to develop tags in Borland s Delphi Contents What Are CFX Tags 390 Before You Begin Developing CFX Tags in Java 391 Writing a Java CFX 393 ZipBrowser Example 397 Approaches to De...

Page 410: ...ndle any number of custom attributes Use and manipulate ColdFusion queries for custom formatting Generate ColdFusion queries for interfacing with non ODBC based information sources Dynamically generate HTML to be returned to the client Set variables within the ColdFusion application page from which they are called Throw exceptions that result in standard ColdFusion error messages You can build CFX...

Page 411: ... OutputQuery Outputs a ColdFusion query in an HTML table Demonstrates how to handle a ColdFusion query as input throw exceptions and generate dynamic output HelloWorldGraphic Generates a Hello World graphic in JPEG format Demonstrates how to dynamically create and return graphics from a Java CFX Setting up your development environment to develop CFXs in Java You can use a wide range of Java develo...

Page 412: ...testing cycle When you create new Java CFXs you should develop and deploy them in the classes directory Following this guideline will dramatically simplify your development debugging and testing processes Once you are finished with development and testing you can then deploy your Java CFX anywhere on the class path visible to the ColdFusion embedded JVM See Customizing and Configuring Java for mor...

Page 413: ...sing the command line tools bundled with the JDK use the following command line which you execute from within the classes directory javac classpath cfx jar HelloColdFusion java Note The previous command works only if the Java compiler javac exe is in your path If it is not in your path specify the fully qualified path for example c jdk12 bin javac on Windows NT or usr java bin javac on UNIX If you...

Page 414: ... name row count and column names and methods for getting and setting data elements Method Description attributeExists Checks whether the attribute was passed to this tag getAttribute Retrieves the value of the passed attribute getIntAttribute Retrieves the value of the passed attribute as an integer getAttributeList Retrieves a list of all attributes passed to the tag getQuery Retrieves the query ...

Page 415: ...form casts to class or interface types that are loaded using the standard Java class path that is classes not located in the classes directory This works because classes loaded from outside the classes directory are always loaded using the system ClassLoader and therefore have a consistent runtime type Automatic class reloading You can determine how the server treats changed Java CFX class files b...

Page 416: ...t To store data and or objects that are accessible to all instances of your CustomTag use static data members If you do so you must ensure that all accesses to the data are thread safe Calling the CFX from a ColdFusion page You call Java CFXs from within ColdFusion pages by using the name of the CFX that is registered on the ColdFusion Administrator CFX tags page This name should be the prefix cfx...

Page 417: ...ntents and output the results you use the following CFML code cfx_ZipBrowser archive C logfiles zip name LogFiles cfoutput query LogFiles Name Size Compressed BR cfoutput The Java implementation of ZipBrowser is as follows import com allaire cfx import java util Hashtable import java io FileInputStream import java util zip public class ZipBrowser implements CustomTag public void processRequest Req...

Page 418: ...n existing process ColdFusion Server This makes debugging Java CFXs more difficult because you cannot use an interactive debugger to debug Java classes that have been loaded by another process To overcome this limitation you can use one of two techniques Debug the CFX while it is running within ColdFusion Server by outputting debug information as needed Debug the request in an interactive debugger...

Page 419: ...e context of the interactive debugger of a Java development environment The three debugging classes are DebugRequest An implementation of the Request interface that enables you to initialize the request with custom attributes settings and a query DebugResponse An implementation of the Response interface that enables you to print the results of a request once it has completed DebugQuery An implemen...

Page 420: ...tes put BORDER 3 initialize query String columns FIRSTNAME LASTNAME TITLE String data Stephen Cheng Vice President Joe Berrey Intern Adam Lipinski Director Lynne Teague Developer DebugQuery query new DebugQuery Employees columns data create tag process debug request and print results OutputQuery tag new OutputQuery DebugRequest request new DebugRequest attributes query DebugResponse response new D...

Page 421: ...u must enable the compiler to locate the CFXAPI header file cfx h On Windows NT you do this by adding the CFXAPI Include directory to your list of global include paths On Windows this directory is cfusion cfx include On UNIX it is opt coldfusion cfx include On UNIX you will need I includepath on your compile line see the Makefile for the directory list example in the cfx examples directory Using t...

Page 422: ...the Sun compiler Implementing C CFX tags CFX tags built in C use the tag request object represented by the C class CCFXRequest This object represents a request made from an application page to a custom tag A pointer to an instance of a request object is passed to the main procedure of a custom tag The methods available from the request object allow the custom tag to accomplish its work For a detai...

Page 423: ...u might need to set a breakpoint in main so the debugger loads the symbols for your CFX before you can set breakpoints in your code OS Debugger Other OS specific requirements Solaris dbx The environment variables must include LD_LIBRARY_PATH and CFHOME Use stop in main to set a breakpoint in main Linux gdb The environment variables must include LD_LIBRARY_PATH and CFHOME Use break main to set a br...

Page 424: ... tab select Extensions CFX Tags to opent the CFX Tags page 2 Click the Register C CFX button 3 Enter the Tag name for example cfx_MyNewTag 4 If the Server Library dll field is empty enter the file path 5 Accept the default Procedure entry 6 Clear the Keep library loaded box while developing the tag When the tag is ready for production use you can select this option to keep the DLL in memory for im...

Page 425: ...utility to export the registry entry from a machine on which the custom tag is already installed On Windows NT use Regedit to import custom tags to the registry On UNIX you must edit the registry data file located in opt coldfusion registry cf registry Entry Value Hive HKEY_LOCAL_MACHINE Key SOFTWARE Allaire ColdFusion CurrentVersion CustomTags TagName ClassName The name of the class to call Descr...

Page 426: ...gistry entry by including the following command in the install script regedit importfilename To import a C custom tag 1 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 LibraryPath C cfusion cfx CFX_TEST test dll ProcedureName ProcessTagRequest...

Page 427: ... 254 processing 216 Application level data and WDDX 347 Application level settings 214 Applications development considerations 16 development process 10 directory structure 216 217 error handling in 215 naming 219 storing variables 230 Area graphs setting appearance 74 Arguments custom function 251 optional 251 passing 252 ArrayAppend CFML function 119 ArrayDeleteAt CFML function 118 ArrayInsertAt...

Page 428: ...orm controls browser considerations 138 description 137 cfform tag passthrough attribute 136 usage notes 138 using with HTML 136 cfftp tag attributes 344 connection actions 344 using 341 cfgraph tag basic usage 61 common attributes 67 for bar charts 68 for line graphs 74 for pie charts 71 graphing queries 62 introduced 60 cfgraphdata tag 66 cfgrid tag browser considerations 138 controlling cell co...

Page 429: ... 82 syntax 25 using 25 using cfindex with 282 cfqueryparam tag 94 cfrethrow tag 204 CFScript custom function syntax 250 differences from JavaScript 248 example 244 expressions 245 function statement 250 interaction with CFML 249 language 245 reserved words 248 return statement 251 statements 244 var statement 251 cfsearch properties 281 cfsearch tag 270 external attribute 276 cfselect tag handling...

Page 430: ...managing 298 populating 276 populating from a query 282 searching 270 Columns in tables 19 COM and WDDX 345 connecting to objects 374 description 368 requirements 370 using properties and methods 375 viewing objects 371 COM DCOM getting started 370 Commas in search expressions 288 Comments CFML 16 CFScript 245 HTML 16 Common Object Request Broker Architecture See CORBA Compiling C CFX tags 402 Com...

Page 431: ... understanding 3 20 Data types about 13 default conversion 382 resolving ambiguous 382 validating 90 Database exceptions 207 Database Management System See DBMS Databases basics of 19 controlling access to 233 deleting multiple records 113 deleting one record 112 design 3 elements of 19 inserting data into 103 locking 233 retrieving data from 25 updating 106 datasource attribute 25 DateFormat CFML...

Page 432: ...e types 322 setting default values 89 setting file attributes 323 synchronizing file system access 241 testing for variables 88 user authentication and authorization 363 using cfauthenticate 359 using cfimpersonate 363 using Java objects 378 380 using StructInsert 130 using structures 132 validating an e mail address 144 validation error page 202 variable locking 238 Exception handling CIORBA obje...

Page 433: ...0 Headers including 172 Hidden fields 91 Horizontal bar charts 68 HTML and ColdFusion 10 knowing 3 using tables 49 using with cfform 136 HTMLEditFormat CFML function 311 353 HTTP URL problems 195 I if else CFScript statements 246 Impersonating with cfimpersonate 362 Implementing C CFX tags 402 Dynamic SQL 96 Java CFX tags 393 Importing C CFX tags 406 Java CFX tags 406 IN SQL operator 27 Indexing c...

Page 434: ...onthAsString CFML function 121 Moving data across the Web 345 server files 326 Multicharacter regular expressions for searching 263 for validation 141 Multiple selection lists 86 Multiple tables searching 52 N name cfquery attribute 25 Naming applications 219 variables 179 Naming conventions for custom exceptions 211 Navigating grids 155 Nested tags using Request scope 174 Nesting cflock tags 237 ...

Page 435: ...erencing array elements 119 REFind CFML function 266 REFindNoCase CFML function 266 Registering CFX tags 404 COM objects 371 Java applets 167 Registry exporting Client variables 227 storing Client variables 223 Regular expressions anchoring to search string 264 backreferences 142 265 character classes 261 common uses 267 examples 143 267 finding repeated words 265 for form validaton 140 for search...

Page 436: ...on 360 IsAuthorized example 365 overview 357 Web server 215 SELECT SQL statement 26 Selecting an indexing method 277 Selection lists multiple 86 Sending e mail 302 303 e mail to multiple recipients 305 form based e mail 304 mail as HTML 308 query based e mail 304 Serialization 347 Server scope 215 Server variables 215 built in 232 using 232 Servers remote 332 341 retrieving files from 332 uploadin...

Page 437: ... time out attribute cflock 235 Transferring data from browser to server 350 cftree tag See also Tree controls Tree controls structuring 150 Troubleshooting 195 U UNIX C debuggers 403 permissions 323 Updating a database with cfgridupdate 159 a database with cfquery 160 a structure with cfset 128 a structure with StructUpdate 128 data using forms 106 files 233 values in structures 128 Uploading file...

Page 438: ...ing data in strings 353 time zone processing 347 transferring data 350 Web accessing with cfhttp 332 application framework 214 overview of distributed data 345 Web Distributed Data Exchange See WDDX Web pages dynamic 18 saving 333 static 18 Web root directory 11 IP address of 11 localhost 11 Web server security 215 Web sites indexing 270 searching 270 WHERE SQL clause comparing with 45 description...

Reviews: