MACROMEDIA COLDFUSION 5-DEVELOPING Applications

Summary of COLDFUSION 5-DEVELOPING

  • Page 1

    Macromedia® incorporated developing coldfusion applications macromedia coldfusion ® 5.

  • Page 2: Copyright Notice

    Copyright notice © 1999–2001 macromedia incorporated. All rights reserved. This book, as well as the software described in it, is furnished under license and may be used or copied only in accordance with the terms of such license. The content of this manual is furnished for informational use only, i...

  • Page 3: Contents

    Contents about this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Xv intended audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Xvi new features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 4: . . . . . . . . .

    Iv contents working with variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 about variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 adding more variables to the application . ...

  • Page 5: Chapter 5 Graphing Data

    Developing web applications with coldfusion draft 5 / 9 / 0 1 p a t h / f i l e n a m e / a u t h o r v using html tables to display query results . . . . . . . . . . . . . . . . . . . . . . . . . . 49 formatting individual data items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 6: With Structures

    Vi contents data entry form notes and considerations . . . . . . . . . . . . . . . . . . . . . . . . . . 103 creating an action page to insert data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 updating data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 7: Chapter 10 Reusing Code

    Developing web applications with coldfusion draft 5 / 9 / 0 1 p a t h / f i l e n a m e / a u t h o r vii input validation with javascript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 handling failed validation . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 8: . . . . . . .

    Viii contents where is data accessible? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 high-level data exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 executing custom tags . . . . . . . . . . . . . . . . . . . . ....

  • Page 9: Scripting

    Developing web applications with coldfusion draft 5 / 9 / 0 1 p a t h / f i l e n a m e / a u t h o r ix client, session, application, and server scope variables . . . . . . . . . . . . . . 214 custom error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 10: . . . .

    X contents variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245 statements . . . . . . . . . . . . . . . ...

  • Page 11: . . . . . . . .

    Developing web applications with coldfusion draft 5 / 9 / 0 1 p a t h / f i l e n a m e / a u t h o r xi using query expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 simple query expressions . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 12: . . . . . .

    Xii contents evaluating the results of a file upload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 moving, renaming, copying, and deleting server files . . . . . . . . . . . . . . . . . . . . 326 reading, writing, and appending to a text file . . . . . . . . . . . . . . . ....

  • Page 13: 367

    Developing web applications with coldfusion draft 5 / 9 / 0 1 p a t h / f i l e n a m e / a u t h o r xiii authenticating users in application.Cfm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363 checking for authentication and authorization . . . . . . . . . . . . . . . . . . . . . 365 c...

  • Page 14: Index

    Xiv contents zipbrowser example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 approaches to debugging java cfxs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398 outputting debug information . . . . . . . . . . . . ...

  • Page 15: About This Book

    About this book developing coldfusion applications describes the process of developing web applications using coldfusion. In the first eight chapters, you can follow the instructions presented to learn how to create basic coldfusion applications. Then, chapters nine through 19 cover various topics o...

  • Page 16: Intended Audience

    Xvi about this book intended audience developing coldfusion applications is intended for web application programmers who are learning coldfusion orwish to extended their coldfusion programming knowledge. It provides a solid grouding in the tools that coldfusion provides to develop web applications. ...

  • Page 17: Developer Resources

    Developer resources xvii developer resources macromedia, inc. Is committed to setting the standard for customer support in developer education, technical support, and professional services. The web site is enhanced performance core engine tuning take advantage of dramatically improved server perform...

  • Page 18

    Xviii about this book designed to give you quick access to the entire range of online resources, as the following table describes. About coldfusion documentation coldfusion documentation is designed to provide support for the complete spectrum of participants. The print and online versions are organ...

  • Page 19: Viewing Online Documentation

    About coldfusion documentation xix printed and online documentation set the coldfusion documentation set consists of the following titles. Viewing online documentation all coldfusion documentation is available online in html and adobe acrobat pdf formats. To view the html documentation, open the fol...

  • Page 20: Getting Answers

    Xx about this book getting answers one of the best ways to solve particular programming problems is to tap into the vast expertise of the coldfusion developer communities on the coldfusion forums. Other developers on the forum can help you figure out how to do just about anything with coldfusion. Th...

  • Page 21: Introduction to Coldfusion

    Chapter 1 introduction to coldfusion this chapter explains the difference between creating static web pages with html and creating dynamic applications with coldfusion. It also describes what coldfusion is and how it works. Contents • a quick web overview................................................

  • Page 22: A Quick Web Overview

    2 chapter 1 introduction to coldfusion a quick web overview over the last few years, the web changed from being simply a collection of static html pages to an application development platform. Rather than offering a space where organizations can merely advertise goods and services, similar to tradit...

  • Page 23: Before You Begin

    Before you begin 3 before you begin before you begin using coldfusion to create your web applications, you should be familiar with html, relational database design and management, and structured query language (sql). Html you will find that coldfusion tags (cfml) are similar in syntax to html tags, ...

  • Page 24: What Is Coldfusion?

    4 chapter 1 introduction to coldfusion what is coldfusion? Coldfusion lets you create page-based web applications using coldfusion markup language (cfml), the tag-based language you use to create server-side scripts that dynamically control data integration; application logic; and user interface gen...

  • Page 25: About The Features

    Coldfusion features and components 5 coldfusion features and components coldfusion provides a comprehensive set of features and components for developing and managing your web applications. Using the coldfusion components, you can enhance the speed and ease of development, dynamically deploy your ap...

  • Page 26: About The Components

    6 chapter 1 introduction to coldfusion for detailed information about security, see advanced coldfusion administration. For the latest publications from macromedia on security, visit the security zone at http://www.Coldfusion.Com/developer/securityzone/. For a complete feature list and more detailed...

  • Page 27: Coldfusion Server

    Coldfusion features and components 7 data input and format data output. They can contain coldfusion (cfml) tags, html tags, cfscript, javascript, and anything else that you can normally embed in an ordinary html page. You can easily access data sources, such as relational databases, from your applic...

  • Page 28: How Coldfusion Server Works

    8 chapter 1 introduction to coldfusion how coldfusion server works regardless of which coldfusion server you have installed, coldfusion application pages are processed on the server at runtime, each time they are requested by a browser. A page request happens when you click a web site link to open a...

  • Page 29: Application

    Chapter 2 writing your first coldfusion application this chapter guides you through the coldfusion development process as you create a coldfusion application page, save it, and view it in a browser. Contents • the development process......................................................................

  • Page 30: The Development Process

    10 chapter 2 writing your first coldfusion application the development process whether you are creating a static html page or a coldfusion application page, you follow the same iterative process: 1 write some code. 2 save the code to a document or page. 3 view the page in a browser. 4 modify the pag...

  • Page 31: Saving Application Pages

    Working with coldfusion application pages 11 i’d like to talk to someone in #department#. Saving application pages instead of saving pages with an htm or html file extension, you save coldfusion application pages with a cfm or cfml extension. By default, the web server knows to pass a page that cont...

  • Page 32

    12 chapter 2 writing your first coldfusion application compare the code that was returned to the browser with what you originally created. Notice that the coldfusion comments and cfml tags are processed, but do not appear in the html file that is returned to the browser. Reviewing the code the appli...

  • Page 33: Working With Variables

    Working with variables 13 working with variables a web application page is different from a static web page because it can publish data dynamically. This involves creating, manipulating, and outputting variables. A variable stores data that you can use in applications. As with other programming lang...

  • Page 34: Using The Pound Sign (#)

    14 chapter 2 writing your first coldfusion application you can write: i’d like to talk to someone in #variables.Department#. Some variable scopes, such as the local scope, do not require the scope identifier prefix, while others do. However, it is good programming practice to use prefixes for most o...

  • Page 35

    Working with variables 15 adding more variables to the application applications can use many different variables. For example, the calldept.Cfm application page can set and display values for department, city, and salary. To modify the application: 1 open the file calldept.Cfm in coldfusion studio,....

  • Page 36: Development Considerations

    16 chapter 2 writing your first coldfusion application 4 view the page in your web browser by entering the following url: http://127.0.0.1/myapps/calldept.Cfm. Development considerations the same development rules that apply for any programming environment apply to coldfusion. You should also follow...

  • Page 37: Querying A Database

    Chapter 3 querying a database this chapter describes how to retrieve data from a database, work with query data, and enable debugging in coldfusion applications. You will learn how to use the coldfusion administrator to set up a data source and enable debugging, use the cfquery tag to query a data s...

  • Page 38: Publishing Dynamic Data

    18 chapter 3 querying a database publishing dynamic data a web application page is different from a static web page because it can publish data dynamically. This can involve querying databases, connecting to ldap or mail servers, and leveraging com, dcom, corba, or java objects to retrieve, update, ...

  • Page 39

    Understanding database basics 19 understanding database basics you do not need a thorough knowledge of databases to develop a data-driven coldfusion application, but you need to know some basic concepts and techniques. A database is a structure for storing information. Databases are organized in tab...

  • Page 40: Database Design Guidelines

    20 chapter 3 querying a database database design guidelines from this basic description, a few database design rules emerge: • each record should contain a unique identifier, known as the primary key. This can be an employee id, a part number, or a customer number. The primary key is typically the c...

  • Page 41: Accessing Data Sources

    Accessing data sources 21 • borland dbase-compliant databases • microsoft excel worksheet data ranges • borland paradox databases • informix databases • progress databases • oracle 8 databases • centura sqlbase databases • sybase ase databases • delimited text files you can also use any additional o...

  • Page 42: Adding Data Sources

    22 chapter 3 querying a database adding data sources you use the coldfusion administrator to add data sources to the coldfusion administrator. When you add a data source, you assign it a name so that you can reference it within tags such as cfquery on application pages to query databases. During a q...

  • Page 43

    Accessing data sources 23 4 name the data source companyinfo . 5 on windows select microsoft access driver (*.Mdb) from the drop-down box to describe the odbc driver. On unix, select the merant dbase/foxpro driver. 6 click add. 7 in the database file field, enter the full path of the database. (you ...

  • Page 44

    24 chapter 3 querying a database adding data source notes and considerations when adding data sources to coldfusion server, keep these guidelines in mind: • data source names should be all one word and begin with a letter. • data source names can contain only letters, numbers, and the underscore. • ...

  • Page 45: Retrieving Data

    Retrieving data 25 retrieving data you can query databases to retrieve data at runtime. The retrieved data, called the result set, is stored on that page as a query object. When retrieving data from a database, perform the following tasks: • use the cfquery tag on a page to tell coldfusion how to co...

  • Page 46: Writing Sql

    26 chapter 3 querying a database • when referencing text literals in sql, use single quotes (’). For example, select * from mytable where firstname=’russ’ selects every record from mytable in which the first name is russ. Writing sql in between the begin and end cfquery tags, write the sql that you ...

  • Page 47: Statement Clauses

    Writing sql 27 statement clauses use the following keywords to refine sql statements: operators the following basic operators specify conditions and perform logical and numeric functions: sql notes and considerations when writing sql in coldfusion, keep the following guidelines in mind: • there is a...

  • Page 48: Building Queries

    28 chapter 3 querying a database • some dbms vendors use nonstandard sql syntax (known as a dialect) in their products. Coldfusion does not validate the sql in a cfquery , so you are free to use any syntax that is supported by your data source. Check your dbms documentation for nonstandard sql usage...

  • Page 49

    Building queries 29 reviewing the code the query you just created retrieves data from the companyinfo database. The following table describes the code and its function: query notes and considerations when creating queries to retrieve data, keep the following guidelines in mind: • enter the query nam...

  • Page 50: Outputting Query Data

    30 chapter 3 querying a database outputting query data after you define a query on a page, you can use the cfoutput tag with the query attribute to specify the query object that contains the data you want to output to a page. When you use the query attribute: • coldfusion loops over all the code con...

  • Page 51

    Outputting query data 31 you now display the results of the query on the page. The following table describes the code and its function: query output notes and considerations when outputting query results, keep the following guidelines in mind: • a cfquery must precede the cfoutput that references it...

  • Page 52

    32 chapter 3 querying a database getting information about query results each time you query a database with the cfquery tag, you get not only the data itself, but also query properties, as described in the following table: to output query data on your page: 1 return to emplist.Cfm in coldfusion stu...

  • Page 53

    Getting information about query results 33 you now display the number of records retrieved in the query. The following table describes the code and its function: query properties notes and considerations when using query properties, keep the following guidelines in mind: • reference the query proper...

  • Page 54: Query Of Query Benefits

    34 chapter 3 querying a database using query results in queries coldfusion allows you to use the results of a previous query in any cfquery tag that returns row data to coldfusion. You can query a database once and use the results in several dependent queries. Queries generated from other queries ar...

  • Page 55

    Using query results in queries 35 you can also do the following tasks: • use the results of one or two queries in your sql statement. • generate computed columns. Performing a query on a query to generate a query using an existing query: • specify the cfquery tag’s dbtype attribute as " query". • do...

  • Page 56

    36 chapter 3 querying a database to use the results of a query in a query: 1 create a new application page in coldfusion studio. 2 edit the page so that it appears as follows: cachedwithin=#createtimespan(0,1,0,0)#> select * from employee cachedwithin=#createtimespan(0,1,0,0)#> select * from employe...

  • Page 57

    Using query results in queries 37 reviewing the code the page retrieves the entire employee table from the companyinfo database. A second query selects only the three columns to display for employees with the specified last name. The following table describes the code and its function: code descript...

  • Page 58

    38 chapter 3 querying a database.

  • Page 59: Contents

    Chapter 4 retrieving and formatting data this chapter explains how to select the data to display in a dynamic web page. It also describes how to populate an html table with query results and how to use coldfusion functions to format and manipulate data. Contents • using forms to specify the data to ...

  • Page 60: Form Tag Syntax

    40 chapter 4 retrieving and formatting data using forms to specify the data to retrieve in the examples in previous chapters, you have retrieved all of the records from a table. However, there are many instances when you want to retrieve data based on certain criteria. For example, you might want to...

  • Page 61: Form Controls

    Using forms to specify the data to retrieve 41 action="runreport.Cfm?Requesttimeout=120" method="post"> form controls within the form, you describe the form controls needed to gather and submit user input. There are a variety of form controls types available. You choose form control input types base...

  • Page 62

    42 chapter 4 retrieving and formatting data use the following procedure to create a sample form. To create a form 1 create a new application page, using coldfusion studio. 2 edit the page so that it appears as follows: first name: maxlength="35"> last name: maxlength="35"> salary: city arlington bos...

  • Page 63

    Using forms to specify the data to retrieve 43 contractor? Checked>yes 3 save the page as formpage.Cfm within the myapps directory under your web root directory. 4 view the form in a browser. The form appears in the browser. Remember that you need an action page in order to submit values; you will c...

  • Page 64

    44 chapter 4 retrieving and formatting data form notes and considerations • to make the coding process easy to follow, name form controls the same as target database fields. • for ease of use, limit radio buttons to between three and five mutually exclusive options. If you need more options, conside...

  • Page 65: Working With Action Pages

    Working with action pages 45 working with action pages a coldfusion action page is just like any other application page except that you can use the form variables that are passed to it from an associated form. The following sections describe how to create effective action pages. Processing form vari...

  • Page 66: Creating Action Pages

    46 chapter 4 retrieving and formatting data however, instead of putting the lastname directly in the sql where clause, you can use the text that the user entered in the form for comparison: select firstname, lastname, salary from employee where lastname="#form.Lastname#" for more information on dyna...

  • Page 67

    Working with action pages 47 this time an error occurs because the check box does not pass a variable to the action page. Reviewing the code the following table describes the highlighted code and its function: testing for a variable’s existence before relying on a variable’s existence in an applicat...

  • Page 68

    48 chapter 4 retrieving and formatting data the argument passed to the isdefined function must always be enclosed in double quotes. For more information on the isdefined function, see the cfml reference. If you attempt to evaluate a variable that you did not define, coldfusion cannot process the pag...

  • Page 69

    Working with queries and data 49 working with queries and data the ability to generate and display query data is one of the most important and flexible features of coldfusion. The following sections further your understanding of using queries and displaying their results. Some of these tools are eff...

  • Page 70

    50 chapter 4 retrieving and formatting data 3 save the page as actionpage.Cfm within the myapps directory. 4 view formpage.Cfm in your browser. 5 enter smith in the last name text box and submit the form. 6 the records that match the criteria specified in the form appear in a table. Reviewing the co...

  • Page 71

    Working with queries and data 51 performing pattern matching use the sql like operator and sql wildcard strings in a sql where clause when you want to compare a value against a character string field so that the query returns database information based on commonalities. This technique is known as pa...

  • Page 72: Creating Table Joins

    52 chapter 4 retrieving and formatting data creating table joins many times, the data that you want to retrieve is maintained in multiple tables. For example, in the database that you are working with: • department information is maintained in the departmt table. This includes department id numbers....

  • Page 73

    Working with queries and data 53 the following action page allows users to search for employees by department, last name, or both. To build a more flexible search interface: 1 open the page a ctionpage.Cfm in coldfusion studio. 2 modify the page so that it appears as follows: select departmt.Dept_na...

  • Page 74

    54 chapter 4 retrieving and formatting data reviewing the code the following table describes the highlighted code and its function: code description select departmt.Dept_name, employee.Firstname, employee.Lastname, employee.Startdate, employee.Salary from departmt, employee where departmt.Dept_id = ...

  • Page 75

    Returning results to the user 55 returning results to the user when you return your results to the user, you must make sure that your pages respond to the user’s needs and are appropriate for the type and amount of information. In particular you must consider the following situations: • when there a...

  • Page 76

    56 chapter 4 retrieving and formatting data and employee.Lastname = ’#form.Lastname#’ no records match your search criteria. Please go back to the form and try again. 3 save the file. 4 return to the form, enter search criteria and submit the form. 5 if no records match the criteria you specified, t...

  • Page 77

    Returning results to the user 57 when you flush data, make sure that a sufficient amount of information is available, because some browsers might not respond if you flush only a very small amount. Similarly, if you use an interval attribute, set it for a reasonable size, such as a few hundred bytes ...

  • Page 78

    58 chapter 4 retrieving and formatting data reviewing the code the following table describes the code and its function: code description worth the short wait! Send the html header and all html output to the cfflush tag to the user. This displays the explanatory paragraph and h2 tag contents. Flush a...

  • Page 79: Graphing Data

    Chapter 5 graphing data this chapter explains how to use the cfgraph tag to display graphs. It illustrates 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 coldfu...

  • Page 80: Creating A Graph

    60 chapter 5 graphing data creating a graph the cfgraph tag provides five graph types. A large 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 be...

  • Page 81: Creating A Basic Graph

    Creating a graph 61 creating a basic graph you use the following cfgraph attributes to create a basic graph: you must end your cfgraph tag with a end tag. For example, if you have a query that contains average salary by department, the following tag displays a bar graph with the information: query="...

  • Page 82: Graphing Data

    62 chapter 5 graphing data graphing data one of the most important considerations when you graph data is the way you supply the data to the cfgraph tag. You can supply data in several ways: • provide all the data in a single query. • specify individual data points using cfgraphdata tags. • combine d...

  • Page 83

    Graphing data 63 the ability to use queries of queries, as described in chapter 3, “using query results in queries” on page 34 provides significant power in generating the data for the chart. For example, you can use aggregating clauses operators such as sum, avg, and group by to create a query of q...

  • Page 84

    64 chapter 5 graphing data select dept_name, avg(salary) as avgbydept from getsalaries group by dept_name 1000)*1000> 1000)*1000> query="deptsalaries" valuecolumn="avgbydept" itemcolumn="dept_name"> query="deptsalaries" valuecolumn="avgbydept" itemcolumn="dept_name"> 3 save the page as graphdata.Cfm...

  • Page 85

    Graphing data 65 reviewing the code the following table describes the code and its function: graphing individual data points when you graph individual data points you specify each data point by putting a cfgraphdata tag in the cfgraph tag body. For example, the following code creates a simple pie ch...

  • Page 86

    66 chapter 5 graphing data this pie chart displays the income values of four departments. Each cfgraph tag specifies a department’s income and the corresponding item description for the legend. The values are specified by individual coldfusion variables. The title “income by department” appears abov...

  • Page 87

    Controlling graph appearance 67 controlling graph appearance the cfgraph tag allows you to customize the appearance of your graph in many ways. Common graph characteristics you can optionally specify the following characteristics on all types of graphs: graph characteristic attributes used descripti...

  • Page 88

    68 chapter 5 graphing data setting bar and horizontal bar chart characteristics you can specify the following additional characteristics for bar and horizontal bar charts: graph characteristic attributes used description value labels showvaluelabel valuelabelfont valuelabelsize valuelocation labels ...

  • Page 89

    Controlling graph appearance 69 example: adding character to a bar graph the example in the following procedure adds a title to the bar graph and changes its appearance from the default, flat look, to a 3d look. It adds gridlines, sets the maximum y-axis value to 100000, separates the bars, and uses...

  • Page 90

    70 chapter 5 graphing data 4 return to your browser and enter the following url to view graphdata.Cfm: http://127.0.0.1/myapps/graphdata.Cfm reviewing the code the following table describes the highlighted code and its function: code description title = "average salary by department" put a title abo...

  • Page 91

    Controlling graph appearance 71 setting pie chart characteristics you can specify the following additional characteristics for pie charts: graph characteristic attributes used description value labels showvaluelabel valuelabelfont valuelabelsize valuelocation labels that display the numeric value be...

  • Page 92: Example: Adding A Pie Chart

    72 chapter 5 graphing data example: adding a pie chart the example in the following procedure adds a pie chart to the page. To create a pie chart: 1 open graphdata.Cfm in coldfusion studio. 2 edit the deptsalaries query and the cfloop code so that they appear as follows: select dept_name, sum(salary...

  • Page 93

    Controlling graph appearance 73 reviewing the code the following table describes the highlighted code and its function: code description sum(salary) as sumbydept, in the deptsalaries query, add a sum aggregation function to get the sum of all salaries per department. Round(deptsalaries.Sumbydept[i]/...

  • Page 94

    74 chapter 5 graphing data setting line and area graph characteristics you can specify the following additional characteristics for line-based graphs example: adding an area graph the example in the following procedure adds an area graph showing the average salary by start date to the salaries analy...

  • Page 95

    Controlling graph appearance 75 2 edit the getsalaries query so that it appears as follows: select departmt.Dept_name, employee.Startdate, employee.Salary from departmt, employee where departmt.Dept_id = employee.Dept_id 3 add the following code before the html tag: getsalaries.Startdate[i]) ,9999)>...

  • Page 96

    76 chapter 5 graphing data 6 return to your browser and enter the following url to view graphdata.Cfm: http://127.0.0.1/myapps/graphdata.Cfm reviewing the code the following table describes the highlighted code and its function: code description employee.Startdate, add the employee start date to the...

  • Page 97

    Linking dynamically from graphs 77 linking dynamically from graphs you can make flash-format bar and pie charts interactive so that coldfusion displays a new data point–specific web page when the user clicks a bar or pie wedge. Coldfusion provides two methods for specifying the destination page: • f...

  • Page 98

    78 chapter 5 graphing data order by employee.Lastname, employee.Firstname salary details 3 save the page as salary_details.Cfm in myapps under the web root directory..

  • Page 99

    Linking dynamically from graphs 79 reviewing the code the following table describes the code and its function: part 2: making the graph dynamic 1 open graphdata.Cfm in coldfusion studio. 2 edit the cfgraph tag for the pie chart so it appears as follows: query="deptsalaries" valuecolumn="sumbydept" i...

  • Page 100

    80 chapter 5 graphing data title="total salaries by department" titlefont="times" showvaluelabel="rollover" valuelabelfont="times" backgroundcolor = "##ccffff" borderwidth = 0 colorlist="##6666ff,##66ff66,##ff6666,##66cccc" legendfont="times"> 3 save the page. 4 return to your browser and enter the ...

  • Page 101: Making Variables Dynamic

    Chapter 6 making variables dynamic this chapter explains how to use cfml to dynamically populate forms and dynamically generate sql. It also discusses ways to make sure that variables exist and have valid data because this information is important to effectively use dynamic data. Contents • dynamica...

  • Page 102

    82 chapter 6 making variables dynamic dynamically populating list boxes in chapter 4, you hard-coded a form’s list box options. Instead of manually entering the information on a form, you can dynamically populate a list box with database fields. When you code this way, the form page automatically re...

  • Page 103

    Dynamically populating list boxes 83 department: training sales value="marketing">marketing hr contractor? Checked>yes 3 save the page as formpage.Cfm. 4 view formpage.Cfm in a browser. The changes that you just made appear in the form. Remember that you need an action page to submit values. Reviewi...

  • Page 104: List Boxes

    84 chapter 6 making variables dynamic creating dynamic check boxes and multiple-selection list boxes when an html form contains either a list of check boxes with the same name or a multiple-selection list box (that is, where users can select multiple items from the list), the user’s entries are made...

  • Page 105: Searching String Values

    Creating dynamic check boxes and multiple-selection list boxes 85 the user sees the name of the department, but the value attribute of each check box is a number that corresponds to the underlying database primary key for the department’s record. If the user checks the marketing and sales items, the...

  • Page 106: Multiple Selection Lists

    86 chapter 6 making variables dynamic note in sql, all strings must be surrounded in single quotes. The listqualify function returns a list with the specified qualifying character (here, a single quote) around each item in the list. If you select the second and fourth check boxes in the form, the fo...

  • Page 107: Searching String Values

    Creating dynamic check boxes and multiple-selection list boxes 87 searching string values suppose you want the user to select departments from a multiple selection list box. The database search field is a string field. The query retrieves detailed information on the selected department(s): training ...

  • Page 108

    88 chapter 6 making variables dynamic ensuring that variables exist the sample code in the previous sections is incomplete. Either the form or the action page should make sure that the selectdepts variable has a value before it is used in the sql select statement. Otherwise, users who do not select ...

  • Page 109

    Ensuring that variables exist 89 for example, the following series of cfparam tags indicates that this page expects two form variables named startrow and rowstofetch: if the page with these tags is called without either one of the form variables, an error occurs and the page stops processing. By def...

  • Page 110: Validating Data Types

    90 chapter 6 making variables dynamic validating data types it is often not sufficient that input data merely exists; it must also have the right format. For example, a date field must have data in a date format. A salary field must have data in a numeric or currency format. There are many ways to e...

  • Page 111

    Validating data types 91 if the variable is not in a valid date format, an error occurs and the page stops processing. Validating form field data types one limitation of standard html forms is that you cannot validate that users input the type or range of data you expect. Coldfusion enables you to d...

  • Page 112

    92 chapter 6 making variables dynamic using a single page for both the form and action provides the opportunity to illustrate the use of the isdefined function to check that data exists. This way, the form does not show any results until you submit the input. To validate the data that users enter in...

  • Page 113

    Validating data types 93 3 save the file as datatest.Cfm. 4 view the file in your browser, omit a field or enter invalid data, and click the submit button. When the user submits the form, coldfusion scans the form fields to find any validation rules you specified. The rules are then used to analyze ...

  • Page 114

    94 chapter 6 making variables dynamic checking query parameters with cfqueryparam you can use the cfqueryparam tag to validate sql query parameters. This tag can validate the value of the sql query parameter against a sql data type such as real, time, or date. The cfqueryparam tag validates the data...

  • Page 115

    Validating data types 95 the following example shows the use of cfqueryparam when valid input is given in the course_id variable used as a query parameter. To see what happens when you use invalid data, substitute a text string such as “test” for the integer 12 in the cfset statement. Note that this...

  • Page 116: Dynamic Sql

    96 chapter 6 making variables dynamic dynamic sql embedding sql queries that use dynamic parameters is a powerful mechanism for linking variable inputs to database queries. However, in more sophisticated applications, you often want user inputs to determine not only the content of queries but also t...

  • Page 117: Creating The Input Form

    Dynamic sql 97 creating the input form first, you need to create an input form, which asks for information about several fields in the employee table. To search for data based on only the fields the user enters in the form, you use cfif statements in the sql statement. To create the input form: 1 cr...

  • Page 118: Creating The Action Page

    98 chapter 6 making variables dynamic creating the action page after you create the input form, you can create the action page to process the user’s request. This action page determines where the user entered search criteria and searches based only on those criteria. To create the action page: 1 cre...

  • Page 119

    Dynamic sql 99 3 save the page as getemp.Cfm . 4 open the file askemp.Cfm in your browser and enter criteria into any fields, then submit the form. 5 verify that the results meet the criteria you specify. Reviewing the code the action page getemp.Cfm builds a sql statement dynamically based on what ...

  • Page 120

    100 chapter 6 making variables dynamic employee.Contract = ‘yes' and employee.Contract = 'no' and if the user selected the contractor check box, get data for the employees who are contractors; otherwise, get data for employees who are not contractors. The isdefined function test for the existence of...

  • Page 121: Updating Your Database

    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 ........................

  • Page 122: Inserting Data

    102 chapter 7 updating your database inserting data you usually use two application pages to insert data into a database: • an insert form • an insert action page you can create an insert form with standard html form tags or with cfform tags (see “creating forms with the cfform tag” on page 136). Wh...

  • Page 123

    Inserting data 103 3 save the file as insertform.Cfm in the myapps directory. 4 view insertform.Cfm in a browser. Data entry form notes and considerations if you use the cfinsert tag in the action page to insert the data into the database, you should follow these rules for creating the form page: • ...

  • Page 124

    104 chapter 7 updating your database 3 save the page as insertaction.Cfm. 4 view insertform.Cfm in a browser, enter values, and click the submit button. 5 the data is inserted into the employee table and the message displays. Reviewing the code the following table describes the code and its function...

  • Page 125

    Inserting data 105 creating an insert action page with cfquery for more complex inserts from a form submittal you can use a sql insert statement in a cfquery tag instead of a cfinsert tag. The sql insert statement is more flexible because you can insert information selectively or use functions withi...

  • Page 126: Updating Data

    106 chapter 7 updating your database reviewing the code the following table describes the highlighted code and its function: updating data you usually use two application pages to update data in a database: • an update form • an update action page you can create an update form with cfform tags or ht...

  • Page 127

    Updating data 107 to create an update form: 1 create a new page in coldfusion studio. 2 edit the page so that it appears as follows: datasource="companyinfo"> select * from employee where emp_id = #url.Emp_id# datasource="companyinfo"> select * from employee where emp_id = #url.Emp_id# value="#emp_i...

  • Page 128

    108 chapter 7 updating your database reviewing the code the following table describes the code and its function: code description datasource="companyinfo"> select * from employee where emp_id = #url.Emp_id# datasource="companyinfo"> select * from employee where emp_id = #url.Emp_id# query the compan...

  • Page 129

    Updating data 109 creating an action page to update data you can create an action page to update data with either the cfupdate tag or cfquery with the update statement. Creating an update action page with cfupdate the cfupdate tag is the easiest way to handle simple updates from a front end form. Th...

  • Page 130

    110 chapter 7 updating your database reviewing the code the following table describes the code and its function: creating an update action page with cfquery for more complicated updates, you can use a sql update statement in a cfquery tag instead of a cfupdate tag. The sql update statement is more f...

  • Page 131

    Updating data 111 you have updated the information for #form.Firstname# #form.Lastname# in the employees database. 3 save the page. 4 view updateform.Cfm in a browser by specifying the page url and an employee id, for example, http://localhost/myapps/updateform.Cfm?Emp_id=3. Enter new values in any ...

  • Page 132: Deleting Data

    112 chapter 7 updating your database deleting data you use a cfquery tag with a sql delete statement to delete data from a database. Deleting a single record to delete a single record, use the table’s primary key in the where condition of a sql delete statement. In the example, the emp_id field is t...

  • Page 133: Deleting Multiple Records

    Deleting data 113 8 view deleteform.Cfm a browser by specifying the page url and an employee id, for example, http://localhost/myapps/updateform.Cfm?Emp_id=3. And click the submit button. The employee is deleted from the employee table and the message displays. Reviewing the code the following table...

  • Page 134

    114 chapter 7 updating your database.

  • Page 135: Handling Complex Data

    Chapter 8 handling complex data with structures coldfusion supports dynamic multidimensional arrays. This chapter explains the basics of creating and handling arrays. It also provides several examples showing how arrays can enhance your coldfusion application code. Coldfusion also supports structure...

  • Page 136: About Arrays

    116 chapter 8 handling complex data with structures about arrays traditionally, an array is a tabular structure used to hold data, much like a spreadsheet table with clearly defined limits and dimensions. A two-dimensional (2d) array is like a simple table. In coldfusion, you typically use arrays to...

  • Page 137: Coldfusion Dynamic 2D Array

    About arrays 117 coldfusion dynamic 2d array a coldfusion 2d array is actually a one-dimensional array that contains a series of additional 1d arrays. Each of the arrays that make up a row can expand and contract independently of any other column. The following terms will help you understand subsequ...

  • Page 138: Basic Array Techniques

    118 chapter 8 handling complex data with structures basic array techniques to use arrays in coldfusion, as in other languages, you need to first declare the array, specifying its dimension. Once it is declared, you can add array elements, which you can then reference by index. As an example, suppose...

  • Page 139

    Basic array techniques 119 creating multidimensional arrays coldfusion supports dynamic multidimensional arrays. When you declare an array with the arraynew function, you can specify up to three dimensions. However, you can increase an array’s dimensions by nesting arrays as array elements: adding e...

  • Page 140

    120 chapter 8 handling complex data with structures #fullname[1][1]# #fullname[2][1]# #fullname[1][2]# #fullname[2][2]# #fullname[1][3]# #fullname[2][3]# #fullname[1][1]# #fullname[2][3]# note that because this is a full 2d array, you can easily output names that do not make sense in the real world....

  • Page 141

    Populating arrays with data 121 populating arrays with data array elements can store any values, including queries, structures, and other arrays. You can use a number of functions to populate an array with data, including arrayset , arrayappend , arrayinsertat , and arrayprepend . These functions ar...

  • Page 142

    122 chapter 8 handling complex data with structures using nested loops for 2d and 3d arrays to output values from 2d and 3d arrays, you must employ nested loops to return array data. With a 1d array, a single cfloop is sufficient to output data, as in the previous example. With arrays of dimension g...

  • Page 143

    Populating arrays with data 123 populating an array from a query when populating an array from a query, keep the following things in mind: • query data cannot be added to an array all at once. A looping structure is generally required to populate an array from a query. • query column data can be ref...

  • Page 144: Array Functions

    124 chapter 8 handling complex data with structures array functions the following functions are available for creating, editing, and handling arrays: for more information about each of these functions, see the cfml reference. Function description arrayappend appends an array element to the end of a ...

  • Page 145: About Structures

    About structures 125 about structures coldfusion structures consist of key-value pairs. Structures let you build a collection of related variables that are grouped under a single name. You can define coldfusion structures dynamically. You can use structures to refer to related values as a unit rathe...

  • Page 146: Structure Notation

    126 chapter 8 handling complex data with structures structure notation coldfusion supports three types of notation for structures. Which notation you use depends on your needs: notation description object.Property use to refer to values in a structure. You can refer to a property, prop, of an object...

  • Page 147: Creating Structures

    Creating and using structures 127 creating and using structures this section explains how to use the structure functions to create and use structures in coldfusion. The sample code in this section uses a structure called employee, which is used to add new employees to a corporate information system....

  • Page 148

    128 chapter 8 handling complex data with structures updating values in structures you can update structure element values in a cfset tag or a sructupdate function. Updating a structure with cfset you can use the cfset tag to update structure values (but not keys). For example, the following code use...

  • Page 149

    Creating and using structures 129 getting information about structures to find out if a given value represents a structure, use the isstruct function: isstruct(variable) this function returns true if variable is a structure. Structures are not indexed numerically, so to find out how many name-value ...

  • Page 150: Copying Structures

    130 chapter 8 handling complex data with structures copying structures to copy a structure, use the structcopy function. This function takes the name of the structure that you want to copy and returns a new structure with all the keys and values of the named structure. Structcopy(structure) this fun...

  • Page 151

    Creating and using structures 131 please fill out the form. Employee=structnew(); structinsert(employee, "firstname", "#form.Firstname#"); structinsert(employee, "lastname", "#form.Lastname#"); structinsert(employee, "email", "#form.Email#"); structinsert(employee, "phone", "#form.Phone#"); structin...

  • Page 152: Looping Through Structures

    132 chapter 8 handling complex data with structures example file addemployee.Cfm error. No employee data was passed. Insert into employees (firstname, lastname, email, phone, department) values ( ’#structfind(attributes.Empinfo, "firstname")#’ , ’#structfind(attributes.Empinfo, "lastname")#’ , ’#str...

  • Page 153: Structure Functions

    Structure functions 133 structure functions use the following functions to create and manage structures in coldfusion applications: function description isstruct returns true if the specified variable is a structure. Structclear removes all data from the specified structure. Structcopy returns a new...

  • Page 154

    134 chapter 8 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: Building Dynamic Forms

    Chapter 9 building dynamic forms this chapter shows you how to use the cfform tag to enrich your forms with sophisticated graphical controls, including several java applet-based controls. You can use these controls without writing a line of java code. Contents • creating forms with the cfform tag .....

  • Page 156: Using Html And Cfform

    136 chapter 9 building dynamic forms creating forms with the cfform tag you already learned how to use html forms to gather user input (see “using forms to specify the data to retrieve” on page 40). This chapter shows you how to use the cfform tag to create dynamic forms in cfml. In addition to html...

  • Page 157: Cfform Controls

    Creating forms with the cfform tag 137 cfform controls the following table describes the controls coldfusion controls you use in forms created using cfform : preserving input data with preservedata the cfform attribute preservedata tells coldfusion to continue displaying the data that a user entered...

  • Page 158: Usage Notes

    138 chapter 9 building dynamic forms usage notes • in cftree , the preservedata attribute causes the tree to expand the tree to the previously selected element. For this to work correctly, you must also set the completepath attribute to true. • the preservedata attribute has no effect on cfgrid . If...

  • Page 159

    Input validation with cfform controls 139 input validation with cfform controls the cfinput and cftextinput tags include the validate attributes which allows you to specify a valid data entry type for the control. You can validate user entries on the following data types. When you specify an input t...

  • Page 160: Special Characters

    140 chapter 9 building dynamic forms validating with regular expressions you can use regular expressions to match and validate the text that users enter in cfinput and cftextinput tags. Ordinary characters are combined with special characters to define the match pattern. The validation succeeds only...

  • Page 161

    Input validation with cfform controls 141 • if the first character of a set of characters in bracket is the caret (^), the expression matches any character except those in the set. It does not match the empty string. For example: [^akm] matches any character except "a", "k", or "m". The caret loses ...

  • Page 162: Backreferences

    142 chapter 9 building dynamic forms • a one-character regular expression or grouped subexpression followed by a plus (+) matches one or more occurrences of the regular expression. For example, [a-z]+ matches one or more lowercase characters. • a one-character regular expression or grouped subexpres...

  • Page 163: Expression Examples

    Input validation with cfform controls 143 expression examples the following examples show some regular expressions and describe what they match: resources an excellent reference on regular expressions is mastering regular expressions by jeffrey e.F. Friedl, published by o’reilly & associates, inc. E...

  • Page 164: Handling Failed Validation

    144 chapter 9 building dynamic forms input validation with javascript in addition to native coldfusion input validation using the validate attribute of the cfinput and cftextinput tags, the following tags support the onvalidate attribute, which allows you to specify a javascript function to handle y...

  • Page 165

    Input validation with javascript 145 to use javascript to validate form data: 1 create a new file in coldfusion studio. 2 edit the page so that it appears as follows: please enter your email address: action="validjs.Cfm" > name="inputbox1" required="yes" onvalidate="testbox" message="sorry, your ent...

  • Page 166

    146 chapter 9 building dynamic forms reviewing the code the following table describes the highlight code and its function: see the following web site for information on javascript validation scripts: http:// www.Dannyg.Com/javascript. Code description javascript code to test for valid entry in the t...

  • Page 167

    Building tree controls with cftree 147 building tree controls with cftree the cftree form lets you display hierarchical information in a space-saving collapsible tree populated from data source queries. To build a tree control with cftree , you use individual cftreeitem tags to populate the control....

  • Page 168

    148 chapter 9 building dynamic forms grouping output from a query in a query that you display using a cftree control, you might want to organize your employees by the department. In this case, you separate column names with commas in the cftreeitem value attribute. To organize the tree based on orde...

  • Page 169: Cftree Form Variables

    Building tree controls with cftree 149 reviewing the code the following table describes the highlight code and its function: note that the cftreeitem comma-separated img and the value attributes both correspond to the tree level structure. If you leave out the img attribute, coldfusion uses the fold...

  • Page 170: Structuring Tree Controls

    150 chapter 9 building dynamic forms structuring tree controls tree controls built with cftree can be very complex. Knowing how to specify the relationship between multiple cftreeitem entries will help you handle even the most complex of cftree constructs. Example: one-level tree control this exampl...

  • Page 171: Image Names In A Cftree

    Structuring tree controls 151 parent="divisions" img="folder"> parent="qa"> parent="qa"> parent="divisions" img="fixed"> parent="support"> parent="divisions" img="cd"> parent="divisions" img="document"> parent="divisions" img="element"> image names in a cftree when you use the img attribute, coldfus...

  • Page 172: Embedding Urls In A Cftree

    152 chapter 9 building dynamic forms embedding urls in a cftree the href attribute in the cftreeitem tag allows you to designate tree items as links. To use this feature in a cftree , you simply define the destination of the link in the href attribute of cftreeitem . The url for the link can be a re...

  • Page 173

    Creating data grids with cfgrid 153 specifying the tree item in the url when a user clicks on a tree item to link to a url the cftreeitemkey variable, which identifies the selected value, is appended to the url in the form: http://myserver.Com?Cftreeitemkey =selected_value automatically passing the ...

  • Page 174

    154 chapter 9 building dynamic forms populating a grid from a query to populate a grid from a query: 1 open a new file named grid1.Cfm in coldfusion studio. 2 edit the file so that it appears as follows: select * from employee selectmode="single"> note use the cfgridcolumn display ="no" attribute to...

  • Page 175

    Creating an updateable grid 155 note if you specify a cfgrid tag with a query attribute defined and no corresponding cfgriditem attributes the grid contains all the columns in the query. Creating an updateable grid you can build grids to allow users to edit data within them. Users can edit individua...

  • Page 176: Controlling Cell Contents

    156 chapter 9 building dynamic forms controlling cell contents the cfgridcolumn type , value , valuesdisplay, and valuesdelimiter attributes let you control the data that a user can enter into a cfgrid cell in the following ways: • by default, a cell is an editable text field. • use the type attribu...

  • Page 177: Editing Data In Cfgrid

    Creating an updateable grid 157 the value of change_index increments for each row that changes, and does not indicate the specific row number. When the user updates data or inserts or deletes rows, the action page gets one array for each changed column, plus the rowstatsus.Action array. The action p...

  • Page 178

    158 chapter 9 building dynamic forms to make the grid editable: 1 open the file grid1.Cfm in coldfusion studio. 2 edit the file so that it appears as follows: select * from employee action="handle_grid.Cfm"> height=300 width=250 vspace=10 selectmode="edit" query="empdata" insert="yes" delete="yes"> ...

  • Page 179

    Creating an updateable grid 159 reviewing the code the following table describes the code and its function: updating the database with cfgridupdate the cfgridupdate tag provides a simple mechanism for updating the database, including inserting and deleting records. It can add, update, and delete rec...

  • Page 180

    160 chapter 9 building dynamic forms to update the data source with cfgridupdate 1 open a new file in coldfusion studio. 2 modify the file so that it appears as follows: datasource="companyinfo" tablename="employee"> 3 save the file as handle_grid.Cfm . 4 view grid2.Cfm in your browser, make changes...

  • Page 181

    Creating an updateable grid 161 datasource="companyinfo"> delete from employee where emp_id=#form.Employee_grid.Original.Emp_id [counter]# datasource="companyinfo"> delete from employee where emp_id=#form.Employee_grid.Original.Emp_id [counter]# datasource="companyinfo"> update employee set lastname...

  • Page 182

    162 chapter 9 building dynamic forms reviewing the code the following table describes the code and its function: code description ("form.Employee_grid.Rowstatus.Action")> #arraylen(form.Employee_grid.Rowstatus.Action)#> if there is an array of edit types, then the table needs changing. Otherwise, do...

  • Page 183

    Creating an updateable grid 163 form.Employee_grid.Rowstatus.Action[counter] is "i"> datasource="companyinfo"> insert into employee (lastname, dept_id) values (’#form.Employee_grid.Lastname[counter]#’, #form.Employee_grid.Dept_id[counter]#) otherwise, if the action is to insert a row, generate a sql...

  • Page 184

    164 chapter 9 building dynamic forms building slider bar controls you can use the cfslider control to create a slider control and define a wide range of formatting options for slider label text, label font name, size, boldface, italics, and color, as well as slider scale increments, range, positioni...

  • Page 185: Building Text Entry Boxes

    Building text entry boxes 165 building text entry boxes the cftextinput tag is similar to the html input =text tag. With cftextinput , however, you can also specify font and alignment options, as well as enable input validation methods using either a javascript or the validate attribute. The followi...

  • Page 186

    166 chapter 9 building dynamic forms building drop-down list boxes the drop-down list box that you can create with cfselect is similar to the html select tag. However, cfselect gives you more control over user inputs, provides error handling, and, most importantly, allows you to automatically popula...

  • Page 187: Embedding Java Applets

    Embedding java applets 167 embedding java applets the cfapplet tag allows you to embed java applets in a cfform . To use cfapplet , you must first register your java applet using the coldfusion administrator java applets page (under extensions on the server tab). In the administrator, you define the...

  • Page 188: Applet Registration Fields

    168 chapter 9 building dynamic forms applet registration fields the following table explains the applet registration fields: field description codebase enter the base url of the applet: the directory that contains the applet components. The applet class files must be located within the web browser r...

  • Page 189: Overriding Parameter Values

    Embedding java applets 169 using cfapplet to embed an applet after you register an applet, you can use the cfapplet tag to place the applet in a coldfusion page. The cfapplet tag has two required attributes: appletsource and name . Since you registered the applet, and you defined each applet paramet...

  • Page 190

    170 chapter 9 building dynamic forms to reference a java applet return value in your application page: 1 specify the name of the 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 cffor...

  • Page 191: Reusing Code

    Chapter 10 reusing code this chapter describes how to reuse common code with cfinclude , and create custom cfml tags that encapsulate common code. Contents • ways to reuse code ................................................................................................ 172 • reusing common code ...

  • Page 192: Ways To Reuse Code

    172 chapter 10 reusing code ways to reuse code coldfusion provides several different ways to reuse code. These ways include the following techniques: • if you are using coldfusion studio, you can write code snippets, which you can copy into pages. • you use the cfinclude tag to include a coldfusion ...

  • Page 193: Using Custom Tags

    Using custom tags 173 6 include the header.Cfm file in this page: 7 view askemp.Cfm in a browser, then submit the form so that you display getemp.Cfm. The header should appear on both pages. Note the file header.Cfm must be in the same directory where you saved askemp.Cfm and getemp.Cfm (or a subdir...

  • Page 194: Using Existing Custom Tags

    174 chapter 10 reusing code using existing custom tags before creating a custom tag in cfml, you should review the custom tag section of the coldfusion developer exchange. Tags are grouped in several broad categories and are downloadable as freeware, shareware, or commercial software. You can quickl...

  • Page 195: Using Tag Attributes

    Using custom tags 175 custom tag pages also have access to system data structure called thistag . The thistag structure contains information about the tag and its execution environment. The thistag variable is described in “executing custom tags,” on page 185. Using tag attributes custom tag attribu...

  • Page 196

    176 chapter 10 reusing code passing values to and from custom tags because custom tags are individual coldfusion pages, variables and other data are not automatically shared between a custom tag and the calling page. To pass data from the calling page to the custom tag, specify attribute name-value ...

  • Page 197

    Using custom tags 177 passing custom tag attributes via cfml structures you can use the reserved attribute attributecollection to pass attributes to custom tags. Attributecollection must reference a structure that contains the attribute names as the keys and the attribute values as the values. You c...

  • Page 198: Custom Tag Example

    178 chapter 10 reusing code custom tag example in this example, we create a custom tag that uses an attribute that is passed to it to set the value of a variable called doctor on the calling page. To create a custom tag: 1 create a new application page (the calling page) in coldfusion studio. 2 modi...

  • Page 199

    Using custom tags 179 reviewing the code the following table describes the code and its function: tip be careful not to overwrite variables that might already exist on the calling page. You should adopt a naming convention to minimize the chance of overwriting variables. For example, prefix the retu...

  • Page 200: Nesting Custom Tags

    180 chapter 10 reusing code nesting custom tags a custom tag can call other custom tags, thereby nesting tags. Coldfusion uses nested tags such as cfgraph and cfgraphdata , cfhttp and cfhttppam , and cftree and cftreeitem . The ability to nest tags allows you to provide similar functionality. The ca...

  • Page 201: What Data Is Accessible?

    Passing data between nested custom tags 181 passing data between nested custom tags a key custom tag feature is the ability of collaborating custom tags to exchange complex data without user intervention while encapsulating each tag’s implementation so that others cannot see it. When you decide to y...

  • Page 202: Ancestor Data Access

    182 chapter 10 reusing code the cfassociate tag has the following format: the basetag attribute is the name of the base tag that gets access to this tag’s attributes. The datacollection attribute is the name of the structure in which the base tag stores the sub-tag data. Its default value is assocat...

  • Page 203

    Passing data between nested custom tags 183 name. By default, the closest ancestor is returned. If there is no ancestor by the given name or if the ancestor does not expose any data (such as cfif), an exception is thrown. Example: ancestor data access this example creates two custom tags and a simpl...

  • Page 204

    184 chapter 10 reusing code ancestorlist entry #loopcount# n is #listgetat(ancestorlist,loopcount)# i’m running in the context of a cfloop tag. List=#listrest(listrest(ancestorlist))#> list=#listrest(listrest(ancestorlist))#> i’m running in the context of a custom tag named #incustomtag#. I’m locate...

  • Page 205: Executing Custom Tags

    Executing custom tags 185 executing custom tags the following sections provide information on executing custom tags. Tag instance data when a custom tag page executes, coldfusion keeps data related to the tag instance. The thistag built in structured variable preserves this data with a unique identi...

  • Page 206: Terminating Tag Execution

    186 chapter 10 reusing code a custom tag page that performs processing in both modes can have the following format: you can also use cfswitch : terminating tag execution the cfexit tag terminates execution of a custom tag. The cfexit tag’s method attribute specifies where execution continues. Cfexit...

  • Page 207: Access To Generated Content

    Installing custom tags 187 access to generated content custom tags can access and modify the generated content of any of its instances using the thistag.Generatedcontent variable. In this context, the term generated content means the results of processing the body of a given tag. This includes all t...

  • Page 208: Managing Custom Tags

    188 chapter 10 reusing code managing custom tags if you deploy custom tags in a multideveloper environment or distribute your tags publicly, you can use additional coldfusion capabilities: • an advanced invocation syntax to resolve possible name conflicts • advanced security • template encoding reso...

  • Page 209: Encoding Custom Tags

    Managing custom tags 189 encoding custom tags you can use the command-line utility cfencode to encode any coldfusion application page. By default, the utility is installed in the /cfusion/bin directory. It is especially useful for securing custom tag code before distributing it. The cfencode tag use...

  • Page 210

    190 chapter 10 reusing code.

  • Page 211: Preventing and Handling

    Chapter 11 preventing and handling errors coldfusion includes many tools and techniques for ensuring that your code works properly. These tools include sophisticated debugging and code validation tools, error logging tools, and error handling mechanisms. This chapter describes these tools and presen...

  • Page 212: Error Messages

    192 chapter 11 preventing and handling errors debug settings in the coldfusion administrator coldfusion can provide important debugging information for every application page requested by a browser. When you enable debugging, the output displays in a block following normal page output. For detailed ...

  • Page 213

    Debug settings in the coldfusion administrator 193 coldfusion returns the following information: • database errors, including the odbc error code, the extended error message returned from the odbc driver, the name of the data source, and the sql statement submitted to the database • syntax error, in...

  • Page 214: Cfml Code Validation

    194 chapter 11 preventing and handling errors cfml code validation coldfusion provides two methods of validating your cfml code: • runtime validation • the cfml syntax checker runtime validation the coldfusion application server features two modes of attribute checking for processing application pag...

  • Page 215: Http/url

    Troubleshooting common problems 195 troubleshooting common problems the following section describes a few common problems that you might encounter and ways to resolve them. Odbc data source configuration problem: odbc driver manager cannot make a connection to the database. Connection errors include...

  • Page 216

    196 chapter 11 preventing and handling errors problem: invalid attribute or value. If you use an invalid attribute or attribute values, coldfusion returns an error message. To prevent such syntax errors, use the coldfusion syntax validation tools in coldfusion studio. Problem: mismatched quotes and ...

  • Page 217: Coldfusion Error Types

    Error handling in coldfusion 197 error handling in coldfusion by default, coldfusion generates its own error messages when it encounters errors. In addition, it provides a variety of tools and techniques for you to customize error information and handle errors when they occur, including the followin...

  • Page 218

    198 chapter 11 preventing and handling errors how coldfusion handles errors the following pseudo-code program illustrates how coldfusion handles errors. The rest of this expands on this outline: case missing template error coldfusion displays either a standard error page or an error page that you sp...

  • Page 219

    Generating custom error messages with cferror 199 generating custom error messages with cferror by default, coldfusion uses a standard page for most errors. Custom error pages allow you to control the error information that users see. You can specify custom error pages for different types of errors ...

  • Page 220: Error Page Variables

    200 chapter 11 preventing and handling errors creating an error application page error application pages for validation and request errors cannot use coldfusion tags; they can only use html tags. Error application pages for exception and monitor errors can use all of cfml, including tags, expression...

  • Page 221

    Generating custom error messages with cferror 201 example of a request error page the following example shows a custom error page for a request error: an error occurred when you requested this page. Please email the webmaster to report this error. We will work to correct the problem and apologize fo...

  • Page 222: Logging Errors

    202 chapter 11 preventing and handling errors example of a validation error page the following example shows a custom error page for a validation error: you failed to correctly complete all the fields in the form. The following problems occurred: #error.Invalidfields# logging errors coldfusion serve...

  • Page 223

    Logging errors 203 we apologize for the inconvenience. Text="exception error -- exception type: #error.Type# template: #error.Template#, remote address: #error.Remoteaddress#, http rerference: #error.Httpreferer# diagnositcs: #error.Diagnostics#" type="error"> reviewing the code the following table ...

  • Page 224

    204 chapter 11 preventing and handling errors handling exceptions in coldfusion ordinarily, when coldfusion encounters an error, it stops processing and displays an error message or error page (as specified by the cferror tag). However, you can use coldfusion’s exception handling tags to catch and p...

  • Page 225

    Handling exceptions in coldfusion 205 types of recoverable exceptions supported coldfusion server supports several types of recoverable exceptions. Use the type attribute in the cfcatch tag to determine which type of exception to catch. You can also use these types as the values of the exception att...

  • Page 226: Tag Context Information

    206 chapter 11 preventing and handling errors applications can optionally use the cfthrow tag to raise custom exceptions. Such exceptions are caught with any of the following type specifications: • type="custom_exception_type" • type="application " • type="any" the custom_exception_type type designa...

  • Page 227: Database Exceptions

    Handling exceptions in coldfusion 207 the structure at position 1 of the array represents the outermost tag in the stack of tags that were executing when the interpreter detected the exception. The structure at position arraylen( cfcatch .Tagcontext) represents the currently executing tag at the tim...

  • Page 228: Locking Exceptions

    208 chapter 11 preventing and handling errors locking exceptions the following additional information is available for exceptions related to cflock sections: missing include exceptions the following additional variable is available if the error is caused by a missing file specified by a cfinclude ta...

  • Page 229

    Handling exceptions in coldfusion 209 select dept_id, firstname, lastname from employee where emp_id=#empid# department: #dept_id# last name: #lastname# first name: #firstname#.

  • Page 230: Custom Exception Types

    210 chapter 11 preventing and handling errors to test the code: 1 make sure there is no includeme.Cfm file and display the page. The cfcatch type="missinginclude" block displays the error. 2 create a non-empty includeme.Cfm file and display the page. If your database is configured properly you shoul...

  • Page 231: Naming Conventions

    Handling exceptions in coldfusion 211 naming conventions a naming convention for custom exception types follows a convention that is similar to java class naming conventions: domain name in reverse order, followed by project identifiers, as in this example: type="invalid_field.Codevalue" errorcode="...

  • Page 232

    212 chapter 11 preventing and handling errors.

  • Page 233: Using The Application

    Chapter 12 using the application framework the coldfusion web application framework is a powerful tool that you can use to help structure your coldfusion applications. This chapter describes how to create and use the application.Cfm file, the application page that controls the application framework....

  • Page 234

    214 chapter 12 using the application framework understanding the web application framework a coldfusion application is a collection of application pages that work together. Applications can be as simple as a guest book or as sophisticated as a full internet commerce system with catalog pages, shoppi...

  • Page 235: Custom Error Handling

    Understanding the web application framework 215 coldfusion does not attempt to automatically evaluate application, session, or server variables. You must use variable prefixes with these variables, as in session.Variablename or application.Variablename. As a general rule you should prefix all these ...

  • Page 236: Processing Application.Cfm

    216 chapter 12 using the application framework mapping an application framework an important step in designing a coldfusion application is mapping its directory structure. Before you start building the application, establish a root directory for the application. You can store application pages in su...

  • Page 237

    Mapping an application framework 217 defining the directory structure defining a root directory for an application has a number of advantages: • development the application is easier to develop and maintain because the application page files are well organized. • portability you can more easily move...

  • Page 238

    218 chapter 12 using the application framework ..

  • Page 239: Naming The Application

    Creating the application.Cfm file 219 creating the application.Cfm file the special application-wide page called application.Cfm defines application-level settings and functions such as: • application name • client state management options • application and session variable management options • defa...

  • Page 240: Example: Application.Cfm

    220 chapter 12 using the application framework example: application.Cfm the following example shows a complete application.Cfm file for the sample products application: clientmanagement="yes" clientstorage="mycompany" sessionmanagement="yes"> template="requesterr.Cfm" mailto="admin@company.Com"> tem...

  • Page 241: Managing The Client State

    Managing the client state 221 managing the client state because the web is a stateless system, each connection that a browser makes to a web server is unique to the web server. However, within an application it is important to be able to keep track of users as they move through the pages within the ...

  • Page 242: About Client Cookies

    222 chapter 12 using the application framework about client cookies both types of variables normally require coldfusion to store two client identification variables as cookies on the client’s system: • cfid, a sequential client id • cftoken, a random-number client security token these cookies unique...

  • Page 243

    Configuring and using client variables 223 configuring and using client variables to use client variables effectively, you set up the client variable options and use the variables on your coldfusion pages. Setting up client variable options if you want to enable client variables, you must do so on e...

  • Page 244: Using Client Variables

    224 chapter 12 using the application framework consider these additional limitations before implementing cookie storage for client variables: • many browsers allow only 20 cookies from a particular host to be set. Coldfusion uses two of these cookies for cfid and cftoken and also creates a cookie na...

  • Page 245: Standard Client Variables

    Configuring and using client variables 225 the following example shows how to use the cfparam tag to check for the existence of a client parameter and to set a default value if the parameter does not already exist: accessing and changing client variables you use the same syntax to access a client va...

  • Page 246: Deleting Client Variables

    226 chapter 12 using the application framework getting a list of client variables to obtain a list of the custom client parameters associated with a particular client, use the getclientvariableslist function. #getclientvariableslist()# the getclientvariableslist function returns a comma-separated li...

  • Page 247

    Configuring and using client variables 227 exporting the client variable database if your client variable database is stored in the windows system registry and you need to move it to another machine, you can export the registry key that stores your client variables and take it to your new server. Th...

  • Page 248: Using Session Variables

    228 chapter 12 using the application framework using session variables use session variables when you need the variables for a single site visit or set of requests. For example, you might use session variables to store a user’s selections in a shopping cart application. (use client variables when yo...

  • Page 249: Standard Session Variables

    Using session variables 229 the default timeout for session variables is set to 20 minutes. You can change the timeout on the memory variables page of the coldfusion administrator server tab. For more information, see advanced coldfusion administration. You can also set the timeout period for sessio...

  • Page 250: Using Application Variables

    230 chapter 12 using the application framework getting a list of session variables the variable session scope is registered as a coldfusion structure. This lets you use the coldfusion structure functions to get a list of session variables. For example, you can use cfloop with the structfind function...

  • Page 251

    Using application variables 231 variables, they are not useful for client-specific information. To target variables for specific clients, use session or client variables. Application variable timeouts application variables have a specific lifetime. If no clients access the application within the spe...

  • Page 252: Using Server Variables

    232 chapter 12 using the application framework using server variables server variables are associated with a single coldfusion server. They are available to all applications that run on the server. Use server variables for data that must be accessed across clients and applications. Server variables ...

  • Page 253: Locking Code With Cflock

    Locking code with cflock 233 locking code with cflock the cflock tag controls simultaneous access to coldfusion code. The cflock tag enables you to: • protect sections of code that access and manipulate shared data such as session, application, and server variables. • ensure that file updates do not...

  • Page 254: Lock Types

    234 chapter 12 using the application framework the cflock tag enables you to ensure that concurrently executing requests do not access the same section of code simultaneously and thus manipulate shared data structures, files, or cfxs inconsistently. It is important to remember that cflock protects c...

  • Page 255: Controlling Lock Timeouts

    Locking code with cflock 235 you can set the attribute to any of the following values: if multiple code sections share a lock, the following rules apply: • when code in a cflock tag block with the type exclusive is running, code in blocks with the same lock are not allowed run. They wait until the c...

  • Page 256

    236 chapter 12 using the application framework for example, if you want to assign the results of a query to a session variable, first get the query results using a variables scope variable in unlocked code. Then, assign the query results to a session variable inside a locked code section. The follow...

  • Page 257: Single-Threading Sessions

    Locking code with cflock 237 automatic read locking also adds overhead because coldfusion must insert read locks and check variable access for locking. However, it can be useful if you already have a site that does not use locking properly. In this case, you must only lock all writes and do not have...

  • Page 258: Examples of Cflock

    238 chapter 12 using the application framework 5 unlock the application scope. 6 unlock the session scope. Note you can skip any pair of lock/unlock steps in the preceding list if you do not need to lock a particular scope. For example, you can omit steps 3 and 4 if you do not need to lock the serve...

  • Page 259

    Examples of cflock 239 timeout="10" type ="readonly"> e-turtleneck is proud to say that we have sold #application.Number# turtlenecks to date. Timeout="10" type ="readonly"> e-turtleneck is proud to say that we have sold #application.Number# turtlenecks to date. The remaining sample code could appea...

  • Page 260

    240 chapter 12 using the application framework timeout="30" type="exclusive"> timeout="30" type="exclusive"> congratulations! You have just selected the longest wearing, most comfortable turtleneck in the world. Please indicate the color and size you want to buy. Red white blue turquoise black fores...

  • Page 261

    Examples of cflock 241 example of synchronizing access to a file system the following example shows how to use cflock to synchronize access to a file system. The cflock tag protects a cffile tag from attempting to append data to a file already open for writing by the same tag executing on another re...

  • Page 262

    242 chapter 12 using the application framework.

  • Page 263: Extending Coldfusion Pages

    Chapter 13 extending coldfusion pages with cfml scripting coldfusion offers a server-side scripting language, cfscript, that provides coldfusion functionality in script syntax. This javascript-like language gives developers the same control flow, but without tags. You can also use cfscript to write ...

  • Page 264: About Cfscript

    244 chapter 13 extending coldfusion pages with cfml scripting about cfscript the coldfusion server-side scripting language, cfscript, offers coldfusion functionality in script syntax. This javascript-like language offers the same control flow, but without tags. Cfscript regions are bounded by cfscri...

  • Page 265: The Cfscript Language

    The cfscript language 245 the cfscript language this section explains the syntax of the cfscript language. Comments comments in cfscript blocks begin with two forward slashes (//) and end at the line end. You can also enclose cfscript comments between /* and */. Note that you cannot nest /* and */ i...

  • Page 266

    246 chapter 13 extending coldfusion pages with cfml scripting if-else: if(expr) statement [else statement] ; if(score gt 1) result = "positive"; else result = "negative"; for loop: for (init-expr ; test-expr ; final-expr) statement ; init-expr and final-expr can be one of the following: • a single a...

  • Page 267

    The cfscript language 247 do-while loop: do statement while (expr) ; // complete do-while loop on a single line a = arraynew(1); loop = 1; do {a[loop] = loop + 5; loop = loop + 1;} while (loop lt 10); // multiline do-while loop a = arraynew(1); loop = 1; do { a[loop] = loop + 5; loop = loop + 1; } w...

  • Page 268: Reserved Words

    248 chapter 13 extending coldfusion pages with cfml scripting continue: skip to next loop iteration for ( loop=1; loop lt 10; loop = loop+1) { if(a[loop] eq 0) continue; a[loop]=1; } break: break out of the current switch statement or loop indx = 0; for( ; ; ) { indx=indx+1; if(find("key",strings[in...

  • Page 269

    Interaction of cfscript with cfml 249 interaction of cfscript with cfml you enclose cfscript regions inside and tags. No other cfml tags are allowed inside a cfscript region. Coldfusion generates an error if a cfscript tag block does not contain at least one cfscript statement, and cfscript comments...

  • Page 270: Defining Functions

    250 chapter 13 extending coldfusion pages with cfml scripting defining and using custom functions you can define custom functions (also known as user-defined functions) and use them in your application pages as you do standard coldfusion functions. This allows you to create a function for an algorit...

  • Page 271: Calling Functions

    Defining and using custom functions 251 the following two statements are allowed only in function definitions. Each function must have a return statement: var variablename = initialvalue; creates and initializes a variable that is local to the function (function variable). This variable has meaning ...

  • Page 272: Passing Arguments

    252 chapter 13 extending coldfusion pages with cfml scripting each function has a built-in arguments array containing all arguments passed to the function: the required arguments specified by the function parameters followed by any additional arguments included in the function call. The function can...

  • Page 273: Examples Of Custom Functons

    Defining and using custom functions 253 used elsewhere in your application. If a function must use a variable from another scope that has the same name as a function variable, just prefix the external variable with its scope identifier, such as variables or form. For example, if you use the variable...

  • Page 274: Using Application.Cfm

    254 chapter 13 extending coldfusion pages with cfml scripting return dollarformat(totalinterest); } you could use the totalinterest function in a cfoutput tag of a form’s action page as follows: loan amount: #form.Principal# annual percentage rate: #form.Annualpercent# loan duration: #form.Months# m...

  • Page 275

    Defining and using custom functions 255 you can use functions that manipulate many rows of a query outside such tags. There you can pass in a query and loop over it in the function. The following example, which changes text in a query column to uppercase, illustrates using a function to modify multi...

  • Page 276: Error Handling

    256 chapter 13 extending coldfusion pages with cfml scripting function makes using the structure appears, but the change the function makes using the directly passed array does not affect the array outside the function. //create a two-element array inside a structure mystruct = structnew(); mystruct...

  • Page 277

    Defining and using custom functions 257 } else { // need to return error value // caller will look at value and then decide to look at errorinfo // alternatively, caller can look at errorinfo and see whether // some pre-defined fields are available return -1; // or "" or whatever we have agreed to.....

  • Page 278

    258 chapter 13 extending coldfusion pages with cfml scripting.

  • Page 279: Using Regular Expressions In

    Chapter 14 using regular expressions in functions this chapter describes how regular expressions work in the following coldfusion functions: • refind • refindnocase • rereplace • rereplacenocase this chapter does not apply to regular expressions used in the cfinput and cftextinput tags. These tags u...

  • Page 280: About Regular Expressions

    260 chapter 14 using regular expressions in functions about regular expressions regular expressions allow you to perform very powerful and flexible string search and replace operations. In traditional search and replace operations, as in the find and replace functions of coldfusion, you must provide...

  • Page 282

    262 chapter 14 using regular expressions in functions this code replaces all the spaces with *, producing this string: macromedia*web*site the following table shows the posix character classes that coldfusion supports: character class matches alpha matches any letter. Same as [a-za-z]. Upper matches...

  • Page 283

    Multicharacter regular expressions 263 multicharacter regular expressions you can use the following rules to build multicharacter regular expressions: • parentheses group parts of regular expressions together into grouped subexpressions that you can be treat as a single unit; for example, (ha)+ matc...

  • Page 284: Limiting Input String Size

    264 chapter 14 using regular expressions in functions an excellent reference on regular expressions is mastering regular expressions, jeffrey e. F. Friedl. O’reilly & associates, inc., 1997. Isbn: 1-56592-257-3, http:// www.Oreilly.Com. Limiting input string size in cfml regular expression functions...

  • Page 285: Using Backreferences

    Using backreferences 265 using backreferences coldfusion server supports backreferencing, which allows you to match text in previously matched sets of parentheses. A slash followed by a digit n () refers to the n th subexpression in parentheses. One use for backreferencing is in searching for doub...

  • Page 286

    266 chapter 14 using regular expressions in functions returning matched subexpressions the refind and refindnocase functions allow you to get information about matched subexpressions. If you set these functions’ fourth parameter, returnsubexpression , to true, the function returns a cfml structure w...

  • Page 287: Regular Expression Examples

    Regular expression examples 267 regular expression examples the following examples show some regular expressions and describe what they match: regular expressions in cfml the following examples of cfml show some common uses of regular expression functions: expression description [\?&]value= a url pa...

  • Page 288

    268 chapter 14 using regular expressions in functions refind ("[uu]\.?[ss]\.?[aa}\.?", report ) the position in the variable report of the first occurrence of the abbreviation usa. The letters can be in either case and the abbreviation can have a period after any letter. Refindnocase("a+c","abcaaccd...

  • Page 289: Indexing and Searching Data

    Chapter 15 indexing and searching data you can provide a full-text search capability for documents and data sources on a coldfusion site by enabling the verity search engine. Coldfusion 5 supports two verity search engines: the default verity search engine (vdk mode) and a restricted version of the ...

  • Page 290: Advantages Of Using Verity

    270 chapter 15 indexing and searching data searching a coldfusion web site until now, you have searched for records in databases based on the value of particular fields using odbc. However, to efficiently search through paragraphs of text or files of varying types you need full-text search capabilit...

  • Page 291: Supported File Types

    Supported file types 271 supported file types the coldfusion verity implementation supports a wide array of file and document types. As a result, you can index web pages, coldfusion applications, and many binary document types and produce search results that include summaries of these documents. To ...

  • Page 292

    272 chapter 15 indexing and searching data support for international languages the coldfusion international language search pack is not shipped with coldfusion, but is available on a separate cd-rom free of charge. To order the language search pack, contact macromedia customer service or visit the o...

  • Page 293: Creating A Collection

    Creating a searchable data source 273 creating a searchable data source you must do the following steps to create a searchable data source: 1 create a collection. You can do this either through the coldfusion administrator or programmatically. 2 populate and index the collection. You must select the...

  • Page 294

    274 chapter 15 indexing and searching data if you checked the option to install the coldfusion documentation, the documentation collection is listed by default. The verity engine is used to search the online documents. 2 in the top section of the page, enter a name for the collection. 3 enter a path...

  • Page 295

    Creating a searchable data source 275 to create a simple collection form page: 1 open a new file in coldfusion studio. 2 modify the file so that it appears as follows: collection name: size="25"> what do you want to do with the collection? Name="collectionaction" value="create" checked>create name="...

  • Page 296

    276 chapter 15 indexing and searching data collection="#form.Collectionname#" path="c:\cfusion\verity\collections\"> the collection #form.Collectionname# is created. Collection="#form.Collectionname#"> the collection #form.Collectionname# is repaired. Collection="#form.Collectionname#"> the collecti...

  • Page 297

    Creating a searchable data source 277 selecting an indexing method use the following guidelines to determine which method to use: using coldfusion administrator to use coldfusion administrator to index a collection: 1 select a collection name in the verity collections box. 2 click index to open the ...

  • Page 298: Using Cfindex

    278 chapter 15 indexing and searching data using cfindex you can use a form page an action page similar to the following examples to select a collection and index it. To select which collection to index: 1 open a new file in coldfusion studio. 2 modify the file so that it appears as follows: enter t...

  • Page 299: Basic Search Operations

    Creating a searchable data source 279 the collection #form.Indexcoll# has been indexed. 3 save the file as collectionindexaction.Cfm. 4 view collectionindexform.Cfm in your browser, enter values, and then click index. Building a search interface after you create and index a searchable data source, y...

  • Page 300

    280 chapter 15 indexing and searching data value=simple checked> simple name=type value=explicit> explicit enter a search string: name=searchstring size=50> name=search1 value="search"> value="reset"> 3 save the file as collectionsearchform.Cfm . Note to use cfsearch to search a verity k2 server col...

  • Page 301: Creating Summaries

    Creating a searchable data source 281 3 save the file as collectionsearchaction.Cfm. 4 view the file collectionsearchform.Cfm in your browser, enter values in the form, and then submit it. Creating summaries as part of the indexing process, verity automatically produces a summary of every document f...

  • Page 302: Indexing Query Results

    282 chapter 15 indexing and searching data indexing query results the following sections describe the reasons and procedures for indexing the results of database, ldap, and pop queries. Indexing database query results the main advantage of performing searches against a verity collection over using c...

  • Page 303

    Indexing query results 283 body="messagetext" key="message_id" title="subject" query="messages"> this cfindex statement specifies the messagetext column as the information to be indexed and names the table’s primary key, the message_id column, as the key value. Note that the title attribute names th...

  • Page 304

    284 chapter 15 indexing and searching data collection="ldap_query" key="dn" type="custom" title="o" query="orglist" body="telephonenumber"> name="s_ldap" criteria="*617*"> #key#, #title#, #body# indexing cfpop query results the contents of mail servers are generally quite volatile; specifically, the...

  • Page 305: Using Query Expressions

    Using query expressions 285 type="custom" title="subject" query="p_messages" body="body"> name="s_messages" criteria="action"> #key#, #title# using query expressions when you search a verity collection, you use the cfsearch tag in a coldfusion application page. Use the criteria attribute to specify ...

  • Page 306: Explicit Query Expressions

    286 chapter 15 indexing and searching data a simple query automatically employs the stem operator and the many modifier. Stem searches for words that derive from those entered in the query expression, so entering “find” returns documents that contain “find,” “finding,” “finds,” and so on. The many m...

  • Page 307: Special Characters

    Using query expressions 287 special characters the search engine handles a number of characters in particular ways as described in the following table: a backslash (\) removes special meaning from whatever character follows it. To enter a literal backslash in a query, use two in succession; for exam...

  • Page 308: Commas In Expressions

    288 chapter 15 indexing and searching data when you use prefix notation, the expression specifies precedence explicitly. The following example means: look for documents that contain b and c first, then documents that contain a: or (a, and (b,c)) when you use infix notation, precedence is implicit in...

  • Page 309

    Using query expressions 289 searching for wildcards as literals to search for a wildcard character in your collection, you need to escape the character with a backslash (\); for example: • to match a literal asterisk, you precede the * with two backslashes: "a\\*" • to match a question mark or other...

  • Page 310: Operators and Modifiers

    290 chapter 15 indexing and searching data operators and modifiers the power of the cfsearch tag is in the control it provides over the verity search engine. The engine offers users a high degree of specificity in setting search parameters. Operators an operator represents logic to be applied to a s...

  • Page 311

    Using query expressions 291 the following tale describes the evidence operators: proximity operators proximity operators specify the relative location of specific words in the document. Specified words must be in the same phrase, paragraph, or sentence for a document to be retrieved. In the case of ...

  • Page 312

    292 chapter 15 indexing and searching data the following table describes the proximity operators: relational operators relational operators search document fields that you defined in the collection. Documents containing specified field values are returned. Documents retrieved using relational operat...

  • Page 313

    Using query expressions 293 you use the following operators for numeric and date comparisons: the following relational operators compare text and match words and parts of words: operator description = equals > greater than >= greater than or equal to less than less than or equal to operator descript...

  • Page 314

    294 chapter 15 indexing and searching data document fields you can specify the values for the cfindex attributes title, key, url, and custom as document fields for use with relational operators in the criteria attribute. Document fields are referenced in text comparison operators. They are identifie...

  • Page 315

    Using query expressions 295 key="identifier" body="text" query="gettext"> collection="testcollection" type="explicit" criteria="1990 and cf_title utah"> record counts: #gettext.Recordcount# #gettext_search.Recordcount# query results --- should be 5 rows #identifier# search results -- should be 1 row...

  • Page 316

    296 chapter 15 indexing and searching data score operators score operators govern how the search engine calculates scores for retrieved documents. The maximum score that a returned search element can have is 1.000. You can set the score percentage display to as many as four decimal places. When you ...

  • Page 317: Modifiers

    Using query expressions 297 modifiers you combine modifiers with operators to change the standard behavior of an operator in some way. For example, you can use the case modifier with an operator to specify that you want to match the case of the search word. The following table describes the availabl...

  • Page 318: Managing Collections

    298 chapter 15 indexing and searching data managing collections as with any data source, the maintenance requirements of a verity collection are dictated by the number, frequency, and type of changes that occur in the records. You can run maintenance routines directly from either the cfcollection or...

  • Page 319

    Managing collections 299 to restrict access to a collection, follow these steps: 1 in the coldfusion administrator, click the security tab and select advanced security > security configuration. 2 select the use advanced server security box. 3 click the submit changes button. 4 click the security con...

  • Page 320

    300 chapter 15 indexing and searching data.

  • Page 321: Sending and Receiving E-Mail

    Chapter 16 sending and receiving e-mail you can add interactive mail features to your coldfusion applications, providing a complete two-way interface to mail servers via the cfmail tag and the cfpop tag. The boom in internet mail services makes coldfusion’s enhanced e-mail capability a vital link to...

  • Page 322: Sending E-Mail Messages

    302 chapter 16 sending and receiving e-mail using coldfusion with mail servers adding e-mail to your coldfusion applications lets you respond automatically to user requests. You can use e-mail in your coldfusion applications in many different ways. These are just a few examples: • trigger e-mail mes...

  • Page 323

    Sending e-mail messages 303 sending smtp mail with cfmail the cfmail tag provides support for sending smtp e-mail from within coldfusion applications. The cfmail tag is similar to the cfoutput tag, except that cfmail outputs the generated text as smtp mail messages rather than to a page. The cfmail ...

  • Page 324: Sample Uses Of Cfmail

    304 chapter 16 sending and receiving e-mail sample uses of cfmail an application page with the cfmail tag dynamically generates e-mail messages based on the tag’s settings. Some of the tasks you can accomplish with cfmail include the following: • sending a mail message whose recipient and contents a...

  • Page 325

    Sample uses of cfmail 305 #productrequests.Firstname# #productrequests.Lastname# (#productrequests.Company#) - #productrequests.Emailaddress##013; regards, the webmaster webmaster@mycompany.Com note the use of the cfoutput tag to present a dynamic list embedded within a normal cfmail message. The te...

  • Page 326

    306 chapter 16 sending and receiving e-mail customizing e-mail for multiple recipients in the following example, a query (getcustomers) is run to retrieve the contact information for a list of customers. This query is then used to send an e-mail to each customer asking the person to verify that the ...

  • Page 327: Attaching A Mime File

    Customizing e-mail for multiple recipients 307 attaching a mime file you use the cfmailparam tag to attach a file or add a header to a mail message. In the following example, a mime-encoded file is sent along with an e-mail message: to="bobm@supercomputer.Com" subject="file you requested" > dear bob...

  • Page 328: Advanced Sending Options

    308 chapter 16 sending and receiving e-mail advanced sending options the coldfusion implementation of smtp mail uses a spooled architecture. When a cfmail tag is processed in an application page, the messages that are generated are not sent immediately. Instead, they are spooled to disk and processe...

  • Page 329: Receiving E-Mail Messages

    Receiving e-mail messages 309 receiving e-mail messages the post office protocol tag, cfpop , expands your ability to add internet mail client features and e-mail consolidation to applications. While a conventional mail client provides an adequate interface for personal mail, there are many cases in...

  • Page 330: Cfpop Query Variables

    310 chapter 16 sending and receiving e-mail cfpop query variables two variables are returned for each cfpop query that provide record number information: • recordcount the total number of records returned by the query. • currentrow the current row of the query being processed by cfoutput in a query-...

  • Page 331

    Handling pop mail 311 username=#myusername# password=#mypassword# action="getheaderonly" name="sample"> messagenumber: #htmleditformat(sample.Messagenumber)# to: #htmleditformat(sample.To)# from: #htmleditformat(sample.From)# subject: #htmleditformat(sample.Subject)# date: #htmleditformat(sample.Dat...

  • Page 332

    312 chapter 16 sending and receiving e-mail retrieving an entire message when you use the cfpop tag with action="getall" , coldfusion returns the same columns as with getheaderonly , plus two additional columns, body and header . To retrieve an entire message: 1 create a new file in coldfusion studi...

  • Page 333

    Handling pop mail 313 note that this example does not use a cfml function to encode the body contents. As a result, the browser displays the formatted message as you would normally see it in a mail program that supports html messages. Retrieving attachments with messages when you use the cfpop tag w...

  • Page 334: Deleting Messages

    314 chapter 16 sending and receiving e-mail body: #sample.Body# header: htmlcodeformat(sample.Header)# 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: username=#username# password=#password# 4 save the file as hdrbody.Cfm in mya...

  • Page 335

    Handling pop mail 315 to delete messages: 1 create a new file in coldfusion studio. 2 modify the file so that it appears as follows: username=#username# password=#password# action="delete" messagenumber="1,2,3"> 3 change the following line so that it refers to a valid pop mail server, as well as to ...

  • Page 336

    316 chapter 16 sending and receiving e-mail.

  • Page 337: Managing Files On The Server

    Chapter 17 managing files on the server the cffile , cfdirectory , and cfcontent tags handle browser/server file management tasks. To perform server-to-server operations, use the cfftp tag, described in “performing file operations with cfftp” on page 341. Contents • using cffile .......................

  • Page 338: Using Cffile

    318 chapter 17 managing files on the server using cffile the cffile tag gives you the ability to work with files on your server in a number of ways: • uploading files from a client to the web server using an html form • moving, renaming, copying, or deleting files on the server • reading, writing, o...

  • Page 339: Uploading Files

    Uploading files 319 uploading files file uploading requires that you create two files: • an html form to enter file upload information • an action page containing the file upload code to create an html file to specify file upload information: 1 create a new file in coldfusion studio. 2 modify the fi...

  • Page 340

    320 chapter 17 managing files on the server the user can enter a file path or browse the system and pick a file to send. To create an action page to upload the file: 1 create a new file in coldfusion studio. 2 modify the file so that it appears as follows: destination="c:\temp" nameconflict="overwri...

  • Page 341

    Uploading files 321 reviewing the code the following table describes the code and its function: note this example performs no error checking and does not incorporate any security measures. Before deploying an application that performs file uploads, be sure to incorporate both error handling and secu...

  • Page 342

    322 chapter 17 managing files on the server note not all browsers support mime type associations. Example: restricting file types this cffile specification saves an image file only if it is in the gif format: filefield="form.Filetoupload" destination="c:\uploads\myimage.Gif" nameconflict="overwrite"...

  • Page 343: Windows

    Setting file and directory attributes 323 setting file and directory attributes in windows, you specify file attributes using the cffile attributes attribute. In unix, you specify file and directory permissions using the cffile and cfdirectory mode attribute. Windows in windows, you can set the foll...

  • Page 344

    324 chapter 17 managing files on the server you enter permissions values in the mode attribute for each type of user: owner, group, and other in that order. For example, use the following code to assign read permissions for everyone: mode=444 to give a file or directory owner read/write/execute perm...

  • Page 345

    Evaluating the results of a file upload 325 note file status variables are read-only. They are set to the results of the most recent cffile operation. If two cffile tags execute, the results of the first are overwritten by the subsequent cffile operation. Filewasappended indicates (yes or no) whethe...

  • Page 346

    326 chapter 17 managing files on the server moving, renaming, copying, and deleting server files with cffile , you can create application pages to manage files on your web server. You can use the tag to move files from one directory to another, rename files, copy a file, or delete a file. The exampl...

  • Page 347: Reading A Text File

    Reading, writing, and appending to a text file 327 reading, writing, and appending to a text file in addition to managing files on the server, you can use cffile to read, create, and modify text files. As a result, you can do the following things: • create log files. (you can also use cflog to creat...

  • Page 348: Writing A Text File

    328 chapter 17 managing files on the server writing a text file you can use cffile to write a text file based on dynamic content. For example, you could create static html files or log actions in a text file. To create a form in which to enter data for a text file: 1 open a new file in coldfusion st...

  • Page 349: Returning File Information

    Performing directory operations 329 the text file is written to the location you specified. If the file already exists, it is replaced. You can use cffile action="append" to append additional text to the end of an existing text file, for example, when you create log files. Performing directory opera...

  • Page 350

    330 chapter 17 managing files on the server 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, eit...

  • Page 351: Contents

    Chapter 18 interacting with remote servers this chapter describes how coldfusion wraps the complexity of hypertext transfer protocol (http) and file transfer protocol (ftp) communications in a simplified tag syntax that lets you easily extend your site’s offerings across the web. Contents • using cf...

  • Page 352: Using The Cfhttp Get Method

    332 chapter 18 interacting with remote servers using cfhttp to interact with the web the cfhttp tag, which enables you to retrieve information from a remote server, is one of the more powerful tags in the cfml tag set. You can use one of two methods to interact with a remote server using the cfhttp ...

  • Page 353

    Using the cfhttp get method 333 reviewing the code the following table describes the code and its function: to get a web page and save it in a file: 1 open a new file in coldfusion studio. 2 modify the file so that it appears as follows: method = "get" url="http://www.Ci.Newton.Ma.Us/main.Htm" path=...

  • Page 354

    334 chapter 18 interacting with remote servers to get a binary file and save it: 1 open a new file in coldfusion studio. 2 modify the file so that it appears as follows: method="get" url="http://localhost/myapps/testfile.Zip" path="c:\temp" file="mytestfile.Zip"> #cfhttp.Mimetype# 3 change the url t...

  • Page 355

    Creating a query from a text file 335 creating a query from a text file you can create a query object from a delimited text file by using the cfhttp tag and specifying method="get" and the name attribute. This is a powerful method for processing and handling generated text files. After you create th...

  • Page 356

    336 chapter 18 interacting with remote servers now using replacement column names url="http://127.0.0.1/orders/june/orders.Txt" name="juneorders" columns="id,number,odate,sdate,name,address" delimiter=","> order id: #id# order number: #number# order date: #sdate# 3 substitute the url with the locati...

  • Page 357

    Using the cfhttp post method 337 using the cfhttp post method use the post method to send cookie, form field, cgi, url, and file variables to a specified coldfusion page or cgi program for processing. For post operations, you must use the cfhttpparam tag for each variable you want to post. The post ...

  • Page 358

    338 chapter 18 interacting with remote servers 3 replace the path to the gif file to a path on your server. 4 save the file as posttest.Cfm in myapps under your web root directory. Reviewing the code the following table describes the code and its function: to view the variables: 1 create a new file ...

  • Page 359

    Using the cfhttp post method 339 the url variable is: #url.Myurl# the cookie variable is: #cookie.Mycookie6# the cgi variable is: #cgi.Mycgi#. The formfield variable is: #form.Emailaddress#. The file was uploaded to #file.Serverdirectory#\#file.Serverfile#. 3 replace c:\temp\junk with an appropriate...

  • Page 360

    340 chapter 18 interacting with remote servers to return results of a cgi program: the following code runs the (theoretical) cgi program search.Exe on the (equally theoretical) somesiteorother.Com site and displays the results, including both the mime type and length of the response. The search.Exe ...

  • Page 361

    Performing file operations with cfftp 341 performing file operations with cfftp the cfftp tag lets you perform tasks on remote servers using file transfer protocol (ftp). You can use cfftp to cache connections for batch file transfers. Note to use cfftp , the enable cfftp tag option must be selected...

  • Page 362

    342 chapter 18 interacting with remote servers did the connection close successfully? #cfftp.Succeeded# ftp directory listing: text="#dateformat(lastmodified)#"> text="#isdirectory#"> 3 change myserver to the name of a server for which you have ftp permission. 4 change myusername and mypassword to a...

  • Page 363

    Performing file operations with cfftp 343 hafter you establish a connection with cfftp , you can reuse the connection to perform additional ftp operations until either you or the server closes the connection. When you access an already-active ftp connection, you do not need to re-specify the usernam...

  • Page 364

    344 chapter 18 interacting with remote servers assigning a cfftp connection to an application variable could cause problems, since multiple users could access the same connection object at the same time. Creating a session variable for a cfftp connection makes more sense, because the connection is a...

  • Page 365: Wddx

    Moving complex data structures across the web with wddx 345 moving complex data structures across the web with wddx you can move complex data structures across the web using web distributed data exchange (wddx). This capability is based on extensible markup language (xml) 1.0 and you can use it to e...

  • Page 366: Wddx And Web Services

    346 chapter 18 interacting with remote servers objects on a remote system. Communication between objects on remote systems uses an efficient, special-purpose wire protocol. In the disconnected world, however, these services are a barrier to development. At the most fundamental level, the wire protoc...

  • Page 367: Time Zone Processing

    Moving complex data structures across the web with wddx 347 types, and descriptors that allow the data to be manipulated on a target system between arbitrary application servers. When you use wddx in coldfusion pages, you typically use the coldfusion cfwddx tag and the javascript utility classes tha...

  • Page 368: How Wddx Works

    348 chapter 18 interacting with remote servers in the cfml implementation, usetimezoneinfo is an attribute of the cfwddx action=cfml2wddx tag. In the javascript implementation, usetimezoneinfo (note the case sensitivity of javascript) is a property of the wddxserializer object. Date-time values in w...

  • Page 369

    Converting cfml data to a javascript object 349 converting cfml data to a javascript object the following example demonstrates the transfer of a cfquery result set from a cfml page executing on the server to a javascript object that is processed by the browser. The application consists of four princ...

  • Page 370

    350 chapter 18 interacting with remote servers transferring data from browser to server this example serializes form field data, posts it to the server, deserializes it, and outputs the data. For simplicity, only a small amount of data is collected. In applications that generate complex javascript d...

  • Page 371

    Transferring data from browser to server 351 // person info record set with columns firstname and lastname // make sure the case of field names is preserved var personinfo = new wddxrecordset(new array("firstname", "lastname"), true); // add next record to end of personinfo record set function donex...

  • Page 372

    352 chapter 18 interacting with remote servers onclick="serializedata(personinfo, document.Personform.Wddxpacket)"> names added so far: wddx packet display: server-side processing output="personinfo"> the submitted personal information is: person #currentrow#: #firstname# #lastname# the client did n...

  • Page 373

    Storing complex data in a string 353 storing complex data in a string the following simple example uses wddx to store complex data, a data structure that contains arrays as a string in a client variable. It uses the cfdump tag to display the contents of the structure before serialization and after d...

  • Page 374

    354 chapter 18 interacting with remote servers.

  • Page 375: Application Security

    Chapter 19 application security coldfusion supports several levels of security. This chapter explains how to deploy user security, which offers runtime security for coldfusion applications. It also describes the remote development services security feature, which authenticates developers accessing s...

  • Page 376

    356 chapter 19 application security coldfusion security features coldfusion server professional and enterprise editions include advanced security features that provide scalable, granular security for building and deploying your coldfusion applications: • application development system administrators...

  • Page 377: Overview Of User Security

    Overview of user security 357 overview of user security user security authenticates users when they log into a coldfusion application, and then assigns privileges based on group membership or other criteria that you determine. For example, suppose you use coldfusion to build and host your company’s ...

  • Page 378: Encrypting Application Pages

    358 chapter 19 application security using advanced security in application pages advanced security makes it easier for developers to enforce application security. After your administrator sets up the appropriate security contexts for your application, you can start using coldfusion security tags and...

  • Page 379: Using The Cfauthenticate Tag

    Using the cfauthenticate tag 359 using the cfauthenticate tag the cfauthenticate tag has several required attributes: • securitycontext describes which security context to use for authentication and authorization. This name matches the security context as defined on the advanced security page of the...

  • Page 380

    360 chapter 19 application security authentication and authorization functions after you use cfauthenticate to check whether the user is defined for a particular security context, you can use the following security functions throughout your applications any time you need to authenticate or authorize...

  • Page 381: Example

    Catching security exceptions 361 note the coldfusion server does not check user authorization unless you specifically request it with the isauthorized function. It is up to you to decide what action to take based on the results of the isauthorized call. Catching security exceptions you can use the c...

  • Page 382: Using The Cfimpersonate Tag

    362 chapter 19 application security using the cfimpersonate tag the cfimpersonate tag gives coldfusion developers a way to execute a segment of code in a secure manner. This tag is useful when you want to briefly grant a type of access that you would normally withhold. Suppose you are an internet se...

  • Page 383: Example

    Example of user authentication and authorization 363 example the following example reads a protected file because the coldfusion user pfoley has been granted access to the file by the security context mycontext. If the user cannot be authenticated, coldfusion throws a security exception. Username="p...

  • Page 384: Example: Application.Cfm

    364 chapter 19 application security response is checked against the list of valid users defined for the current security context. If the user passes the authentication step, the requested page appears. The application uses the cgi variables script_name and query_string to keep track of the originall...

  • Page 385: Example: Orders.Cfm

    Example of user authentication and authorization 365 checking for authentication and authorization inside application pages, you can use the isauthorized function to check whether an authenticated user is authorized to access the protected resources, and then display only the authorized resources. T...

  • Page 386

    366 chapter 19 application security select * from orders authorization succeeded. Order information follows: #customer# - #balancedue#.

  • Page 387: Using Cfobject to Invoke

    Chapter 20 using cfobject to invoke component objects this chapter describes how to use the cfobject tag to invoke objects created by component technologies, including com/dcom, corba, and java objects. Contents • component object overview................................................................

  • Page 388: Component Object Overview

    368 chapter 20 using cfobject to invoke component objects component object overview this section gives you some basic information on objects supported in coldfusion and provides resources for further inquiry. About com com (component object model) is a specification and a set of services defined by ...

  • Page 389: Invoking Component Objects

    Invoking component objects 369 invoking component objects you use the cfobject tag to create an instance of an object. You use other coldfusion tags, such as cfset and cfoutput , to invoke properties (attributes), and methods (operations) on the object. An object created by cfobject or returned by o...

  • Page 390: Calling Nested Objects

    370 chapter 20 using cfobject to invoke component objects calling nested objects the current release of coldfusion does not support nested (scoped) object calls. For example, if an object method returns another object and you must invoke a property or method on that object, use the following syntax:...

  • Page 391: Registering The Object

    Getting started with com/dcom 371 registering the object after you acquire the object you want to use, you must register it with windows in order for coldfusion (or any other program) to find it. Some objects might be deployed with their own setup programs that register objects automatically, while ...

  • Page 392

    372 chapter 20 using cfobject 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

    Getting started 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: Connecting To Com Objects

    374 chapter 20 using cfobject to invoke component objects creating and using com objects the following example uses cfobject to create the cdo (collaborative data objects) for nts newmail object to send mail. Action="create" name="mailer" class="cdonts.Newmail"> note cdo is installed by default on a...

  • Page 395

    Creating and using com objects 375 • local an out-of-process server object (typically an exe file) that is running outside the coldfusion process space but running locally on the same server. • remote an out-of-process server object (typically an exe file) that is running remotely on the network. If...

  • Page 396: Getting Started With Corba

    376 chapter 20 using cfobject to invoke component objects getting started with corba the coldfusion cfobject tag supports corba through the dynamic invocation interface (dii). As with com, the object’s type information has to be available to coldfusion. This requirement implies that an iiop-complian...

  • Page 397: Example

    Calling corba objects 377 example here is the idl for an object: struct simplestruct { short s; long l; float d; }; struct nestedstruct { simplestruct f; char c; string s; }; typedef sequence blongsequence; interface someobject { short somemethod( in nestedstruct instruct, in blongsequence inseq); }...

  • Page 398: Exception Handling

    378 chapter 20 using cfobject to invoke component objects exception handling you can catch exceptions thrown by the corba object methods with the cftry and cfcatch tags. However, you cannot extract information from the exception object. Calling java objects the cfobject tag can call any java class t...

  • Page 399

    Calling java objects 379 firstname =""; lastname =""; salary = 0.0f; jobgrade = 0; } public employee(string first, string last) { firstname = first; lastname = last; salary = 0.0f; jobgrade = 0; } public employee(string first, string last, float salary, int grade) { firstname = first; lastname = las...

  • Page 400: Java Considerations

    380 chapter 20 using cfobject to invoke component objects example: cfml page that uses the employee class save the following text as jemployee.Cfm: employee name is #firstname# #lastname# when you view the page in your browser, you should get the following output: employee name is john doe reviewing...

  • Page 401

    Calling java objects 381 • java method and field names are not case sensitive. Similarly, coldfusion variables are not case sensitive. As a result, the sample code works even though the cfml uses emp.Firstname and emp.Lastname, while the java source code uses firstname and lastname for these fields....

  • Page 402: Exception Handling

    382 chapter 20 using cfobject to invoke component objects default data type conversion whenever possible, coldfusion matches java types to coldfusion types as listed in the following table. Coldfusion does not support direct conversion of date/time variables and structures. Resolving ambiguous data ...

  • Page 403

    Calling java objects 383 example: exception-throwing class the following java code defines the foo class that throws a sample exception. It also defines a fooexception class that extends the java built-in exception class and includes a method for getting an error message. Public class foo { public f...

  • Page 404: The Class Loading Mechanism

    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...

  • Page 405: A More Complex Java Example

    Calling java objects 385 to disable automatic class loading, put all classes in the normal java class path. Classes located on the java class path are loaded once per server lifetime and can only be reloaded by stopping and restarting coldfusion server. A more complex java example the following code...

  • Page 406

    386 chapter 20 using cfobject to invoke component objects string[] ret = new string[arr.Length]; for (int i=0; i ret[arr.Length-i-1]=arr[i]; } return ret; } public int add(int a, int b) { return (a+b); } public float add(float a, float b) { return (a+b); } public example add(example a, example b) { ...

  • Page 407: The Useexample Cfml Page

    Calling java objects 387 the useexample cfml page the following useexample.Cfm page uses the example class to manipulate numbers, strings, booleans, and example objects. Note the use of the javacast cfml function to ensure that cfml variables convert into the appropriate java data types. Original ar...

  • Page 408

    388 chapter 20 using cfobject to invoke component objects intval1 :#intval# array1: #reversedarray[1]# array2: #reversedarray[2]# intval1: #intval#.

  • Page 409: Building Custom Cfxapi Tags

    Chapter 21 building custom cfxapi tags sometimes, the best approach is to develop elements of your application by building executables to run with coldfusion. Perhaps the application requirements go beyond what is currently feasible in cfml. Perhaps you can improve application performance for certai...

  • Page 410: What Are Cfx Tags?

    390 chapter 21 building custom cfxapi tags what are cfx tags? Cfx tags are custom tags written against the coldfusion extension application programming interface. Generally, you create a cfx if you want to do something that is not possible in cfml, or if you want to improve performance of a repetiti...

  • Page 411: Sample Java Cfxs

    Before you begin developing cfx tags in java 391 before you begin developing cfx tags in java while implementing cfx tags in java is easy, you should consider the information in this section before you begin developing them. Sample java cfxs before you begin developing a cfx tag in java, you might w...

  • Page 412

    392 chapter 21 building custom cfxapi tags the classes directory created by the coldfusion setup program serves two purposes: • it contains the supporting classes required for developing and deploying java cfxs. This is the com.Allaire.Cfx package located in the cfx.Jar archive. • it supports a feat...

  • Page 413: Writing A Java Cfx

    Writing a java cfx 393 writing a java cfx to create a java cfx, you create a class that implements the customtag interface. This interface contains one method, processrequest , which is passed request and response objects that are then used to do the work of the tag. To create a java cfx: 1 create a...

  • Page 414: Request Object

    394 chapter 21 building custom cfxapi tags this section provides an overview of these object types. For a complete example java cfx that uses request , response , and query objects, see the “zipbrowser example” on page 397. Request object the request object is passed to the processrequest method of ...

  • Page 415: Loading Java Cfx Classes

    Writing a java cfx 395 for detailed reference information on each of these interfaces, see the cfml reference. Loading java cfx classes each java cfx class has its own associated classloader that loads it and any dependent classes also located in the classes directory. When java cfxs are reloaded af...

  • Page 416: Life Cycle Of Java Cfxs

    396 chapter 21 building custom cfxapi tags the default value is reload="auto" . This is appropriate for most applications. Use reload="always" during the development process when you must ensure that you always have the latest class files, even when only a dependent class changed. Use reload="never"...

  • Page 417: Zipbrowser Example

    Zipbrowser example 397 coldfusion processes the page and returns a page that displays the text “hello, robert.” if an error is returned instead, check the source code to make sure you have entered it correctly. Zipbrowser example the following example illustrates the use of the request , response , ...

  • Page 418

    398 chapter 21 building custom cfxapi tags // read the zip file and build a query from its contents zipinputstream zin = new zipinputstream( new fileinputstream(strarchive) ) ; zipentry entry ; while ( ( entry = zin.Getnextentry()) != null ) { // add a row to the results int irow = files.Addrow() ; ...

  • Page 419

    Approaches to debugging java cfxs 399 if you need to debug a java cfx while running against a live production server, this is the technique you must use. In addition to outputting debug text using the response.Write method, you can also call your java cfx tag with the debug="on" attribute. This attr...

  • Page 420: Debugging Classes Example

    400 chapter 21 building custom cfxapi tags debugging classes example the following example demonstrates the use of the debugging classes: import java.Util.Hashtable ; import com.Allaire.Cfx.* ; public class outputquery implements customtag { // debugger testbed for outputquery public static void mai...

  • Page 421: Developing Cfx Tags In C++

    Developing cfx tags in c++ 401 developing cfx tags in c++ the following sections provide some background to help you develop cfx tags in c++. Sample c++ cfxs before you begin development of a cfx tag in c++, you might want to study the two cfx tags that are included to give you additional insight in...

  • Page 422: Compiling C++ Cfxs

    402 chapter 21 building custom cfxapi tags to build a cfx tag: 1 in visual c++, select file > new, and then click the projects tab. 2 select coldfusion tag wizard and enter a tag name of the form cfx_mynewtag in the project name box. Click ok to open the wizard. 3 enter the new tag name as the name ...

  • Page 423: On Unix

    Developing cfx tags in c++ 403 on unix use the following debuggers and settings for the supported unix operating systems: shut down coldfusion using the stop script. Set the environment variables as they are set in the start script. You can then run the cfserver executable under the dbx debugger and...

  • Page 424: Registering Cfxs

    404 chapter 21 building custom cfxapi tags registering cfxs to use a cfx tag in your coldfusion applications, first register it in the extensions, cfx tags page in the coldfusion administrator. To register a java cfx: 1 on the coldfusion administrator server tab, select extensions > cfx tags to open...

  • Page 425: Distributing Cfx Tags

    Distributing cfx tags 405 to delete a cfx tag: • click the delete applet (right-most) icon in the controls column of the registered cfx tags list for the tag you want to delete. On windows nt only, the visual c++ custom tag wizard automatically registers custom tags so that they can be tested and de...

  • Page 426

    406 chapter 21 building custom cfxapi tags to import a java 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] "classname"="pro...

  • Page 427: Index

    Index special #,using 14 , in search expressions 288 a accessing client variables 225 collections 298 data sources 21 generated content 187 action pages 45 active server pages 345 adding data elements to structures 127 data sources 22 elements to an array 119 administrative lock management 236 advan...

  • Page 428

    408 index b backreferences about 265 in regular expression searches 142 in replacement strings 265 bar charts, specifying appearance 68 base tags 180 between sql operator 27 binary files, saving 334 break, cfscript statement 248 browsers cfform considerations 138 displaying e-mail in 309 transferrin...

  • Page 429

    Index 409 interaction with cfscript 249 syntax checker 194 syntax errors 195 cfml expressions,in cfscript 245 cfml functions arrayappend 119 arraydeleteat 118 arrayinsertat 119 arraynew 119 arrayprepend 119 arrayset 121 arraysort 129 atructkeyarray 129 createtimespan 35 , 228 dateformat 94 deletecli...

  • Page 430

    410 index class path configuring 391 java objects and 368 class reloading, automatifc 395 classes, debugging 399 client cookies 222 client scope 214 client state management clustering 222 cookies for 222 described 221 enabling 223 client variables and cflocation tag 226 built-in 225 caching 226 char...

  • Page 431

    Index 411 arguments 251 calling 251 defining 250 described 250 error handling 256 evaluating strings 255 examples 253 identifying 253 in application.Cfm 254 passing arrays 255 using with queries 254 variables 252 custom tags ancestor 180 attributes 175 base 180 built-in variables 185 calling 173 , 1...

  • Page 432

    412 index editions of coldfusion 4 e-mail attachments 313 checking for spooled 308 customizing 306 deleting 314 error logging 308 for multiple recipients 306 form-based 304 handling pop 310 headers 310 indexing 270 , 284 integrating coldfusion 302 multiple recipients 305 query-based 304 receiving 30...

  • Page 433

    Index 413 referring to 45 scope of 45 , 48 formatting data items 50 query results 50 forms about 40 action pages 45 check boxes 84 considerations for 44 creating with cfform 136 deleting data 112 designing 44 drop-down list boxes 166 dynamically populating 82 html 40 inserting data 102 java applets ...

  • Page 434

    414 index class loading 395 debugging 398 , 399 example 397 importing 406 life cycle of 396 writing 393 java objects calling 378 considerations 380 exception handling 382 javacast cfml function 382 javascript differences from cfscript 248 validating with 144 joining tables 52 k keys, listing structu...

  • Page 435

    Index 415 post cfhttp method 332 , 337 pound signs, using 14 precedence rules, search 287 prefix notation, search strings 287 preservedata cfform attribute 137 problems, troubleshooting 195 processing application.Cfm 216 form variables on action pages 45 java cfx requests 393 onrequestend.Cfm 216 pr...

  • Page 436

    416 index scopes and custom functions 252 application 215 , 230 attributes 174 , 176 caller 174 , 176 client 214 , 221 , 223 file 185 form 14 , 45 local 14 locking 234 managing locking of 237 request 174 server 215 , 232 session 214 , 221 , 228 types 13 url 14 variables 14 variables, and custom tags...

  • Page 437

    Index 417 cfscript 244 , 245 sql 26 strings evaluating in functions 255 limiting size of 264 storing complex data in 353 structclear cfml function 130 structcopy cfml function 130 structcount cfml function 129 structdelete cfml function 130 structfind cfml function 129 structinsert cfml function 127...

  • Page 438

    418 index types of 13 url 14 using pound signs 14 validating 91 see also scope, built-in variables verbs, sql 26 verity about 270 see also searching, search expressions verity wizard 279 viewing application pages 11 online documentation xix w wddx and application-level data 347 and web services 346 ...