MACROMEDIA COLDFUSION 4.5-DEVELOPING WEB Applications - Debugging and Error Handling

Summary of COLDFUSION 4.5-DEVELOPING WEB

  • Page 1

    Allaire corporation developing web applications with coldfusion coldfusion 4.5.

  • Page 2: Copyright Notice

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

  • Page 3: Contents

    Contents preface: welcome to coldfusion ..................................................................Xv intended audience.........................................................................................................................Xvi welcome to the coldfusion 4.5 web application ser...

  • Page 4

    Iv developing web applications with coldfusion coldfusion server .....................................................................................................................6 coldfusion administrator...............................................................................................

  • Page 5

    Contents v creating table joins........................................................................................................................40 building flexible search interfaces ...............................................................................................40 code review ...

  • Page 6

    Vi developing web applications with coldfusion access to generated content...................................................................................................84 installing custom tags ........................................................................................................

  • Page 7

    Contents vii array functions.............................................................................................................................111 about structures ...........................................................................................................................113...

  • Page 8

    Viii developing web applications with coldfusion chapter 11: indexing and searching data .................................................149 searching a coldfusion web site................................................................................................150 advantages of using verity ...

  • Page 9

    Contents ix choosing a client variable storage method.........................................................................189 managing client state in a clustered environment ..................................................................190 using client state management.........................

  • Page 10

    X developing web applications with coldfusion chapter 14: managing files on the server .................................................219 using cffile ................................................................................................................................220 uploading files...

  • Page 11

    Contents xi chapter 17: application security ................................................................263 coldfusion security features......................................................................................................264 remote development services (rds) security .............

  • Page 12

    Xii developing web applications with coldfusion ccfxquery class ..........................................................................................................................295 class members....................................................................................................

  • Page 13

    Contents xiii invoking component objects......................................................................................................327 coding guidelines..................................................................................................................327 calling methods ......

  • Page 14

    Xiv developing web applications with coldfusion.

  • Page 15: Welcome To Coldfusion

    Preface welcome to coldfusion this manual describes the process of developing web applications using coldfusion. In the first six chapters, you can follow the instructions presented to learn how to create basic coldfusion applications. Then, chapters seven through 17 cover various topics of interest...

  • Page 16: Intended Audience

    Xvi developing web applications with coldfusion intended audience this manual is particularly useful for web application developers who are new to coldfusion. In particular, chapters 1 through 6 provide instructions for creating a basic coldfusion application. If you are somewhat familiar with coldf...

  • Page 17

    Preface xvii products and system requirements coldfusion has been fully tested on the following platforms and with the following configurations. Coldfusion server 4.5 enterprise edition for windows • windows nt 4.0 sp4+ • intel pentium or above • 150 mb hard disk space • 128 mb ram (256 mb recommend...

  • Page 18

    Xviii developing web applications with coldfusion coldfusion studio 4.5 • windows 95/98/nt4 • intel pentium or above • 35 mb hard disk space • 32 mb ram (64 mb recommended) new features in coldfusion 4.5 a wide range of new features are available in coldfusion 4.5. New visual tools universal file br...

  • Page 19

    Preface xix enhancements to cfml object scripting — instantiate and script objects using cfml script in addition to the cfobject tag easier integration with distributed object middleware such as com and corba. Structured exception handling — exception handling now offers hierarchical exception handl...

  • Page 20

    Xx developing web applications with coldfusion scriptable performance metrics — track key server metrics at run time through your own scripts for intelligent diagnosis of performance bottlenecks of stability problems in your applications. Performance debugging data — access detailed debugging inform...

  • Page 21: Developer Resources

    Preface xxi os server sandbox security — secure shared hosting environments more easily by creating server sandboxes with windows nt security. Os server sandboxes process all requests under the privileges of a designated windows nt user account (enterprise edition for windows only). Enhanced advance...

  • Page 22

    Xxii developing web applications with coldfusion about coldfusion documentation coldfusion documentation is designed to provide support for all components of the coldfusion development system. Both the print and online versions are organized to allow you to quickly locate the information you need. I...

  • Page 23

    Preface xxiii using coldfusion studio documents everything you need to know about using coldfusion studio, including features like projects, source control integration, as well as the studio workspace and interface. Coldfusion quick reference guide a valuable quick reference to cfml tags, functions,...

  • Page 24: Getting Answers

    Xxiv developing web applications with coldfusion documentation conventions when reading, please be aware of these formatting cues: • code samples, filenames, and urls are set in a monospaced font • notes and tips are identified by bold type • bulleted lists present options and features • numbered st...

  • Page 25

    Preface xxv technical support telephone support is available monday through friday 8 a.M. To 8 p.M. Eastern time (except holidays) toll free: 888.939.2545 (u.S. And canada) tel: 617.761.2100 (outside u.S. And canada) for complete details about allaire product support options, please refer to the all...

  • Page 26

    Xxvi developing web applications with coldfusion.

  • Page 27: Introduction to Coldfusion

    C h a p t e r 1 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 28: A Quick Web Overview

    2 developing web applications with coldfusion a quick web overview over the last few years, the web has changed from being simply a collection of static html pages to an application development platform. Rather than offering a space where organizations can merely advertise goods and services, simila...

  • Page 29: What Is Coldfusion?

    Chapter 1: introduction to coldfusion 3 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 ge...

  • Page 30

    4 developing web applications with coldfusion rapid development the coldfusion development platform enhances the speed and ease of development through the following features: • a tag-based server scripting language that is powerful and intuitive. • two-way visual programming and database tools. • re...

  • Page 31: Coldfusion Components

    Chapter 1: introduction to coldfusion 5 complete security coldfusion provides a foundation for building secure applications through the following features: • integration with existing authentication systems including windows nt domain and ldap directory servers, and proprietary user and group databa...

  • Page 32

    6 developing web applications with coldfusion coldfusion studio coldfusion studio is the development environment for coldfusion server. It offers visual development tools, including dynamic page previews using your web browser, an interactive debugger, a query builder, an expression builder, project...

  • Page 33: How Coldfusion Server Works

    Chapter 1: introduction to coldfusion 7 data sources coldfusion applications may interact with any database that supports the odbc standard. However, coldfusion is not limited to odbc data sources. You can also retrieve data using ole-db, native database drivers, or directory servers that support th...

  • Page 34

    8 developing web applications with coldfusion.

  • Page 35: Application

    C h a p t e r 2 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 36: The Development Process

    10 developing web applications with coldfusion the development process whether you are creating a static html page or a coldfusion application page, you follow the same iterative process: • write some code. • save the code to a document or page. • view the page in a browser. • modify the page. • sav...

  • Page 37: Saving Application Pages

    Chapter 2: writing your first coldfusion application 11 saving application pages instead of saving pages with an htm or html file extension, you save coldfusion application pages with a cfm or cfml extension. By default, the web server knows to pass a page that contains a cfm extension to the coldfu...

  • Page 38

    12 developing web applications with coldfusion compare the code that was returned to the browser with what you originally created. Notice that the coldfusion comments and cfml tags are processed, but do not appear in the html file that’s returned to the browser. Code review the application page that...

  • Page 39: Variables

    Chapter 2: writing your first coldfusion application 13 variables a web application page is different from a static web page because it can publish data dynamically. This involves creating, manipulating, and outputting variables. A variable stores data that can be used in applications. As with other...

  • Page 40: Development Considerations

    14 developing web applications with coldfusion adding more variables to the application applications can use many different variables. For example, the calldept.Cfm application page can set and display values for department, city, and salary. To modify the application: 1. Return to the file calldept...

  • Page 41: Querying A Database

    C h a p t e r 3 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 t...

  • Page 42: Publishing Dynamic Data

    16 developing web applications with coldfusion publishing dynamic data a web application page is different from a static web page because it can publish data dynamically. This can involve querying databases, connecting to ldap or mail servers, and leveraging com, dcom, corba, or java objects to retr...

  • Page 43

    Chapter 3: querying a database 17 data can be organized in multiple tables. This type of data structure is known as a relational database and is the type used for all but the simplest data sets. From this basic description, a few database design rules emerge: • each record should contain a unique id...

  • Page 44: Understanding Data Sources

    18 developing web applications with coldfusion understanding data sources a database is a file or server that contains a collection of data. A data source is a pointer from coldfusion to a specific database. You add data sources to your coldfusion server so that you can point to the databases that y...

  • Page 45: Adding Data Sources

    Chapter 3: querying a database 19 adding data sources you add data sources in the coldfusion administrator to define connection requirements for database access. When you add a data source, you assign it a name so that you can reference it within tags such as cfquery on application pages to query da...

  • Page 46: Retrieving Data

    20 developing web applications with coldfusion the data source is added to the data source list. 9. Locate companyinfo in the data source list. 10. Choose verify to run the verification test on the data source. If the data source was created, you should see this message: the connection to the data s...

  • Page 47: Writing Sql

    Chapter 3: querying a database 21 • performs sql commands that are enclosed within the block. • returns query variable values to the page. Cfquery tag syntax you’ll type sql here in this example, the query code tells coldfusion to: • use the companyinfo data source to connect to the company.Mdb data...

  • Page 48

    22 developing web applications with coldfusion when the database processes the sql, it creates a data set that is returned to coldfusion server. Coldfusion places the data set in memory and assigns it the name that you defined for the query in the begin cfquery tag. You may reference that data set b...

  • Page 49

    Chapter 3: querying a database 23 operators these specify conditions and perform logical and numeric functions: sql notes and considerations keep the following in mind when writing sql in coldfusion: • there is a lot more to sql than what is covered here. It’s a good idea to purchase one or several ...

  • Page 50: Building Queries

    24 developing web applications with coldfusion building queries as discussed earlier in this chapter, you build queries using the cfquery tag and sql. To query the table: 1. Create a new application page. 2. Edit the page so that it appears as follows: 4 4 select firstname, lastname, salary, contrac...

  • Page 51: Outputting Query Data

    Chapter 3: querying a database 25 query notes and considerations when creating queries to retrieve data, keep these guidelines in mind: • enter the query name and datasource attributes in the begin cfquery tag. • surround attribute settings with double quotes("). • reference the query data by naming...

  • Page 52

    26 developing web applications with coldfusion 4 #firstname#, #lastname#, #salary#, #contract# 4 3. Save the file as emplist.Cfm . 4. View the page in a browser. A list of employees appears in the browser, with each line displaying one row of data. You have created a coldfusion application page that...

  • Page 53

    Chapter 3: querying a database 27 • when outputting the data itself, you define the variable name using the query attribute. • when outputting query properties variables, don’t use the query attribute; instead, prefix the variable reference with the name of the query, for example, emplist.Recordcoun...

  • Page 54

    28 developing web applications with coldfusion 4 4 the query returned #emplist.Recordcount# records. 4 3. Save the file as emplist.Cfm . 4. View the page in a browser. The number of employees now appears below the list of employees. Code review you now display the number of records retrieved in the ...

  • Page 55: Data You Want

    C h a p t e r 4 chapter 4 retrieving and formatting the data you want this chapter explains how to select the data to display in a dynamic web page. It also describes how to populate an html table with query results and how to use coldfusion functions to format and manipulate data. Contents • using ...

  • Page 56

    30 developing web applications with coldfusion using forms to specify the data to retrieve until now, you’ve retrieved all of the records from a table. However, there are many instances when you’ll want to retrieve data based on certain criteria. For example, you may want to see records for everyone...

  • Page 57

    Chapter 4: retrieving and formatting the data you want 31 to create a form: 1. Create a new application page, using studio. 2. Edit the page so that it appears as follows: html form controls control code text control radio buttons displayname1 displayname2 displayname3 select box displayname1 displa...

  • Page 58

    32 developing web applications with coldfusion first name: maxlength="35"> last name: maxlength="35"> salary: city arlington boston cambridge minneapolis seattle department: training sales marketing contractor? Checked>yes 3. Save the page as formpage.Cfm within the myapps directory under your web r...

  • Page 59

    Chapter 4: retrieving and formatting the data you want 33 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 create one later in this chapter. Code review a form appears on the page, ready for user input. Code des...

  • Page 60

    34 developing web applications with coldfusion form notes and considerations • to make the coding process easy to follow, name form controls the same as target database fields. • limit radio buttons to three-to-five mutually exclusive options. If you need more than that many options, consider a drop...

  • Page 61: Creating Action Pages

    Chapter 4: retrieving and formatting the data you want 35 but when you want to return information about employees that match user search criteria, you use the sql where clause with a sql select statement to compare a value against a character string field. When the where clause is processed, it filt...

  • Page 62

    36 developing web applications with coldfusion 5. Enter data for the lastname form control and submit it. 6. Return to the form in your browser. 7. Reset the values. 8. Do not check the checkbox and submit the form again. An error occurs when the checkbox does not pass to the action page. You will r...

  • Page 63

    Chapter 4: retrieving and formatting the data you want 37 • form variables for checkboxes and radio buttons generate errors on action pages if nothing is selected for the form controls. Using html tables to layout query results you have displayed each row of data from the employees table, but the in...

  • Page 64

    38 developing web applications with coldfusion 4. View formpage.Cfm in your browser. 5. Enter data for the lastname form control and submit it. 6. The records that match the criteria specified in the form appear in a table. Code review formatting individual data items you may want to format individu...

  • Page 65: Performing Pattern Matching

    Chapter 4: retrieving and formatting the data you want 39 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...

  • Page 66: Creating Table Joins

    40 developing web applications with coldfusion creating table joins many times, the data that you want to retrieve is maintained in multiple tables. For example, in the database that you’re working with: • department information is maintained in the departments table. This includes department id num...

  • Page 67

    Chapter 4: retrieving and formatting the data you want 41 and employees.Lastname = ’form.Lastname’ code review to build a flexible search interface: 1. Return to actionpage.Cfm in studio. 2. Modify the page so that it appears as follows: 4 select departments.Department.Name, 4 employees.Firstname, 4...

  • Page 68

    42 developing web applications with coldfusion 3. Save the file. 4. Test the search interface in your browser. The returned records will not be displayed because you have not entered that code yet, however, you will see the number of records returned if you have debugging enabled. Returning query re...

  • Page 69

    Chapter 4: retrieving and formatting the data you want 43 select departments.Department.Name, employees.Firstname, employees.Lastname, employees.Startdate, employees.Salary from departments, employees where departments.Department_id = employees.Department_id and departments.Department_name = ’form.D...

  • Page 70

    44 developing web applications with coldfusion.

  • Page 71: Making Variables Dynamic

    C h a p t e r 5 chapter 5 making variables dynamic this chapter explains how to use cfml to dynamically populate forms and dynamically generate sql. Contents • dynamically populating select boxes ............................................................ 46 • creating dynamic checkboxes and multip...

  • Page 72

    46 developing web applications with coldfusion dynamically populating select boxes in the previous chapter, you hard-coded a form’s select box options. Instead of manually entering the information on a form, you can dynamically populate a select box with database fields. When you code this way, chan...

  • Page 73

    Chapter 5: making variables dynamic 47 4 department: training sales marketing 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. Creating dynamic chec...

  • Page 74

    48 developing web applications with coldfusion searching numeric values suppose you want a user to select one or more departments using checkboxes. You query the database to retrieve detailed information on the selected department(s). Select one or more departments to get information on: name="selec...

  • Page 75

    Chapter 5: making variables dynamic 49 the first example searched for department information based on a numeric primary key field called "department_id." suppose, instead, that the primary key is a database field called "departmentname" that contains string values. In that case, it’s necessary to ma...

  • Page 76

    50 developing web applications with coldfusion multiple select list is a comma-delimited list of the entries selected by the user. For example, a multiple select list contains four entries: training, marketing, hr, and sales. The user selects marketing and sales. The value of the form field variable...

  • Page 77

    Chapter 5: making variables dynamic 51 sales name="selectdepts_required" value="you must select at least one department."> if the user selected the marketing and sales items, the value of the selectdepts form field would be ’marketing’,’sales’. Just as you did when using checkboxes to search databas...

  • Page 78

    52 developing web applications with coldfusion there are two ways to use the cfparam tag, depending on how you want the validation test to proceed. • use cfparam with only the name attribute to test that a required variable exists. If it does not exist, the coldfusion server stops processing the pag...

  • Page 79: Dynamic Sql

    Chapter 5: making variables dynamic 53 example: checking data types select * from departments where dept_id= cfsqltype="cf_sql_integer"> department number: #number# description: #descript# cfsqltype="cf_sql_integer"> department number: #number# description: #descript# dynamic sql embedding sql queri...

  • Page 80

    54 developing web applications with coldfusion queryname" datasource=" datasourcename"> ... Base sql statement ... Additional sql first, you need to create an input form, which asks for information about several fields in the employees table. Instead of entering information in each field, a user may...

  • Page 81

    Chapter 5: making variables dynamic 55 3. Save the page as askemp.Cfm . Once you have created the input form, you can then create the action page to process the user’s request. This action page will determine where the user has entered search criteria and search based only on those criteria. To crea...

  • Page 82

    56 developing web applications with coldfusion 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. The results should meet the criteria you specify. Code review the action page getemp.Cfm build a sql statement dyna...

  • Page 83

    Chapter 5: making variables dynamic 57 and employees.Lastname like ’#form.Lastname#%’ if the user entered anything in the lastname text box in the form, add "and employees.Lastname like ‘[what the user entered in the lastname text box]%'" to the sql statement. And employees.Salary >= #form.Salary# i...

  • Page 84

    58 developing web applications with coldfusion.

  • Page 85: Updating Your Data

    C h a p t e r 6 chapter 6 updating your data this chapter describes how to insert, update, and delete data in a database with coldfusion. Contents • inserting data ................................................................................................... 60 • creating an html insert form......

  • Page 86: Inserting Data

    60 developing web applications with coldfusion inserting data inserting data into a database is usually done with two application pages: • an insert form • an insert action page you can create an insert form with cfform tags (see “creating forms with the cfform tag” on page 124 ) or with standard ht...

  • Page 87

    Chapter 6: updating your data 61 3. Save the file as insertform.Cfm in the myapps directory. 4. View insertform.Cfm in a browser. Data entry form notes and considerations creating data entry fields for an html form is very simple: • you need only create the html form fields for each database field i...

  • Page 88: Updating Data

    62 developing web applications with coldfusion 3. Save the page. As insertpage.Cfm . 4. View insertform.Cfm in a browser, enter values, and click the submit button. 5. The data is inserted into the employees table and the message appears. To create an insert page with cfquery: 1. Create a new applic...

  • Page 89: Creating An Update Form

    Chapter 6: updating your data 63 creating an update form an update form is similar to an insert form, but there are two key differences: • an update form contains a reference to the primary key of the record that is being updated. A primary key is a field or combination of fields in a database table...

  • Page 90

    64 developing web applications with coldfusion 3. Save the page. As updatedorm.Cfm . 4. View updateform.Cfm in a browser. Code review code description datasource="companyinfo"> select * from employees where employee_id = #url.Employee_id# datasource="companyinfo"> select * from employees where emplo...

  • Page 91

    Chapter 6: updating your data 65 creating an action page to update data you can create an action page to update data with either the cfupdate tag or cfquery with the update statement. The cfupdate tag is the easiest way to handle simple updates from a front end form. The cfupdate tag has an almost i...

  • Page 92: Deleting Data

    66 developing web applications with coldfusion 4 update employees 4 set firstname=’#form.Firstname#’, 4 lastname=’#form.Lastname#’, 4 department_id=’#form.Department_id#’ 4 startdate=’#form.Startdate#’> 4 salary=#form.Salary#> where employee_id=#employee_id# you have updated the information for #for...

  • Page 93

    Chapter 6: updating your data 67 5. Enter the following code: datasource="companyinfo"> delete from employees where employee_id = #url.Employeeid# datasource="companyinfo"> delete from employees where employee_id = #url.Employeeid# 6. Save the page. As deletepage.Cfm . 7. View deleteform.Cfm in a br...

  • Page 94

    68 developing web applications with coldfusion example, if you want the error message to read "you must enter your first name," use the syntax: name="firstname_required" value="you must enter your first name."> validating the data that users enter in form fields another limitation of html forms is t...

  • Page 95

    Chapter 6: updating your data 69 to validate the data users enter in the insert form 1. Open the file insertform.Cfm in studio. 2. Modify the file so that it appears as follows: name="deptid_integer" value="the department id must be a number."> name="startdate_date" value="enter a valid date as the ...

  • Page 96

    70 developing web applications with coldfusion name="resetform" value="clear form"> name="submitform" value="insert data"> 3. Save the file. The value attribute is optional. A default message displays if no value is supplied. When the form is submitted, coldfusion scans the form fields to find any v...

  • Page 97: Reusing Code

    C h a p t e r 7 chapter 7 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 ......................................................................................... 72 • reusing common...

  • Page 98: Ways To Reuse Code

    72 developing web applications with coldfusion ways to reuse code coldfusion provides several different ways to reuse code. If you are using coldfusion studio, you can write code snippets, which you can copy into templates. For more information on writing code snippets, see using coldfusion studio. ...

  • Page 99: About Custom Tags In Cfml

    Chapter 7: reusing code 73 about custom tags in cfml custom tags wrap functionality in a page that can be called from a coldfusion application page. Coldfusion custom tags built in cfml allow for rapid application development and code re-use while offering off-the-shelf solutions to many programming...

  • Page 100

    74 developing web applications with coldfusion defining attributes cfml custom tags support both required and optional attributes. Attributes are defined as name-value pairs. Custom tag attributes conform to cfml coding standards: • coldfusion passes any attributes in the attributes scope. • use the...

  • Page 101

    Chapter 7: reusing code 75 4 before you leave this page, you’re #nameyouentered#. 4 you are now #doctor#. 3. Save the page as callingpage.Cfm . 4. Create another new page (the custom tag) in studio. 5. Enter the following code: 6. Save the page as getmd.Cfm . 6. Save the page as getmd.Cfm ..

  • Page 102

    76 developing web applications with coldfusion 7. Open the file callingpage.Cfm in your browser. The calling page uses the getmd custom tag and displays the results. Code review tip be careful not to overwrite variables that might already exist on the calling page. You should adopt a naming conventi...

  • Page 103: Nesting Custom Tags

    Chapter 7: reusing code 77 nesting custom tags coldfusion lets you turn a custom tag into a special kind of container that can enclose additional custom tags, which allows you to nest tags. Base tags are also know as ancestors or parent tags, while the tags that base tags call are known as sub tags,...

  • Page 104

    78 developing web applications with coldfusion passing data between nested custom tags a key custom tag feature is the ability of collaborating custom tags to exchange complex data without user intervention and without violating the encapsulation of a tag’s implementation outside the circle of its c...

  • Page 105

    Chapter 7: reusing code 79 when cfassociate is encountered in a sub tag, the sub tag’s attributes are automatically saved in the base tag. The attributes are in a structure appended to the end of an array whose name is ‘thistag.Collection_name'. The default value for the datacollection attribute is ...

  • Page 106

    80 developing web applications with coldfusion example: ancestor data access this example was snipped from a custom tag. I’m custom tag #listgetat(ancestorlist,2)# i’m running in the context of a cfloop tag. List=#listrest(listrest(ancestorlist))#> list=#listrest(listrest(ancestorlist))#> i’m runnin...

  • Page 107

    Chapter 7: reusing code 81 i’m not nested inside any custom tags. :^( passing custom tag arguments via cfml structures attributes can be passed to custom tags via the reserved attribute attributecollection. Attributecollection must reference a structure. Syntax cfmodule otherattr1=value attributecol...

  • Page 108: Executing Custom Tags

    82 developing web applications with coldfusion examples via cfmodule a="blab" attributecollection=#zort# foo="16"> via shorthand accessing attributes within the custom tag if testtwo.Cfm contains this cfml: ---custom tag --- #attributes.A# #attributes.X# #attributes.Y# #attributes.Foo# --- end custo...

  • Page 109

    Chapter 7: reusing code 83 • assocattribs — holds the attributes of all nested tags if cfassociate was used them. Pattern of execution the same cfml template is executed for both the start and end tag of a custom tag. Modes of execution coldfusion invokes a custom tag template in either of two modes...

  • Page 110

    84 developing web applications with coldfusion terminating tag execution cfexit terminates execution of a custom tag. Cfexit’s method attribute specifies where execution continues. Cfexit can specify that processing continues from the first child of the tag or continues immediately after the end tag...

  • Page 111: Installing Custom Tags

    Chapter 7: reusing code 85 ’’> installing custom tags custom tags are just like other .Cfm files except that they must be installed in a specific location to be accessible from the calling template. Because coldfusion loads the first instance it finds of the custom tag called by a template, you shou...

  • Page 112

    86 developing web applications with coldfusion securing custom tags coldfusion’s security framework enables you to selectively restrict access to individual tags or to tag directories. This can be an important safeguard in team development. To avoid name conflicts, you can register custom tags as a ...

  • Page 113

    Chapter 7: reusing code 87 the following options are supported: note while it is possible to encode binary files with cfencode , it is not recommended. Cfencode command line options option description input file name of the file you want to encode. Cfencode will not process an encoded file. Output f...

  • Page 114

    88 developing web applications with coldfusion.

  • Page 115: Debugging and Error Handling

    C h a p t e r 8 chapter 8 debugging and error handling coldfusion includes sophisticated debugging and code validation tools. This chapter gives an overview of the debugging options available in the coldfusion administrator and how to enable cfml attribute validation. In addition, the coldfusion ser...

  • Page 116

    90 developing web applications with coldfusion debug settings in the coldfusion administrator coldfusion can provide important debugging information for every application page requested by a browser. When enabled, debugging output is shown in a block following normal page output. For detailed inform...

  • Page 117: Cfml Code Validation

    Chapter 8: debugging and error handling 91 tip if you get a message that does not explicitly identify the cause of the error, check on key system parameters like available memory and disk space. For information on using the logging settings and mail logging settings, see administering coldfusion ser...

  • Page 118

    92 developing web applications with coldfusion connection errors may include problems with the location of files, network connections, and database client library configuration. First, verify that you can connect to the database by clicking the verify button on the odbc data sources page of the cold...

  • Page 119

    Chapter 8: debugging and error handling 93 generating custom error messages (cferror) coldfusion displays error pages that can help you to debug your application. There are four types of errors in coldfusion: • request — request errors occur when a application page is requested and there is an error...

  • Page 120

    94 developing web applications with coldfusion an error occurred when you requested this page. Please email the webmaster to report this error. We will work to correct the problem and apologize for the inconvenience. #error.Datetime# #error.Template# #error.Remoteaddress# #error.Httpreferer# example...

  • Page 121

    Chapter 8: debugging and error handling 95 note for cases when the error handler is not able to successfully handle the thrown error, use the cfrethrow tag within a block. ... Add code here ... Exception type1"> ... Add exception processing code here ... Exception type2"> ... Add exception processin...

  • Page 122

    96 developing web applications with coldfusion types of recoverable exceptions type tag(s) notes application-defined exception events cfthrow cfcatch type="application" cfcatch type="any" a cfcatch block that has no type attribute raise exceptions using the cfthrow tag (with an optional diagnostic m...

  • Page 123

    Chapter 8: debugging and error handling 97 specifying the type as any causes the coldfusion application server to catch internal exceptions, memory allocation errors, and access violations, which you may not be prepared to handle. Applications can optionally use the cfthrow tag to raise custom excep...

  • Page 124

    98 developing web applications with coldfusion tag context information the coldfusion administrator’s debugging settings page allows you to"enable cfml stack trace." when this setting is enabled, cfcatch blocks make available an array of structures called cfcatch.Tagcontext. Each structure represent...

  • Page 125

    Chapter 8: debugging and error handling 99 database exceptions for database exceptions, coldfusion supplies some additional diagnostic information. The following variables are available whenever the exception type is database: expression exceptions locking exceptions for exceptions related to cflock...

  • Page 126: Exception Handling Example

    100 developing web applications with coldfusion missinginclude exceptions for exceptions related to missing files, where the type of exception is missinginclude, the following variable is available: exception handling strategies use cftry with cfcatch to handle exceptions based on their point of ori...

  • Page 127

    Chapter 8: debugging and error handling 101 department: #departmentid# last name: #lastname# first name: #firstname# 4 4 4 4 4.

  • Page 128: Custom Exception Types

    102 developing web applications with coldfusion 4 4 custom exception types the type attribute allows a cfthrow tag to throw an exception of a specific type, which can be caught by a cfcatch tag that has a matching type attribute. A cfthrow tag without a type attribute will throw a type="application"...

  • Page 129: Handling Complex Data

    C h a p t e r 9 chapter 9 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 su...

  • Page 130: About Arrays

    104 developing web applications with coldfusion about arrays traditionally, an array is a tabular structure used to hold data, much like a spreadsheet table with clearly defined limits and dimensions. A 2-dimensional (2d) array is like a simple table. In coldfusion, you typically use arrays to tempo...

  • Page 131: Creating An Array

    Chapter 9: handling complex data with structures 105 coldfusion dynamic 2d array a coldfusion 2d array is actually a 1d array that contains a series of additional 1d arrays. Each of the arrays that make up a column can expand and contract independently of any other column. The following terms will h...

  • Page 132: Basic Array Techniques

    106 developing web applications with coldfusion multidimensional arrays coldfusion supports dynamic multidimensional arrays. When you declare an array with the arraynew function, you can specify up to three dimensions. However, you can increase an array’s dimensions by nesting arrays as array elemen...

  • Page 133

    Chapter 9: handling complex data with structures 107 firstname[1]=coleman firstname[2]=dexter adding elements to an array you can add elements to an array by simply defining the value of an array element: but you can also employ a number of array functions to add data to an array. You can use arraya...

  • Page 134

    108 developing web applications with coldfusion #fullname[1][1]# #fullname[2][1]# #fullname[1][2]# #fullname[2][2]# #fullname[1][3]# #fullname[2][3]# additional referencing methods you can reference array indexes in the standard way: myarray[x] where x is the index you want to reference. You can als...

  • Page 135

    Chapter 9: handling complex data with structures 109 in the following example, a simple one-dimensional array is populated with the names of the months using a cfloop. A second cfloop is used to output data in the array to the browser. #months[loopcount]# using nested loops for 2d and 3d arrays to o...

  • Page 136

    110 developing web applications with coldfusion my3darray’s values are currently: from="1" to="#arraylen(my3darray)#"> from="1" to="#arraylen(my3darray[dim1])#"> to="#arraylen(my3darray[dim1][dim2])#"> [#dim1#][#dim2#][#dim3#]: #my3darray[dim1][dim2][dim3]# from="1" to="#arraylen(my3darray)#"> from=...

  • Page 137: Array Functions

    Chapter 9: handling complex data with structures 111 id: #myarray[counter][1]#, lastname: #myarray[counter][2]#, firstname: #myarray[counter][3]#, email: #myarray[counter][4]# array functions the following functions are available for creating, editing, and handling arrays: array functions function d...

  • Page 138

    112 developing web applications with coldfusion for more information about each of these functions, see the cfml language reference. Arrayresize resets an array to a specified minimum number of elements. Arrayset sets the elements in a 1d array in a specified range to a specified value. Arraysort re...

  • Page 139: About Structures

    Chapter 9: handling complex data with structures 113 about structures coldfusion supports the creation and handling of structures, which enable developers to create and maintain key-value pairs. A structure lets you build a collection of related variables that are grouped under a single name. Struct...

  • Page 140

    114 developing web applications with coldfusion creating and using structures this section explains how to use the structure functions to create and use structures in coldfusion. The sample structure is called employee, and is used to add new employees to a corporate information system. Creating str...

  • Page 141

    Chapter 9: handling complex data with structures 115 finding information in structures to find the value associated with a specific key, use the structfind function: structfind( structure_name, key) example the following example shows how to generate a list of keys defined for a structure. Key - #pe...

  • Page 142

    116 developing web applications with coldfusion but if the key is dynamic, or contains special characters, you must use the structkeyexists function: structure_name, key)> getting a list of keys in a structure to get a list of the keys in a cfml structure, you use the structkeylist function: structu...

  • Page 143: Structure Example

    Chapter 9: handling complex data with structures 117 structure example structures are particularly useful for grouping together a set of variables under a single name. In the following example files, structures are used to collect information from a form, structinsert.Cfm , and to submit that inform...

  • Page 144

    118 developing web applications with coldfusion first name: last name: email: phone: department: example file addemployee.Cfm this file is an example of a custom tag used to add employees. Employee information is passed through the employee structure (the empinfo attribute). In unix, you must also a...

  • Page 145

    Chapter 9: handling complex data with structures 119 ) employee add complete using structures as associative arrays you can also use structures as associative arrays. When used as associative arrays, structures index repetitive data by string keys rather than by integers. You might use structures to...

  • Page 146: Structure Functions

    120 developing web applications with coldfusion called person to hold value of key as loop runs ---> structure functions there are several functions that help you create and manage structures in coldfusion applications. Structure functions function description isstruct returns true if the specified ...

  • Page 147

    Chapter 9: handling complex data with structures 121 note that in all cases, except structdelete, an exception will be thrown if the referenced key or structure does not exist. For more information on these functions, see the cfml language reference. Structnew returns a new structure. Structupdate u...

  • Page 148

    122 developing web applications with coldfusion.

  • Page 149: Building Dynamic Forms

    C h a p t e r 1 0 chapter 10 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. These controls can be enabled without the need to code java directly. Contents • creating for...

  • Page 150

    124 developing web applications with coldfusion creating forms with the cfform tag you’ve already learned how to use html forms to gather user input. (see “using forms to specify the data to retrieve” on page 30 .) this chapter shows you how to use the cfform tag to create dynamic forms in cfml. In ...

  • Page 151

    Chapter 10: building dynamic forms 125 improving performance with enablecab the cfform enablecab attribute allows you to improve the performance of java- applet based cfform controls. When you use enablecab, coldfusion prompts the end user to accept a download of the java classes needed for the cffo...

  • Page 152

    126 developing web applications with coldfusion input validation with cfform controls the cfinput and cftextinput tags include the validate attributes which allows you to specify a valid data type entry for the control. You can validate user entries on the following data types. When you specify an i...

  • Page 153

    Chapter 10: building dynamic forms 127 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 handl...

  • Page 154

    128 developing web applications with coldfusion to use javascript to validate form data: 1. Create a new file in studio. 2. Edit the page so that it appears as follows: 4 please enter your email address: action="update.Cfm" > name="inputbox1" required="yes" 4 onvalidate="testbox" message="sorry, inv...

  • Page 155

    Chapter 10: building dynamic forms 129 code review see the following web site for information on javascript validation scripts: • http://www.Dannyg.Com/javascript building tree controls with cftree the cftree form lets you display hierarchical information in a space-saving collapsible tree populated...

  • Page 156

    130 developing web applications with coldfusion 4 query="engquery" 4 queryasroot="yes" 4 img="folder,document"> 4 3. Save the page and view it in your browser. Code review grouping output from a query in a similar query, you may want to organize your employees by the department. In this case, you se...

  • Page 157

    Chapter 10: building dynamic forms 131 method="post"> hscroll="no" vscroll="no" border="yes" height="350" required="yes"> query="deptquery" queryasroot="department_id" img="cd,folder"> method="post"> hscroll="no" vscroll="no" border="yes" height="350" required="yes"> query="deptquery" queryasroot="d...

  • Page 158: Structuring Tree Controls

    132 developing web applications with coldfusion • form.Treename.Path — returns the complete path of the user selection, in the form: rootode1ode2ode_n\value the root part of the path is only returned if you set the completepath attribute tof cftree to yes; otherwise, the path value starts with...

  • Page 159

    Chapter 10: building dynamic forms 133 example: multi-level tree control when populating a cftree, you manipulate the structure of the tree by specifying a treeitem parent. In this example, every treeitem, except the top level, specifies a parent. The parent attribute allows your cftree to show the ...

  • Page 160: Embedding Urls In A Cftree

    134 developing web applications with coldfusion the built-in image names are: • cd • computer • document • element • folder • floppy • fixed • remote embedding urls in a cftree the href attribute in the cftreeitem tag allows you to designate tree items as links. To use this feature in a cftree, you ...

  • Page 161

    Chapter 10: building dynamic forms 135 code review specifying which tree items to send to the action page when a user selects a tree item and submits the form, the cftreeitemkey variable is appended to the url passed to the application page specified in the cfform action attribute, in the form: http...

  • Page 162

    136 developing web applications with coldfusion populating a grid from a query to populate a grid from a query: 1. Open a new file named grid1.Cfm in studio. 2. Edit the file so that it appears as follows: select * from employees selectmode="single"> selectmode="single"> note use the cfgridcolumn di...

  • Page 163

    Chapter 10: building dynamic forms 137 code review note if you specify a cfgrid tag with a query attribute defined and no corresponding cfgriditem attributes the default grid that is created contains all the columns in the query. Creating an updateable grid you can build grids to allow users to edit...

  • Page 164

    138 developing web applications with coldfusion editing data in a cfgrid to enable grid editing, you use the selectmode="edit" attribute. When enabled, a user can edit cell data and insert or delete grid rows. When a cfform containing a cfgrid is submitted, data about changes to grid cells are store...

  • Page 165

    Chapter 10: building dynamic forms 139 headeritalic="no" headerbold="yes" display="yes" select="yes"> header="department" width=240 italic="no" headeralign="center" headeritalic="no" headerbold="yes" bold="yes" display="yes"> 3. Save the file as grid2.Cfm . To update the data source with cfquery: 1....

  • Page 166

    140 developing web applications with coldfusion datasource="companyinfo"> update employees set lastname=’#form.Employee_grid.Lastname[counter]#’, department_id=#form.Employee_grid.Department_id[counter]# where employee_id=#form.Employee_grid.Original.Employee_id[counter]# datasource="companyinfo"> u...

  • Page 167

    Chapter 10: building dynamic forms 141 how user edits are stored the following arrays are created to keep track of edits to grid rows and cells: for example, you have an updateable cfgrid called "mygrid" consisting of two displayable columns, col1, col2, and one hidden column, col3. When an end user...

  • Page 168: Building Text Entry Boxes

    142 developing web applications with coldfusion building slider bar controls you can use the cfslider control to create a slider control and define a wide range of formatting options for slider label text, , colors for the groove in which the slider knob moves, label font name, size, boldface, itali...

  • Page 169

    Chapter 10: building dynamic forms 143 validation methods using either a javascript or the validate attribute in cftextinput. The following example shows a basic cftextinput control. This example validates a date entry, which means that a user must enter a valid date in the form mm/dd/yy. For a comp...

  • Page 170: Embedding Java Applets

    144 developing web applications with coldfusion to populate a drop-down list box with query data using cfselect: 1. Open a new file in studio. 2. Modify the file so that it appears as follows: datasource="companyinfo"> select * from employees datasource="companyinfo"> select * from employees method=...

  • Page 171

    Chapter 10: building dynamic forms 145 • parameter options — you can override parameter values you defined in the administrator by specifying the parameter value pair in cfapplet. Unless overridden, coldfusion uses the parameter value pairs you defined in the administrator. When an applet is registe...

  • Page 172

    146 developing web applications with coldfusion click create to complete the process. Using cfapplet to embed an applet once you’ve registered 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 ...

  • Page 173

    Chapter 10: building dynamic forms 147 name="applet1_var" height=400 width=200 vspace=125 hspace=125 align="left"> overriding parameter values you can also override the values you assigned to applet parameters in the administrator by providing new values for any parameter. Note that in order to over...

  • Page 174

    148 developing web applications with coldfusion.

  • Page 175: Indexing and Searching Data

    C h a p t e r 1 1 chapter 11 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. Contents • searching a coldfusion web site....................................................................

  • Page 176

    150 developing web applications with coldfusion searching a coldfusion web site until now, you’ve searched for records in databases based on the value of particular fields using odbc. However, to efficiently search through paragraphs of text or files of varying types requires full-text search capabi...

  • Page 177: Supported File Types

    Chapter 11: indexing and searching data 151 online verity training a video titled "creating search engines with verity" is available at http:// alive.Allaire.Com . The video gives an overview of the verity implementation in coldfusion and illustrates the development process with sample code. The vid...

  • Page 178

    152 developing web applications with coldfusion support for international languages the coldfusion international language search pack can be purchased and installed to index data in any the following languages: • danish • dutch • finnish • french • german • italian • norwegian • portuguese ms word f...

  • Page 179: Creating A Collection

    Chapter 11: indexing and searching data 153 • spanish • swedish the default language for verity collections is english. To index data in one of the supported languages, you must select the language from the drop-down list when you create a collection on the coldfusion administrator verity page. You ...

  • Page 180

    154 developing web applications with coldfusion using the coldfusion administrator to create a collection to create a new collection: 1. Open the coldfusion administrator verity page. If you checked the option to install the coldfusion documentation, the documentation collection is listed by default...

  • Page 181

    Chapter 11: indexing and searching data 155 collection name: size="25"> what do you want to do with the collection? Name="collectionaction" value="create" checked>create name="collectionaction" value="repair">repair name="collectionaction" value="optimize">optimize name="submit" value="submit"> 3. S...

  • Page 182

    156 developing web applications with coldfusion to create a collection action page: 1. Open a new file in studio. 2. Modify the file so that it appears as follows: collection="#form.Collectionname#" path="c:\cfusion\verity\collections\"> the collection #form.Collectionname# is created. Collection="#...

  • Page 183

    Chapter 11: indexing and searching data 157 populating and indexing a collection at this point, the new collection is just an empty shell. To populate the collection with indexed data, you can use either of two methods: • the cf administrator • the cfindex tag you can use the verity wizard in coldfu...

  • Page 184

    158 developing web applications with coldfusion 5. Check the recursively index subdirectories box if you want to extend the indexing operation to all directories below the selected path. 6. Optionally, you can enter a return url to prepend to all indexed files. This allows you to easily create a lin...

  • Page 185: Building A Search Interface

    Chapter 11: indexing and searching data 159 to use cfindex to index a collection: 1. Open a new file in studio. 2. Modify the file so that it appears as follows: key="#form.Indexdir#" action="refresh" type="path" urlpath="#form.Indexdir#" extensions=".Htm, .Html" recurse="yes" language="english"> th...

  • Page 186

    160 developing web applications with coldfusion basic search operations to search the collection: 1. Create a new file in stuio. 2. Modify the file so that it appears as follows: enter the collection you want to search: p> select the type of search: name=type value=simple checked> simple name=type v...

  • Page 187

    Chapter 11: indexing and searching data 161 collection="#form.Collection#" form type="#form.Type#" criteria="#form.Searchstring#"> search results collection="#form.Collection#" form type="#form.Type#" criteria="#form.Searchstring#"> #search1.Recordcount# found out of #search1.Recordssearched# search...

  • Page 188

    162 developing web applications with coldfusion cfsearch properties three properties are generated for each cfsearch query that provide information about a particular query: • recordcount — the total number of records returned by the query. • currentrow — the current row of the query being processed...

  • Page 189

    Chapter 11: indexing and searching data 163 this cfindex statement specifies the messagetext column as the core of the collection and names the table’s primary key, the message_id column, as the key value. Note that the title attribute names the subject column. The title attribute can be used to des...

  • Page 191: Using Query Expressions

    Chapter 11: indexing and searching data 165 name="p_messages server="mail.Mycompany.Com" username="user1" password="user1"> #messagenumber# #from# #to# #subject# #body# ========================= collection="pop_query" key="messagenumber" type="custom" title="subject" query="p_messages" body="body"> ...

  • Page 192

    166 developing web applications with coldfusion pass a simple query expression to the search engine directly from an html input form. The verity query language provides many operators and modifiers for composing queries. The following search techniques can be used in searching a verity collection: •...

  • Page 193

    Chapter 11: indexing and searching data 167 density of the search term in the searched documents. The more frequent the occurrence of a word in a document, the higher the document’s score. As a result, the search engine ranks documents according to word density as it searches for the word you specif...

  • Page 194: Composing Search Expressions

    168 developing web applications with coldfusion special characters a number of characters are handled in particular ways by the search engine. A backslash (\) removes special meaning from whatever character follows it. To enter a literal backslash in a query, use two in succession, such as this exam...

  • Page 195

    Chapter 11: indexing and searching data 169 when prefix notation is used, precedence is handled explicitly within the expression. The following example means: "look for documents that contain b and c first, then documents that contain a": or (a, and (b,c)) when infix notation is used, precedence is ...

  • Page 196: Searching With Wildcards

    170 developing web applications with coldfusion searching with wildcards this table shows the wildcard characters for searching verity collections. Searching for wildcards as literals to search for a wildcard character in your collection, you need to escape the character with a backslash (\). For ex...

  • Page 197: Operators And Modifiers

    Chapter 11: indexing and searching data 171 • left curly brace ({) • left bracket ([) • less than sign ( • backquote (‘ ) in addition to the backslash character, you can use paired backquotes (‘ ‘ ) to interpret special characters as literals. For example, to search for the wildcard string "a{b" you...

  • Page 198

    172 developing web applications with coldfusion • natural language operators — allow the use of natural language expressions in forming queries. Ordinarily, you use operators in explicit searches. They are used in the following manner: "search_string" evidence operators evidence operators can be use...

  • Page 199

    Chapter 11: indexing and searching data 173 the following table describes each operator. Relational operators relational operators search document fields that have been defined in the collection. Documents containing specified field values are returned. Documents retrieved using relational operators...

  • Page 200

    174 developing web applications with coldfusion the following operators are used for numeric and date comparisons. Text comparison operators match words and parts of words. The following operators are used for text comparisons. Verity numerical and date relational operators operator description = eq...

  • Page 201

    Chapter 11: indexing and searching data 175 document fields the values you specify for the cfindex attributes title, key, url, and custom can be specified as document fields for use with relational operators in the criteria attribute. Document fields are referenced in text comparison operators. They...

  • Page 202

    176 developing web applications with coldfusion the following application page matches records that have 1990 in the text column and are in the place utah. The search is performed against the collection that contains the text column and then is narrowed further by searching the string "utah" in the ...

  • Page 203

    Chapter 11: indexing and searching data 177 #gettext_search.Title# concept operators concept operators combine the meaning of search elements to identify a concept in a document. Documents retrieved using concept operators are ranked by relevance. The following table describes each concept operator....

  • Page 204

    178 developing web applications with coldfusion the following table lists the score operators. Modifiers modifiers can be used with operators to further refine query expressions. You can specify case sensitivity in a query, or force the output to be ranked by relevancy. Modifiers include: • case — s...

  • Page 205

    Chapter 11: indexing and searching data 179 search modifiers modifiers are combined with operators to change the standard behavior of an operator in some way. For example, you can use the case modifier with an operator to specify that you want to match the case of the search word. Modifiers are as f...

  • Page 206: Managing Collections

    180 developing web applications with coldfusion managing collections as with any data source, the maintenance requirements of a verity collection are dictated by the amount, frequency, and type of changes that occur in the records. You can run maintenance routines directly from either the cfcollecti...

  • Page 207

    Chapter 11: indexing and searching data 181 • delete (when used as a cfindex action) — deletes the specified key value, or comma-separated values, from the collection. • delete (when used on the administrator verity page or in cfcollection) — deletes the entire collection. • update — re-populates th...

  • Page 208

    182 developing web applications with coldfusion.

  • Page 209: Using The Application

    C h a p t e r 1 2 chapter 12 using the application framework the coldfusion web application framework is a powerful tool you can use to help structure your coldfusion applications. This section describes how to create and use the application.Cfm file, the application page that controls the applicati...

  • Page 210

    184 developing web applications with coldfusion understanding the web application framework a coldfusion application is a collection of application pages that work together. Applications can be as simple as a guest book or as sophisticated as a full internet commerce system with catalog pages, shopp...

  • Page 211

    Chapter 12: using the application framework 185 custom error handling using the cferror tag, you can display customized html pages when errors occur. This allows you to maintain a consistent look and feel within your application even when errors occur. It also allows you to optionally suppress the d...

  • Page 212

    186 developing web applications with coldfusion • development: the application is easier to develop and maintain because the application page files are well organized. • portability: the application can be more easily moved to another server or another part of a server without having to change any c...

  • Page 213

    Chapter 12: using the application framework 187 behavior with cfinclude only one application.Cfm file is ever processed for each coldfusion application page. The presence of an application.Cfm file is an implicit cfinclude. If it is present in the directory tree, there is no way not to include it. F...

  • Page 214

    188 developing web applications with coldfusion • default variables • custom error pages • data sources • default style settings • exclusive locks • other application-level constants note because unix is case sensitive, the application framework file must be spelled with an initial capital, applicat...

  • Page 215

    Chapter 12: using the application framework 189 4 clientmanagement="yes"> 2. Save the file as application.Cfm in the root directory of your application framework. Choosing a client variable storage method once you have enabled client state management, you then have to determine where you want to sto...

  • Page 216

    190 developing web applications with coldfusion cookie storage when you set clientstorage="cookie" the cookie that coldfusion creates has the application’s name. Storing client data in a cookie is scalable to large numbers of clients, but this storage mechanism has some limitations. Chief among them...

  • Page 217: Using Client Variables

    Chapter 12: using the application framework 191 creating a client variable to create a client variable and set the value of the parameter, use the cfset or cfparam tag., for example: once a client variable has been set in this manner, it is available for use within any application page in your appli...

  • Page 218

    192 developing web applications with coldfusion the client id (cfid)and the client security token (cftoken) between pages, either in hidden form fields or appended to urls. You accomplish this using the variable client.Urltoken or session.Urltoken. Note in coldfusion, client state management is expl...

  • Page 219

    Chapter 12: using the application framework 193 variable caching all client variable reads and writes are cached to help decrease the overhead of client state management operations. See administering coldfusion server for information on variables and server clustering. Exporting the client variable ...

  • Page 220: Using Session Variables

    194 developing web applications with coldfusion for information on setting time-outs for variables, see administering coldfusion server. Differentiating client, session, and application variables this table shows the relationships among client, session, and application variables.: note coldfusion do...

  • Page 221

    Chapter 12: using the application framework 195 period, coldfusion interprets this as the end of the session and clears any variables associated with that session. The default time-out for session variables is set to 20 minutes. In the variables page of the coldfusion administrator, you can change t...

  • Page 222: Using Application Variables

    196 developing web applications with coldfusion to be triggered on every page ---> using application variables application variables require an application name be associated with them and are always scoped within that application name. Unlike client and session variables, however, application varia...

  • Page 223

    Chapter 12: using the application framework 197 you can set the time-out period for application variables within a specific application (thereby overriding the default setting in the coldfusion administrator) by using the applicationtimeout attribute of the cfapplication tag. If no clients access th...

  • Page 224

    198 developing web applications with coldfusion example: application.Cfm the following example shows a complete application.Cfm file for the sample products application: clientmanagement="yes" clientstorage="mycompany"> template="requesterr.Cfm" mailto="admin@company.Com"> template="validationerr.Cf...

  • Page 225

    Chapter 12: using the application framework 199 • exclusive locks allow only one request to process the locked code. • read-only locks allow multiple requests to execute concurrently, provided that no exclusive locks are executing. Note unless you specify the type attribute, the default lock is excl...

  • Page 226: Cflock Examples

    200 developing web applications with coldfusion a deadlock is a state in which no request can execute the locked section of the page. Thus, all requests to the protected section of the page are blocked until there is a time- out. The following table shows one scenario that would cause a deadlock. On...

  • Page 227

    Chapter 12: using the application framework 201 the following sample code might be part of the application.Cfm file. Cfapplication defines scoping for a coldfusion applicationand enables or disables the storing of client and/or session variables. This tag is placed in the application.Cfm file for th...

  • Page 228

    202 developing web applications with coldfusion e-turtleneck is proud to say that we have sold #application.Number# turtlenecks to date. Tip in general, you should limit lock scopes. When locking variables, queries, and arrays (anything other than structures), you can copy to a local variable in the...

  • Page 229

    Chapter 12: using the application framework 203 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 forest green small medium large xlarge example of synchronizing ac...

  • Page 230

    204 developing web applications with coldfusion dynamic value for the name attribute to allow protection of a file with any given name. File=#filename# output=#texttoappend#> example of protecting coldfusion extensions this example illustrates how a custom tag wrapper can be built around cfxs that a...

  • Page 231: Sending and Receiving Email

    C h a p t e r 1 3 chapter 13 sending and receiving email you can add interactive email features to your coldfusion applications, providing complete two-way interface to mail servers via the cfmail tag and the cfpop tag. The boom in internet mail services makes coldfusion’s enhanced email capability ...

  • Page 232: Sending Email Messages

    206 developing web applications with coldfusion using coldfusion with mail servers adding email to your coldfusion applications lets you respond automatically to user requests. You can use email in your coldfusion applications in many different ways. These are just a few examples: • trigger email me...

  • Page 233: Samples Uses Of Cfmail

    Chapter 13: sending and receiving email 207 sending smtp mail with cfmail the cfmail tag provides support for sending smtp email from within coldfusion applications. The cfmail tag is similar to the cfoutput tag, except that cfmail outputs the generated text as smtp mail messages rather than to a pa...

  • Page 234

    208 developing web applications with coldfusion • use a query to send a customized mail message, such as a billing statement to a list of recipients that is dynamically populated from a database. • send a mime file attachment along with a mail message. Sending form-based email in the example below, ...

  • Page 235

    Chapter 13: sending and receiving email 209 the "productrequests" query, while the text above and below it serve as the header and footer (respectively) for the mail message. Sending email to multiple recipients in the following example, a query ("cfbetatesters") is run to retrieve a list of people ...

  • Page 236

    210 developing web applications with coldfusion company name: #company# contact: #firstname# #lastname# address: #address1# #address2# #city#, #state# #zip# phone: #phone# fax: #fax# home page: #homepageurl# please let us know if any of the above information has changed, or if we need to get in touc...

  • Page 237: Advanced Sending Options

    Chapter 13: sending and receiving email 211 advanced sending options the coldfusion implementation of smtp mail uses a spooled architecture. This means that when a cfmail tag is processed in an application page, the messages generated are not sent immediately. Instead, they are spooled to disk and p...

  • Page 238

    212 developing web applications with coldfusion use cfpop in applications when you want to receive email. Here are two instances where implementing pop mail makes sense: • if your site has generic mailboxes that are read by more than one person (sales@yourcompany.Com), it may be more efficient to co...

  • Page 239: Handling Pop Mail

    Chapter 13: sending and receiving email 213 handling pop mail this section gives an example of each of the following usages: • retrieving only message headers • retrieving a message body • retrieving attachments • deleting messages returning only message headers the header includes: • date • from • ...

  • Page 240

    214 developing web applications with coldfusion cc: #htmleditformat(sample.Cc)# replyto: #htmleditformat(sample.Replyto)# 3. Change the following line so that it refers to a valid pop mail server, as well as a valid user name and password: username=#username# password=#password# 4. Save the file as ...

  • Page 241

    Chapter 13: sending and receiving email 215 the message body: username=#username# password=#password# action="getall" name="sample"> messagenumber: #htmleditformat(sample.Messagenumber)# to: #htmleditformat(sample.To)# from: #htmleditformat(sample.From)# subject: #htmleditformat(sample.Subject)# dat...

  • Page 242

    216 developing web applications with coldfusion body, and all attachments: username=#username# password=#password# action="getall" attachmentpath="c:\attachdir" name="sample"> messagenumber: #htmleditformat(sample.Messagenumber)# to: #htmleditformat(sample.To)# from: #htmleditformat(sample.From)# su...

  • Page 243

    Chapter 13: sending and receiving email 217 returned will be 1,2,3,4. If messages 1 and 2 are then deleted within a single cfpop tag, messages 3 and 4 will be assigned message numbers 1 and 2, respectively. To delete messages: 1. Create a new file in studio. 2. Modify the file so that it appears as ...

  • Page 244

    218 developing web applications with coldfusion.

  • Page 245: Managing Files On The Server

    C h a p t e r 1 4 chapter 14 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. Contents • using cffile .........................................................................

  • Page 246: Using Cffile

    220 developing web applications with coldfusion using cffile the cffile tag gives you the ability to work with files on your server in a number of ways: • uploading files from a client to the web server using an html form. • moving, renaming, copying, or deleting files on the server. • reading, writ...

  • Page 247

    Chapter 14: managing files on the server 221 code review html forms can be designed in most browsers to give users the ability to upload files. Setting the html input tag type to "file" instructs the browser to prepare to read and transmit a file from the user’s system to your server. Setting the en...

  • Page 248

    222 developing web applications with coldfusion 3. Change the following line to point to an appropriate location on your server: destination="c:\inetpub\wwwroot\hr\" 4. Save the file as uploadfileaction.Cfm in myapps under the web root directory. 5. View uploadfileform.Cfm in your browser, enter val...

  • Page 249

    Chapter 14: managing files on the server 223 a file’s mime type is determined by the browser. Common types, like "image/gif" and "text/plain", are registered in your browser. Note not all browsers support mime type associations. Example: restricting file types this cffile specification will only sav...

  • Page 250

    224 developing web applications with coldfusion you enter permissions values in the mode attribute for each type of user: owner, group, other in that order. For example to assign read permissions for all: mode=444 to give a file or directory owner read/write/execute permissions and read only permiss...

  • Page 251

    Chapter 14: managing files on the server 225 the following file upload status variables are available after an upload. File upload variables parameter description attemptedserverfile initial name coldfusion used attempting to save a file, for example, myfile.Txt . See " resolving conflicting file na...

  • Page 252

    226 developing web applications with coldfusion use the file prefix to refer to these variables, for example, #cffile.Fileexisted#. 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 over...

  • Page 253

    Chapter 14: managing files on the server 227 reading, writing, and appending to a text file in addition to managing files on the server, you can use cffile to read, create, and modify text files. This gives you the ability to • create log files. • generate static html documents. • use text files to ...

  • Page 254

    228 developing web applications with coldfusion to create a form in which to enter data for a text file: 1. Open a new file in studio. 2. Modify the file so that it appears a follows: enter you name: enter you the name of the file: name="filename" size="25"> enter your message: 3. Save the file as w...

  • Page 255

    Chapter 14: managing files on the server 229 performing directory operations use the cfdirectory tag to return file information from a specified directory and to create, delete, and rename directories. As with cffile, coldfusion administrators can disable cfdirectory processing in the coldfusion adm...

  • Page 256

    230 developing web applications with coldfusion 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..

  • Page 257

    C h a p t e r 1 5 chapter 15 interacting with remote servers this chapter describes how coldfusion wraps the complexity of hypertext transfer protocol communications in a simplified tag syntax that allows you to easily extend your site’s offerings across the web. Contents • using cfhttp to interact ...

  • Page 258: Using The Cfhttp Get Method

    232 developing web applications with coldfusion using cfhttp to interact with the web the cfhttp tag is one of the more powerful tags in the cfml tag set. You can use one of two methods to interact with a remote server using the cfhttp tag: get or post. The get method is a one-way transaction in whi...

  • Page 259

    Chapter 15: interacting with remote servers 233 code review to get a web page and save it in a file: 1. Open a new file in studio. 2. Modify the file so that it appears as follows: method = "get" url="http://www.Allaire.Com/index.Cfm" path="c:\mine" file="allaireindex.Cfm"> 3. Change the path from c...

  • Page 260

    234 developing web applications with coldfusion method="get" url="http://maximus/downloads/quakestuff/q2_test.Zip" path="c:\quake2\install" file="quake2beta.Zip"> #cfhttp.Mimetype# 3. Change the url to point to a binary file you want to download. 4. Change the path to point to a path on your hard dr...

  • Page 261

    Chapter 15: interacting with remote servers 235 • when duplicate column heading names are encountered, coldfusion adds an underscore character to the duplicate column name to make it unique. For example, if two customerid columns are found, the second is renamed "customerid_". To create a query from...

  • Page 262: Using The Cfhttp Post Method

    236 developing web applications with coldfusion using the cfhttp post method use the post method to send cookie, form field, cgi, url, and file variables to a specified coldfusion page or cgi program. For post operations, you must use the cfhttpparam tag for each variable you want to post. Unlike th...

  • Page 263

    Chapter 15: interacting with remote servers 237 you have posted to me. Nameconflict="overwrite" filefield="myfile" action="upload" attributes="normal"> the url variable is: #url.Myurl# the cookie variable is: #cookie.Mycookie6# the cgi variable is: #cgi.Mycgi#. The formfield variable is: #form.Myfor...

  • Page 264

    238 developing web applications with coldfusion this example runs a cgi program, search.Exe , that searches the site and returns the hits on the value specified in value. Using secure sockets layer (ssl) with cfhttp when using secure sockets layer (ssl) to transmit secured transactions via cfhttp, y...

  • Page 265

    Chapter 15: interacting with remote servers 239 performing file operations with cfftp the cfftp tag allows you to perform tasks on remote servers via the file transfer protocol (ftp). Cfftp allows you to cache connections for batch file transfers. Note in order to use cfftp, make sure cfobject is en...

  • Page 266

    240 developing web applications with coldfusion text="date(format#lastmodified#)"> text="#isdirectory#"> 3. Change beta.Company.Com to the name of a server you have permission to ftp to. 4. Change betauser and monroe to a valid username and password. To establish an anonymous connection enter "anony...

  • Page 267: Wddx

    Chapter 15: interacting with remote servers 241 connection caching actions and attributes the following table shows which cfftp attributes are required for cfftp actions when employing connection caching. If connection caching is not used, the connection attributes username, password, and server mus...

  • Page 268: Wddx Components

    242 developing web applications with coldfusion the best source of information about wddx is http://www.Wddx.Org/ . This site, sponsored by allaire corporation, offers a free download of the wddx sdk and a number of resources, including a wddx faq and a developer forum. An overview of distributed da...

  • Page 269

    Chapter 15: interacting with remote servers 243 descriptors that allow the data to be manipulated on a target system between arbitrary application servers. Wddx is based on xml, which is a w3c recommendation. Other w3c efforts now in the works will have obvious application to wddx when they are comp...

  • Page 270: How Wddx Works

    244 developing web applications with coldfusion all of allaire’s wddx serializers (cfml, com, and js) have an attribute/property usetimezoneinfo that specifies whether time zone information should be used in the serialization process. The default value is true. In the cfml implementation, usetimezon...

  • Page 271

    Chapter 15: interacting with remote servers 245 see the cfml language reference for more information on javascript objects. Converting cfml data to a javascript object the following example demonstrates the transfer of a cfquery result set from a cfml template executing on the server to a javascript...

  • Page 272

    246 developing web applications with coldfusion q.Dump(true); note to see how cfwddx action="cfml2js" works, view the source to the page. Transferring data from browser to server this example serializes form field data, posts it to the server, deserializes it, and outputs the data. For simplicity, o...

  • Page 273

    Chapter 15: interacting with remote servers 247 name="personform"> personal information first name: last name: onclick="serializedata(personinfo, document.Personform.Wddxpacket)"> wddx packet display: /textarea> /textarea> server-side processing output="personinfo"> the submitted personal informatio...

  • Page 274

    248 developing web applications with coldfusion.

  • Page 275

    C h a p t e r 1 6 chapter 16 connecting to ldap directories support for the lightweight directory access protocol (ldap) api in cfml is part of allaire’s commitment to open networking standards. Contents • what is ldap? ...................................................................................

  • Page 276: What Is Ldap?

    250 developing web applications with coldfusion what is ldap? Ldap (lightweight directory access protocol) is a protocol that enables organizations to arrange directory information in a hierarchy. Note that in this case, "directory" refers to a collection of information something like a telephone di...

  • Page 277

    Chapter 16: connecting to ldap directories 251 ldap attributes following is a list of the common attributes: key terms following is a brief description of the ldap information structure. Entry the basic information object of ldap is the entry. An entry is composed of attributes, each of which has a ...

  • Page 278

    252 developing web applications with coldfusion attribute is "ou=support, o=allaire" the level below "support" is searched. You can optionally restrict a query to the level of the start entry or extend it to the entire subtree. Referral while not supported directly in the ldap2 standard, the ability...

  • Page 279: Viewing The Directory Schema

    Chapter 16: connecting to ldap directories 253 • build applications that incorporate data from directory queries in their processes. Working with ldap directories the cfldap tag allows you to work with ldap directories in the following ways. You can: • view the directory schema • search an ldap dire...

  • Page 280: Querying An Ldap Directory

    254 developing web applications with coldfusion attributes="dn, objectclasses, attributetypes" scope="base" filter="objectclass=*" start=#entrylist.Subschemasubentry# > dn=#dn# objectclasses: #objectclasses# attribute types: #attributetypes# 3. Change the server from testldap.Company.Com to a valid ...

  • Page 281

    Chapter 16: connecting to ldap directories 255 although sophisticated search criteria can be constructed from these filter operators, performance may degrade if the ldap server is slow to process the synchronous search routines supported by cfldap. The timeout and maxrows attributes can be used to c...

  • Page 282: Updating An Ldap Directory

    256 developing web applications with coldfusion query="orglist" height=250 width=620 hspace=20 vspace="6"> header="organization" width=380> header="state" width=100> header="phone ##" width=150> query="orglist" height=250 width=620 hspace=20 vspace="6"> header="organization" width=380> header="state...

  • Page 283

    Chapter 16: connecting to ldap directories 257 server="myserver" action="query" attributes="cn,mail,telephonenumber" scope="subtree" filter="ou=human resources" sort="cn asc" start="o=airius.Com"> human resources directory for arius server="myserver" action="query" attributes="cn,mail,telephonenumbe...

  • Page 284

    258 developing web applications with coldfusion action="modify" username="uid=kvaughan, ou=people, o=airius.Com" password="bribery" attributes="uniquemember=uid=scarter,,ou=people,,o=airius.Com, uid=tmorris,,ou=people,,o=airius.Com, id=gfarmer,,ou=people,,o=airius.Com" dn="cn=accounting managers, ou...

  • Page 285

    Chapter 16: connecting to ldap directories 259 password="testldap" action="modifydn" attributes=#new_dn# dn=#rename_dn#> #phonetag# & #phone#> server="myserver" username="cn=directory manager, o=ace industry, c=us" password="testldap" action="modify" attributes=#update_attrs# dn=#dn#> person,organiz...

  • Page 286

    260 developing web applications with coldfusion server="myserver" action="query" attributes="dn,cn, sn" scope="subtree" sort="sn asc" filter="(&(sn=*ens*)(cn>=k))" start="o=ace industry, c=us" maxrows=50 timeout=30> server="myserver" action="query" attributes="dn,cn, sn" scope="subtree" sort="sn asc...

  • Page 287

    Chapter 16: connecting to ldap directories 261 4. Change the uid to a valid user id. 5. Save the page as ldapchangeattr.Cfm and view it in your browser. To delete an entry: 1. Open a new file in studio. 2. Modify the file so that it appears as follows: server="myserver" username="cn=directory manage...

  • Page 288

    262 developing web applications with coldfusion.

  • Page 289: Application Security

    C h a p t e r 1 7 chapter 17 application security coldfusion 4.5 supports several levels of advanced security. This chapter teaches you how to deploy user security, which is controlled by the coldfusion developer and offers runtime security for coldfusion applications. It also describes the remote d...

  • Page 290

    264 developing web applications with coldfusion coldfusion security features coldfusion server professional and enterprise editions include advanced security features that provide scalable, granular security for building and deploying your coldfusion applications: • application development — system ...

  • Page 291: Overview of User Security

    Chapter 17: application security 265 overview of user security user security authenticates users when they log into a coldfusion application, and then assigns privileges based on group membership or other criteria that you determine. For example, suppose you’ve used coldfusion to build and host your...

  • Page 292: Using The Cfauthenticate Tag

    266 developing web applications with coldfusion • use the isauthenticated function to check if the current user is authenticated. • use the isauthorized function to check if the user is authorized to access resources. This function lets developers offer or deny access to protected resources based on...

  • Page 293

    Chapter 17: application security 267 example username=#userid# password=#pwd#> if the user has not already been defined in the system, coldfusion throws a security exception. You can either reject access to the resource or re-route the user to a login page. For example, you can display a login form ...

  • Page 294

    268 developing web applications with coldfusion isauthorized returns true if the user is authorized to perform the specified action on the specified coldfusion resource. Isauthorized takes three parameters: isauthorized(resourcetype, resourcename, [resourceaction]) for example, to check whether the ...

  • Page 295

    Chapter 17: application security 269 a new user. Username=#user# password=#pwd#> authentication error username=#user# password=#pwd#> you might place code here to define the user to the security context. ---> #cfcatch.Message# using the cfimpersonate tag cfimpersonate gives coldfusion developers a w...

  • Page 296

    270 developing web applications with coldfusion • username — the username of the user to impersonate. • password — the password of the user to impersonate. • type — indicates the type of impersonation to implement, application-level or operating-system-level. Application-level impersonation lets you...

  • Page 297

    Chapter 17: application security 271 if a user passes the authentication test, coldfusion passes a cookie to carry the user’s authentication state to subsequent application pages governed by this application.Cfm page. • next, only authenticated users are able to access the requested application page...

  • Page 298

    272 developing web applications with coldfusion checking for authentication and authorization inside application pages, developers 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....

  • Page 299

    Chapter 17: application security 273 example: orders.Cfm ... Insert into orders (customer, orderid) values (#customer#, #orderid#) authorization succeeded. Order information added: #customer# - #orderid# to update order information."> select * from orders authorization succeeded. Order information f...

  • Page 300

    274 developing web applications with coldfusion.

  • Page 301: Building Custom Cfapi Tags

    C h a p t e r 1 8 chapter 18 building custom cfapi tags for some applications, building executables to run with coldfusion is the best solution. Perhaps the application requirements go beyond what is currently feasible in cfml. Or perhaps application performance can be improved for certain types of ...

  • Page 302: What Are Cfx Tags?

    276 developing web applications with coldfusion what are cfx tags? Cfx tags are custom tags written against the coldfusion application programming interface. Generally, you create a cfx if you want to do something that’s not possible in cfml, or if you want to improve performance of a task in cfml t...

  • Page 303: Compiling C++ Cfxs

    Chapter 18: building custom cfapi tags 277 using the tag wizard to create cfxs in c++ on windows nt, you can get a start in developing cfxs by using the coldfusion tag wizard. To use the wizard, the cfxapi tag development kit must be installed (it is by default), and the setup routine must detect mi...

  • Page 304

    278 developing web applications with coldfusion on unix solaris you can debug custom tags on unix using the dbx debugger. You should shut down coldfusion using the stop script. Set the environment variables, including ld_library_path and cfhome as they are set in the start script. You should then be...

  • Page 305: Writing A Java Cfx

    Chapter 18: building custom cfapi tags 279 • helloworldgraphic - generates a "hello world!" graphic in jpeg format. Demonstrates how to dynamically create and return graphics from a java cfx. Setting up your development environment to develop cfxs in java you can use a wide range of java development...

  • Page 306

    280 developing web applications with coldfusion to create a java cfx: 1. Create a new source file in your editor. 2. Enter the code, for example, the code below illustrates the creation of a very simple java cfx named simplejavacfx that writes a text string back to the calling page: import com.Allai...

  • Page 307

    Chapter 18: building custom cfapi tags 281 request object passed to the processrequest method of the customtag interface. Provides methods for retrieving attributes passed to the tag, including queries, and reading global tag settings. Response object passed to the processrequest method of the custo...

  • Page 308

    282 developing web applications with coldfusion query object provides an interface for working with coldfusion queries, including methods for retrieving name, row count, and column names as well as methods for getting and setting data elements.. For detailed reference information on each of these in...

  • Page 309

    Chapter 18: building custom cfapi tags 283 automatic class reloading you can determine how the server treats changed java cfx class files by using the reload (?) . The allowable values for the reload attribute are as follows:. The default value is reload=auto . This is appropriate for most applicati...

  • Page 310: Zipbrowser Example

    284 developing web applications with coldfusion your customtag object. If you wish to store data and/or objects that are accessible to all instances of your customtag you should use static data members. Calling the cfx from a coldfusion template you call java cfxs from within coldfusion templates by...

  • Page 311

    Chapter 18: building custom cfapi tags 285 the java implementation of zipbrowser is as follows: import com.Allaire.Cfx.* ; import java.Util.Hashtable ; import java.Io.Fileinputstream ; import java.Util.Zip.* ; public class zipbrowser implements customtag { public void processrequest( request request...

  • Page 312

    286 developing web applications with coldfusion approaches to debugging java cfxs java cfxs are not standalone applications that run in their own process like typical java applications. Rather, they are created and invoked from an existing process — coldfusion server. This makes debugging java cfxs ...

  • Page 313

    Chapter 18: building custom cfapi tags 287 • debugresponse — an implementation of the response interface that enables you to print the results of a request once it has completed. • debugquery — an implementation of the query interface that enables you to initialize a query with a name, columns, and ...

  • Page 314

    288 developing web applications with coldfusion debugquery query = new debugquery( "employees", columns, data ) ; // create tag, process debug request, and print results outputquery tag = new outputquery() ; debugrequest request = new debugrequest( attributes, query ) ; debugresponse response = new ...

  • Page 315: Implementing C++ Cfx Tags

    Chapter 18: building custom cfapi tags 289 debugquery // initialize a query with name and columns public debugquery( string name, string[] columns ) throws illegalargumentexception ; // initialize a query with name, columns, and data public debugquery( string name, string[] columns, string[][] data ...

  • Page 316

    290 developing web applications with coldfusion to register a c++ cfx: 1. In the cf administrator, open the extensions > cfx tags page. 2. Enter cfx_mynewtag in the tag name and, optionally, a description. 3. Select the type of tag (either c++ or java). 4. Click add to open the new cfx tag page. 5. ...

  • Page 317

    Chapter 18: building custom cfapi tags 291 distribution if you are distributing a custom tag, you may want to automatically register the custom tag during the setup process by writing the registration entries directly into the registry. The location, key, and value names to write are as follows: you...

  • Page 318

    292 developing web applications with coldfusion to import a c++ custom tag: 1. Export the custom tag’s registry entry by using the regedit utility. This creates a file similar to the following: regedit4 [hkey_local_machine\software\allaire\coldfusion\currentversion\ customtags\cfx_test] "librarypath...

  • Page 319: C++ Cfx Reference

    Chapter 18: building custom cfapi tags 293 c++ cfx reference below is a listing of cfxapi classes and members. Individual members are described fully in the following sections. Class members ccfxexception class ccfxexception::geterror ccfxexception::getdiagnostics ccfxquery class ccfxquery::addrow c...

  • Page 320: Ccfxexception Class

    294 developing web applications with coldfusion ccfxexception class abstract class that represents an exception thrown during the processing of a coldfusion extension (cfx) procedure. Exceptions of this type can be thrown by ccfxrequest class , ccfxquery class , and ccfxstringset class . Your coldfu...

  • Page 321: Ccfxquery Class

    Chapter 18: building custom cfapi tags 295 prequest->rethrowexception( e ) ; } // catch all other exceptions and throw them as // cold fusion exceptions (do not remove! -- // this prevents the server from crashing in // case of an unexpected exception) catch( ... ) { prequest->throwexception( "error...

  • Page 322

    296 developing web applications with coldfusion ccfxquery::addrow int ccfxquery::addrow(void) add a new row to the query. You should call this function each time you want to append a row to the query. Returns the index of the row that was appended to the query. Example the following example demonstr...

  • Page 323

    Chapter 18: building custom cfapi tags 297 ccfxquery::getdata lpcstr ccfxquery::getdata(int irow , int icolumn ) retrieves a data element from a row and column of the query. Row and column indexes begin with 1. You can determine the number of rows in the query by calling ccfxquery::getrowcount . You...

  • Page 324

    298 developing web applications with coldfusion retrieves the number of rows in the query. Returns the number of rows contained in the query. Example the following example retrieves the number of rows in a query and writes it back to the user: ccfxquery* pquery = prequest->getquery() ; char buffoutp...

  • Page 325: Ccfxrequest Class

    Chapter 18: building custom cfapi tags 299 ccfxquery::setquerystring this is a deprecated function and should not be used. Ccfxquery::settotaltime this is a deprecated function and should not be used. Ccfxrequest class abstract class that represents a request made to a coldfusion extension (cfx). An...

  • Page 326

    300 developing web applications with coldfusion virtual void writedebug( lpcstr lpszoutput ) ccfxrequest::writedebug writes text output into the debug stream. Virtual ccfxstringset* createstringset() ccfxrequest::createstringset allocates and returns a new ccfxstringset instance. Virtual void throwe...

  • Page 327

    Chapter 18: building custom cfapi tags 301 // create a query that contains these columns ccfxquery* pquery = prequest->addquery( "people", pcolumns ) ; // add data to the query int irow ; irow = pquery->addrow() ; pquery->setdata( irow, ifirstname, "john" ) ; pquery->setdata( irow, ilastname, "smith...

  • Page 328

    302 developing web applications with coldfusion ccfxrequest::debug bool ccfxrequest::debug(void) checks whether the tag contains the debug attribute. You should use this function to determine whether or not you need to write debug information for this request. (see the ccfxrequest::writedebug tag fo...

  • Page 329

    Chapter 18: building custom cfapi tags 303 you are not responsible for freeing the memory allocated for the returned string set (it will be freed automatically by coldfusion after the request is completed). Example the following example retrieves the list of attributes and then iterates over the lis...

  • Page 330

    304 developing web applications with coldfusion (created using the cfquery tag or another custom tag). The query attribute is optional and should only be used by tags that need to process an existing data set. Returns an object of the ccfxquery class that represents the query that was passed to the ...

  • Page 331

    Chapter 18: building custom cfapi tags 305 your extension code and then either re-throw them (if they are of the ccfxexception class ) or create and throw a new exception pointer using ccfxrequest::throwexception . E an existing ccfxexception that has been caught. Example the following code demonstr...

  • Page 332

    306 developing web applications with coldfusion void processtagrequest( ccfxrequest* prequest ) { try { mytagdata tagdata ; prequest->setcustomdata( (lpvoid)&tagdata ) ; ... Remainder of procedure ... } ccfxrequest::setvariable void ccfxrequest::setvariable(lpcstr lpszname, lpcstr lpszvalue) sets a ...

  • Page 333

    Chapter 18: building custom cfapi tags 307 ccfxrequest::rethrowexception to provide protection against resource leaks in extension code. Lpszerror short identifier for error. Lpszdiagnostics error diagnostic information. Example the following example throws an exception indicating that an unexpected...

  • Page 334: Ccfxstringset Class

    308 developing web applications with coldfusion example the following example checks to see whether the debug attribute is present, and if it is, it writes a brief debug message: if ( prequest->debug() ) { prequest->writedebug( "top secret debug info" ) ; } ccfxstringset class abstract class that re...

  • Page 335

    Chapter 18: building custom cfapi tags 309 ccfxstringset::getcount int ccfxstringset::getcount(void) gets the number of strings contained in the string set. This value can be used along with ccfxstringset::getstring to iterate over the strings in the set (when iterating, remember that the index valu...

  • Page 336

    310 developing web applications with coldfusion ccfxstringset::getstring lpcstr ccfxstringset::getstring(int iindex) retrieves the string located at the passed index (note that index values are 1-based). Returns the string located at the passed index. Iindex index of string to retrieve. Example the ...

  • Page 337: Java Cfx Reference

    Chapter 18: building custom cfapi tags 311 java cfx reference contents • interface customtag • interface query • interface request • interface response interface customtag public abstract interface customtag interface for implementing custom tags. Classes that implement this interface can be specifi...

  • Page 338: Interface Query

    312 developing web applications with coldfusion response — interface for generating response to request (output, variables, queries, etc.) throws: exception — if an unexpected error occurs while processing the request. Interface query public abstract interface query interface to a query used or crea...

  • Page 339

    Chapter 18: building custom cfapi tags 313 returns: the name of the query. Getrowcount public int getrowcount() retrieves the number of rows in the query. The following example retrieves the number of rows in a query and writes it back to the user: query query = request.Getquery() ; int rows = query...

  • Page 340

    314 developing web applications with coldfusion retrieves a list of the column names contained in the query. The following example retrieves the array of columns and then iterates over the list, writing each column name back to the user: // get the list of columns from the query string[] columns = q...

  • Page 341

    Chapter 18: building custom cfapi tags 315 throws: indexoutofboundsexception - if an invalid index is passed to the method. See also: setdata, addrow addrow public int addrow() adds a new row to the query. Call this method each time you want to append a row to the query. The following example demons...

  • Page 342: Interface Request

    316 developing web applications with coldfusion int icity = 1, istate = 2, izip = 3 ; // first row int irow = query.Addrow() ; query.Setdata( irow, icity, "minneapolis" ) ; query.Setdata( irow, istate, "mn" ) ; query.Setdata( irow, izip, "55345" ) ; // second row irow = query.Addrow() ; query.Setdat...

  • Page 343

    Chapter 18: building custom cfapi tags 317 method detail attributeexists public boolean attributeexists(string name) checks to see whether the attribute was passed to this tag. The following example checks to see if the user passed an attribute named destination to the tag and throws an exception if...

  • Page 344

    318 developing web applications with coldfusion getattribute public string getattribute(string name) retrieves the value of the passed attribute. Returns an empty string if the attribute does not exist (use attributeexists to test whether an attribute was passed to the tag). Use getattribute(string,...

  • Page 345

    Chapter 18: building custom cfapi tags 319 throws: numberformatexception — if the attribute is not a valid number. See also: attributeexists, getattributelist, getintattribute(string,int) getattributelist public string[] getattributelist() retrieves a list of all attributes passed to the tag. To ret...

  • Page 346

    320 developing web applications with coldfusion "order for this tag to work correctly." ) ; } returns: the query that was passed to the tag. If no query was passed to the tag then null is returned. Getsetting public string getsetting(string name) retrieves the value of a global custom tag setting. C...

  • Page 347: Interface Response

    Chapter 18: building custom cfapi tags 321 returns: returns true if the tag contains the debug attribute otherwise returns false. See also: response.Writedebug interface response public abstract interface response interface to response generated from a customtag. This interface includes methods for ...

  • Page 348

    322 developing web applications with coldfusion sets a variable in the calling template. If the variable name specified already exists in the template then its value is replaced. If it does not already exist then a new variable is created. For example, this code sets the value of a variable named ’m...

  • Page 349

    Chapter 18: building custom cfapi tags 323 query.Setdata( irow, ifirstname, "john" ) ; query.Setdata( irow, ilastname, "smith" ) ; irow = query.Addrow() ; query.Setdata( irow, ifirstname, "jane" ) ; query.Setdata( irow, ilastname, "doe" ) ; parameters: name — the name of the query to add to the temp...

  • Page 350

    324 developing web applications with coldfusion.

  • Page 351: Using Cfobject To Invoke

    C h a p t e r 1 9 chapter 19 using cfobject to invoke component objects the cfobject tag is used to invoke objects created by component technologies. This includes com/dcom, corba, java, and ejb objects. Contents • component object overview...............................................................

  • Page 352: Component Object Overview

    326 developing web applications with coldfusion component object overview this section gives you some basic information on objects supported in coldfusion and provides resources for further inquiry. About com com (component object model) is a specification and a set of services defined by microsoft ...

  • Page 353: Invoking Component Objects

    Chapter 19: using cfobject to invoke component objects 327 invoking component objects the cfobject tag is used to create an instance of the object and other coldfusion tags, such as cfset and cfoutput, are used to invoke properties (attributes), and methods (operations) on the object. An object crea...

  • Page 354

    328 developing web applications with coldfusion calling nested objects the current release of coldfusion does not support nested (scoped) object calls. For example, if an object method returns another object and you would like to invoke a property/method on that object, the following is required: (t...

  • Page 355

    Chapter 19: using cfobject to invoke component objects 329 deployed with their own setup programs that register objects automatically, while others may require manual registration. Inproc object servers (*.Dll, *.Ocx) can be registered manually by using the "regsvr32.Exe" utility using the following...

  • Page 356

    330 developing web applications with coldfusion 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. If you view the typeinfo, you’ll see the object’s method...

  • Page 357

    Chapter 19: using cfobject to invoke component objects 331 creating and using com objects in the following example, an smtp mail handling component is created using cfobject. Name=mailer class=smtp.Mailer> the component needs to be created by coldfusion before any methods in the component can be inv...

  • Page 358: Getting Started With Corba

    332 developing web applications with coldfusion • remote — this is also an out-of-process server object (also typically an exe) that is running remotely on the network. Using remote implies using the server attribute to identify where the object resides. Setting properties and invoking methods the f...

  • Page 359: Calling A Corba Object

    Chapter 19: using cfobject to invoke component objects 333 • if visibroker is already installed on the server, the log directory is the directory pointed to by the vbroker_adm environment variable. • if this is a new visibroker installation, the log directory is created on the root of the drive from...

  • Page 360

    334 developing web applications with coldfusion { 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); }; the applicable coldfusion code exce...

  • Page 361: Calling Java Objects

    Chapter 19: using cfobject to invoke component objects 335 calling java objects the cfobject tag can call any java class that’s available on the class path specified in the coldfusion administrator. For example: although this loads the class, it doesn’t create an instance object. Static methods and ...

  • Page 362

    336 developing web applications with coldfusion.

  • Page 363: Extending Coldfusion Pages

    C h a p t e r 2 0 chapter 20 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. This chapter desc...

  • Page 364: About Cfscript

    338 developing web applications with coldfusion about cfscript the coldfusion server-side scripting language, cfscript, offers coldfusion functionality in script syntax. This javascript-like language offers the same control flow, but without tags. Cfscript regions are bounded by and . You can use co...

  • Page 365: The Cfscript Language

    Chapter 20: extending coldfusion pages with cfml scripting 339 • for • break • continue • for-in • switch-case for more information the following javascript references may be useful in understanding the concepts and control flow statements in cfscript: • netscape’s javascript guide • netscape’s java...

  • Page 366

    340 developing web applications with coldfusion for loop: for (init-expr ; test-expr ; final-expr) statement ; note that init-expr and final-expr can be one of the following: • a single assignment expression, for example, x=5 or loop=loop+1 • any coldfusion expression, for example, setvariable("a",a...

  • Page 367

    Chapter 20: extending coldfusion pages with cfml scripting 341 do-while loop: do statement while (expr) ; // complete do-while loop on a single line a = arraynew(1); do {a[loop1] = loop1 + 5; loop1 = loop1 + 1;} while (loop1 lt 10); // multiline do-while loop a = arraynew(1); do { a[loop1] = loop1 +...

  • Page 368

    342 developing web applications with coldfusion continue: skip to next loop iteration for ( loop=1; loop lt 10; loop = loop+1) { if(a[loop]=0) continue; a[loop]=1; } break: break out of the current switch statement or loop for( ; ; ) { indx=indx+1; if(find("key",strings[indx],1)) break; } expression...

  • Page 369

    Chapter 20: extending coldfusion pages with cfml scripting 343 • cfscript is case-insensitive. • all statements end in a semi-colon, and line breaks in your code are insignificant. • in cfscript, assignments are statements, not expressions. • some implicit objects are not available, such as window a...

  • Page 370

    344 developing web applications with coldfusion //‘testres' is a column in the "employees" query if( testres eq 1 ) result="positive"; else result="negative"; test for #name# is #result#..

  • Page 371: Accessing The Windows Nt

    C h a p t e r 2 1 chapter 21 accessing the windows nt registry the cfregistry tag gives you programmatic access to the windows registry. Contents • overview of registry access in coldfusion ................................................. 346 • getting registry values .................................

  • Page 372: Getting Registry Values

    346 developing web applications with coldfusion overview of registry access in coldfusion coldfusion includes the cfregistry tag, which allows you to get, set, and delete registry values. The registry is a database that windows uses to maintain hierarchical information about users, hardware, and sof...

  • Page 373: Setting Registry Values

    Chapter 21: accessing the windows nt registry 347 branch="hkey_local_machine\software\microsoft\java vm" type="any" name="regquery"> 2. Access the record set (this example uses the cftable tag): cfregistry action="getall" branch="hkey_local_machine\software\microsoft\java vm" type="any" name="regque...

  • Page 374: Deleting Registry Values

    348 developing web applications with coldfusion if the specified value does not exist, coldfusion creates it. If the value already exists, coldfusion updates the value data. To create a registry key: call the cfregistry tag with the set action, specifying the branch, the entry to set, specifying key...

  • Page 375: Index

    Index a accessing collections 181 action pages 34 active server pages 242 advanced security implementing 265 allaire xxiv contacting xxiv headquarters xxiv sales xxv technical support xxiv ancestor tags 77 and operator 23, 40 application framework, web custom error pages 93 application framwork 184 ...

  • Page 376

    350 developing web applications with coldfusion cfauthenticate tag 185, 266 example 270 syntax 266 using setcookie 266 cfcatch tag 95 cfcontent tag 239 cfdirectory tag 239 cfelse tag 42, 53 cfelseif tag 53 cferror page 93 cferror tag 185 cfexit tag 84, 185 cffile tag 220, 237 cfform tag 124 cfftp ta...

  • Page 377

    Index 351 descendants 77 distributing 291 downloading 73 encrypting 86 executing 82 execution modes 83 installing 85 local 85 location of 73 managing 85 naming 73 nesting 77 parent 77 restricting access to 86 shared 85 using existing 73 d data converting to javascript object 245 exchanging 241 passi...

  • Page 378

    352 developing web applications with coldfusion cfform 124 form fields required 68 form variables in queries 35 naming 34 processing 34 referring to 34 testing 36 formatting data items 38 query results 38 forms 30 checkboxes 47 creating 55, 61 creating with cfform 124 deleting data 66 designing 34 d...

  • Page 379

    Index 353 relational 173 score 177 searching 171 sql 23 or operator 23 order by clause 22 p parameters dynamic sql 53 parent tags 77 pattern matching 39 perl 242 pop 7 populating arrays 108 arrayset 108 cfloop 108 from queries 110 nested loops 109 populating collections 157 post method 232, 236 poun...

  • Page 380

    354 developing web applications with coldfusion application-level 184 shared data modifying 199 single quotes 21, 51 in form field values 49 using 21 slider bar controls 142 smtp 206 special characters searching 170 sql 2, 20, 21 clauses 22 dynamic 53, 56 dynamic parameters 53 insert statement 61 no...