background image

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 a user’s authorization level, which is determined by 
already-established security contexts.

Use the CFIMPERSONATE tag wherever you want to provide a greater level of 
access than is otherwise assigned to a particular user.

Read the section “Example of User Authentication and Authorization” on page 270 to 
see code examples that show how these tags functions work in ColdFusion 
applications.

To learn about syntax and usage for the CFAUTHENTICATE and CFIMPERSONATE 
tags, and the IsAuthenticated and IsAuthorized functions, See the CFML Language 
Reference
.

Encrypting application pages

For an added measure of security, you can encrypt strings in your applications using 
the Encrypt and Decrypt functions. See the CFML Language Reference for descriptions 
of these functions.

Using the CFAUTHENTICATE tag

The CFAUTHENTICATE tag has several required attributes:

SECURITYCONTEXT— Describes which security context to use for 
authentication and authorization. This name matches the security context as 
defined in the Advanced Security page of the ColdFusion Administrator.

USERNAME — The username required to access the protected resources.

PASSWORD — The password required to access the protected resources.

The USERNAME and PASSWORD are usually variables passed in a cookie from form 
fields on a secure login page for the current session.

In addition, CFAUTHENTICATE has two optional attributes:

SETCOOKIE — Indicates whether ColdFusion sets a cookie to contain 
authentication information. This cookie is encrypted and includes the user 
name, security context, browser remote address, and the http user agent. 
Default is Yes.

THROWONFAILURE — Indicates whether ColdFusion throws an exception of 
type Security if authentication fails. Default is Yes.

Summary of Contents for COLDFUSION 4.5-DEVELOPING WEB

Page 1: ...Allaire Corporation Developing Web Applications with ColdFusion ColdFusion 4 5...

Page 2: ...ication may be reproduced stored in a retrieval system or transmitted in any form or by any means electronic mechanical recording or otherwise without the prior written permission of Allaire Corporati...

Page 3: ...s xxi About ColdFusion Documentation xxii Documentation updates xxii ColdFusion manuals xxii ColdFusion Server online documentation xxiii Printing ColdFusion documentation xxiii Documentation conventi...

Page 4: ...Data 20 The CFQUERY Tag 20 Writing SQL 21 Basic SQL Syntax elements 22 SQL Notes and Considerations 23 Building Queries 24 Query Notes and Considerations 25 Outputting Query Data 25 Query Output Note...

Page 5: ...Insert Data 61 Updating Data 62 Creating an Update Form 63 Creating an Action Page to Update Data 65 Deleting Data 66 Requiring Users to Enter Values in Form Fields 67 Validating the Data That Users...

Page 6: ...Creating an error application page 93 Overview of Exception Handling in ColdFusion 94 Types of recoverable exceptions supported 95 Exception Information in CFCATCH 97 Tag context information 98 Datab...

Page 7: ...ORM Controls 126 Input Validation with JavaScript 127 JavaScript objects passed to the validation routine 127 Handling failed validation 127 Building Tree Controls with CFTREE 129 Grouping output from...

Page 8: ...DAP Query Results 163 Indexing CFPOP Query Results 164 Using Query Expressions 165 Simple query expressions 166 Explicit query expressions 166 Expression syntax 166 Special characters 168 Composing Se...

Page 9: ...ion variable time outs 196 Tips for Using Session and Application Variables 197 Getting a list of application and session variables 197 Default Variables and Constants 197 Using CFLOCK for Exclusive L...

Page 10: ...ry from a Text File 234 Using the CFHTTP Post Method 236 Using Secure Sockets Layer SSL with CFHTTP 238 Performing File Operations with CFFTP 239 Caching connections across multiple pages 240 Connecti...

Page 11: ...mple C CFXs 276 Setting Up Your C Development Environment 276 Using the Tag Wizard to create CFXs in C 277 Compiling C CFXs 277 Debugging C CFXs 277 Before You Begin Developing CFX Tags in Java 278 Sa...

Page 12: ...ta 303 CCFXRequest GetQuery 303 CCFXRequest GetSetting 304 CCFXRequest ReThrowException 304 CCFXRequest SetCustomData 305 CCFXRequest SetVariable 306 CCFXRequest ThrowException 306 CCFXRequest Write 3...

Page 13: ...claring structures and sequences 333 Exception handling 334 Calling Java Objects 335 Calling EJBs 335 Exception handling 335 Chapter 20 Extending ColdFusion Pages with CFML Scripting 337 About CFScrip...

Page 14: ...xiv Developing Web Applications with ColdFusion...

Page 15: ...pabilities Because of the power and flexibility of ColdFusion you can create many different types of Web applications of varying complexity As you become more familiar with the material presented in t...

Page 16: ...lease we re launching a new edition of ColdFusion Server for Linux so you can take advantage of the reliability and performance of the hottest new Internet server operating system While optimizing the...

Page 17: ...6 or 7 patch 103582 1B or higher 128 MB RAM 256 MB recommended for clustering 200 MB hard disk space ColdFusion Server 4 5 Enterprise Edition for Linux Red Hat Linux 6 0 or 6 1 Intel Pentium or above...

Page 18: ...onfigurations with FTP or ColdFusion Remote Development Services RDS Use VBScript or Java Script to fully script deployment of projects with granular control over how files uploaded Setup deployment s...

Page 19: ...sters on Linux and Solaris using the Apache Web Server Enterprise Edition only Automatic Shared Variable Locking Lock user and session variable reads automatically at the server level to prevent desta...

Page 20: ...ter Large Binary Object CLOB support to encoded binary objects transmit them via XML and store them in databases or files SQL Bind Parameters Improve query performance security and flexibility with ex...

Page 21: ...omer support in developer education technical support and professional services Our Web site is designed to give you quick access to the entire range of online resources Allaire Developer Services Res...

Page 22: ...Allaire support options and Allaire products and services For ColdFusion Studio users you can access the documentation update page by clicking on the Help resource tab and browsing your way through t...

Page 23: ...t have a product CD you can download ColdFusion documentation from the Allaire web site by visiting http www allaire com developer and clicking the Documentation link ColdFusion Studio online document...

Page 24: ...est ways to solve particular programming problems is to tap into the vast expertise of the ColdFusion developer community on the Allaire Forums Other ColdFusion developers on the forum can help you fi...

Page 25: ...outside U S and Canada For complete details about Allaire Product Support options please refer to the Allaire Support pages on the Allaire web site http www allaire com support Postings to the ColdFu...

Page 26: ...xxvi Developing Web Applications with ColdFusion...

Page 27: ...reating static Web pages with HTML and creating dynamic applications with ColdFusion It also describes what ColdFusion is and how it works Contents A Quick Web Overview 2 What You Should Already Know...

Page 28: ...day business of your organization What You Should Already Know Before you begin using ColdFusion to create your Web applications you should be familiar with the following topics HTML You ll find that...

Page 29: ...contain ColdFusion Markup Language Editions of ColdFusion There are three editions of ColdFusion Enterprise Professional and Express Using ColdFusion Enterprise and Professional editions and ColdFusio...

Page 30: ...owing features A multi threaded service architecture that scales across processors Database connection pooling to optimize database performance Just in time page compilation and caching to accelerate...

Page 31: ...y visit the Security Zone at http www allaire com developer securityzone For a complete feature list and more detailed information refer to the ColdFusion product pages http www allaire com coldfusion...

Page 32: ...age The default file extension used for ColdFusion application pages is CFM CFML CFML is a tag based server scripting language that encapsulates complex processes such as connecting to databases and L...

Page 33: ...processed on the server at runtime each time they are requested by a browser A page request happens when you click on a Web site link to open a Web page in your browser When you request a ColdFusion a...

Page 34: ...8 Developing Web Applications with ColdFusion...

Page 35: ...ColdFusion development process as you create a ColdFusion application page save it and view it in a browser Contents The Development Process 10 Writing Code 10 Saving Application Pages 11 Viewing Appl...

Page 36: ...should install ColdFusion Studio From a coding perspective the major difference between a static HTML page and a ColdFusion application page is that ColdFusion pages contain ColdFusion Markup Language...

Page 37: ...alldept cfm in myapps under the Web root directory For example the directory path on your machine may be c inetpub wwwroot myapps on Windows NT or mywebserverdocroot myapps on UNIX Viewing Application...

Page 38: ...ment TITLE HEAD BODY STRONG Call Department STRONG Set all variables CFSET Department Sales CFOUTPUT I d like to talk to someone in Department Display results CFOUTPUT BODY HTML HTML HEAD TITLE Call D...

Page 39: ...t how long they exist and where their values are stored These considerations are referred to as a variable s scope You will learn more about scope as needed throughout this book For example you would...

Page 40: ...4 Display results CFOUTPUT 4 I d like to talk to someone in Department in city who earns at least Salary CFOUTPUT BODY HTML 3 Save the file 4 View the page in your Web browser by entering the followi...

Page 41: ...ldFusion Administrator to set up a data source and enable debugging use the CFQUERY tag to query a data source and use the CFOUTPUT tag to output the query results to a Web page Contents Publishing Dy...

Page 42: ...u will build a query to retrieve data from company mdb an Access database In subsequent chapters in this book you will insert and update data in this database To build a query you will need to use Col...

Page 43: ...que identity among the tables in a relational database Once a column has been defined to contain a specific type of information the data must be entered in that column in a consistent way This is acco...

Page 44: ...lication Applications that use ODBC must have an ODBC driver installed and configured for each data source On Windows you can check your system s installed drivers by opening the ODBC Data Source Mana...

Page 45: ...ion Administrator On Windows Select Start Programs ColdFusion Server ColdFusion Administrator On UNIX enter the URL hostname CFIDE administrator in your browser The Administrator prompts you for a pas...

Page 46: ...e you should use a consistent capitalization scheme A data source must exist in the ColdFusion Administrator before you use it on an application page to retrieve data Retrieving Data You can query dat...

Page 47: ...nd attribute values with double quotes Place SQL statements inside the CFQUERY block to tell the database what to process during the query When referencing text literals in SQL use single quotes For e...

Page 48: ...ef descriptions of the main SQL command elements Statements These keywords identify commonly used SQL commands Statement clauses These keywords are used to refine SQL statements Basic SQL Statements K...

Page 49: ...query Some DBMS vendors use non standard SQL syntax known as a dialect in their products ColdFusion does not validate the SQL in a CFQUERY so you are free to use any syntax that is supported by your...

Page 50: ...C INETPUB WWWROOT myapps on Windows NT 4 Return to your browser and enter the following URL to view EmpList cfm http 127 0 0 1 myapps emplist cfm 5 View source in the browser The ColdFusion EmpList da...

Page 51: ...the CFOUTPUT tag with the QUERY attribute to define the query variable that you want to output to a page When you use the QUERY attribute ColdFusion loops over all the code contained within the CFOUTP...

Page 52: ...UERY before referencing its results using a CFOUTPUT with a QUERY attribute It s a good idea to run all queries before all output blocks A query name must exist on the page in order to successfully ou...

Page 53: ...oldFusion will start a new line for each row that is returned from the query Getting Information About Query Results Each time you query a database with the CFQUERY tag you get not only the data itsel...

Page 54: ...ry properties Prefix the property with its type in this case prefix the property with the name of the query Reference the query property within a CFOUTPUT block so that ColdFusion will output the quer...

Page 55: ...format and manipulate data Contents Using Forms to Specify the Data to Retrieve 30 Processing Form Variables on Action Pages 34 Dynamically Generating SQL Statements 34 Creating Action Pages 35 Using...

Page 56: ...ction page where some type of processing takes place Note Because forms are not ColdFusion specific the syntax and examples that follow provide you with just enough detail to get going with ColdFusion...

Page 57: ...NAME ControlName VALUE Value1 DisplayName1 INPUT TYPE Radio NAME ControlName VALUE Value2 DisplayName2 INPUT TYPE Radio NAME ControlName VALUE Value3 DisplayName3 Select box SELECT NAME ControlName O...

Page 58: ...ALUE Arlington Arlington OPTION VALUE Boston Boston OPTION VALUE Cambridge Cambridge OPTION VALUE Minneapolis Minneapolis OPTION VALUE Seattle Seattle SELECT radio buttons p Department br input type r...

Page 59: ...35 characters INPUT TYPE Text NAME Salary SIZE 10 MAXLENGTH 10 Create a text box called Salary where users can enter a salary to look for Make it 10 characters wide and allow input of up to 10 charac...

Page 60: ...like any other application page except that you can use the form variables that are passed to it from an associated form A form variable is passed for every form control that contains a value when th...

Page 61: ...ad of putting the LastName directly in the SQL WHERE clause you can use the text the user entered in the form for comparison CFQUERY NAME GetEmployees DATASOURCE CompanyInfo SELECT FirstName LastName...

Page 62: ...urround variable values with pound signs for output Checkboxes and radio buttons are only passed to the action page if an option is selected Code Description CFQUERY NAME GetEmployees DATASOURCE Compa...

Page 63: ...table tags You can also use the HTML TH tag to put column labels in a header row To create a row in the table for each row in the query results put the TR block inside the CFOUTPUT tag To put the que...

Page 64: ...e cfm in Studio 2 Change the line TD Salary TD to TD DollarFormat Salary TD Code Description TABLE Put data into a table TR TH First Name TH TH Last Name TH TH Salary TH TR In the first row of the tab...

Page 65: ...ollows should be used for pattern matching The LIKE operator tells the database that the string that follows should be used for pattern matching If you placed a wildcard before and after AL you would...

Page 66: ...loyees LastName Employees StartDate Employees Salary FROM Departments Employees WHERE Departments Department_ID Employees Department_ID AND Departments Department_Name HR CFQUERY Prefix each column in...

Page 67: ...rtments Department_ID Employees Department_ID 4 CFIF Form Department_Name IS NOT 4 AND Departments Department_Name Form Department_Name 4 CFQUERY H4 Employee Data Based on Criteia from Form H4 TABLE T...

Page 68: ...t a search has retrieved records you will need to test if any records have been returned using the recordcount variable in a conditional logic expression in order to display search results appropriate...

Page 69: ...partments Department_Name Form Department_Name CFQUERY H4 Employee Data Based on Criteia from Form H4 4 CFIF GetEmployees RecordCount IS 0 4 No records match your search criteria br 4 Please go back t...

Page 70: ...44 Developing Web Applications with ColdFusion...

Page 71: ...cally populate forms and dynamically generate SQL Contents Dynamically Populating Select Boxes 46 Creating Dynamic Checkboxes and Multiple Select Boxes 47 Testing for a variable s existence 51 Creatin...

Page 72: ...f this form control To dynamically populate a select box 1 Open the file formpage cfm in Studio 2 Modify the file so that it appears as follows HTML HEAD TITLE Input form TITLE HEAD BODY 4 CFQUERY NAM...

Page 73: ...mic Checkboxes and Multiple Select Boxes When an HTML form contains either a list of checkboxes with the same name or a multiple select box the user s entries are made available as a comma delimited l...

Page 74: ...dDepts_required VALUE You must select at least one organization The text displayed to the user is the name of the department but the VALUE attribute of each checkbox corresponds to the underlying data...

Page 75: ...LUE HR HR BR INPUT TYPE checkbox NAME SelectedDepts VALUE Sales Sales BR INPUT TYPE checkbox NAME SelectedDepts_required VALUE You must select at least one organization If the user checked Marketing a...

Page 76: ...Name SelectDepts MULTIPLE OPTION VALUE 1 Training OPTION VALUE 2 Marketing OPTION VALUE 3 HR OPTION VALUE 4 Sales SELECT INPUT TYPE hidden NAME SelectDepts_required VALUE You must select at least one...

Page 77: ...efined function For example the following code checks to see if a Form variable named Order_ID exists CFIF Not IsDefined FORM Order_ID CFLOCATION URL previous_page cfm CFIF The argument passed to the...

Page 78: ...the variables that a page or a custom tag expects to receive before processing can proceed This can make your code more readable as well as easier to maintain and to debug For example the following s...

Page 79: ...ynamic parameters is a powerful mechanism for linking variable inputs to database queries However in more sophisticated applications you will often want user inputs to determine not only the content o...

Page 80: ...he input form 1 Create a new application page in Studio 2 Enter the following code HTML HEAD TITLE Input form TITLE HEAD BODY Query the Employees table to be able to populate the form CFQUERY NAME Ask...

Page 81: ...create the action page 1 Create a new application page in Studio 2 Enter the following code HTML HEAD TITLE Get Employee Data TITLE HEAD BODY CFQUERY NAME GetEmployees DATASOURCE CompanyInfo 4 SELECT...

Page 82: ...on page getemp cfm build a SQL statement dynamically based on what the user enters in the form page AskEmp cfm CFML Code Description SELECT FROM Employees WHERE 0 0 Get all the records from the Employ...

Page 83: ...orm Salary is not AND Employees Salary form Salary CFIF If the user entered anything in the Salary text box in the form add AND Employees Salary what the user entered in the Salary text box to the SQL...

Page 84: ...58 Developing Web Applications with ColdFusion...

Page 85: ...h ColdFusion Contents Inserting Data 60 Creating an HTML Insert Form 60 Creating an Action Page to Insert Data 61 Updating Data 62 Creating an Update Form 63 Creating an Action Page to Update Data 65...

Page 86: ...end user Creating an HTML Insert Form To create an insert form 1 Create a new application page in Studio 2 Edit the page so that it appears as follows HTML HEAD TITLE Insert Data Form TITLE HEAD BODY...

Page 87: ...the data entered by the user into the appropriate database fields Creating an Action Page to Insert Data There are two ways to create an action page to insert data into a database The CFINSERT tag is...

Page 88: ...Employee Added H1 CFOUTPUT You have added Form FirstName Form LastName to the Employees database CFOUTPUT BODY HTML 3 Save the page as insertpage cfm 4 View isertform cfm in a browser enter values an...

Page 89: ...hidden input field with the value of the primary key for the record you want to update The hidden field indicates to ColdFusion which record to update To create an update form 1 Create a new page in S...

Page 90: ...y FORM ACTION EmployeeUpdate cfm METHOD Post Create a form whose variables will be process on the EmployeeUpdate cfm action page INPUT TYPE Hidden NAME Employee_ID VALUE Employee_ID BR Use a hidden in...

Page 91: ...ng the remaining form fields submitted For more complicated updates you can use a SQL UPDATE statement in a CFQUERY tag instead of a CFUPDATE tag The SQL update statement is more flexible for complica...

Page 92: ...ontains a CFQUERY tag with a SQL delete statement To delete one record from a database 1 Open the file updateform cfm in Studio 2 Modify the file by changing the FORM tag so that it appears as follows...

Page 93: ...from the Employees table you would use the following DELETE FROM Employees Note Deleting records from a database is not reversible Use delete statements carefully Requiring Users to Enter Values in Fo...

Page 94: ...Fields Field Suffix Value Attribute Description _integer Custom error message Verifies that the user enters a number If the user enters a floating point value it is rounded to an integer _float Custom...

Page 95: ...ate_date VALUE Enter a valid date as the start date INPUT TYPE hidden NAME Salary_float VALUE The salary must be a number Employee ID INPUT TYPE text NAME Employee_ID SIZE 4 MAXLENGTH 4 BR First Name...

Page 96: ...user that explains the problem The user then must go back to the form correct the problem and resubmit the form ColdFusion will not accept form submission until the entire form is entered correctly Be...

Page 97: ...n code Contents Ways to Reuse Code 72 Reusing Common Code with CFINCLUDE 72 About Custom Tags in CFML 73 Using Existing Custom Tags 73 Writing Custom CFML Tags 73 Passing Attribute Values between Cust...

Page 98: ...code in one page and then refer to it in many pages This way you can modify one file the changes appear throughout an entire application Use the CFINCLUDE tag to automatically include an existing fil...

Page 99: ...nline discussion forum for tag topics Tag names with the CF_ preface are CFML custom tags those with the CFX_ preface are ColdFusion Extensions written in C For more information about the CFX tags see...

Page 100: ...ribute value pairs for a tag must be separated by a space Passed values that contain spaces must be enclosed in double quotes Passing Attribute Values between Custom Tags Because custom tags are indiv...

Page 101: ...e custom tag CFOUTPUT You are now DOCTOR CFOUTPUT BODY HTML 3 Save the page as callingpage cfm 4 Create another new page the custom tag in Studio 5 Enter the following code HTML HEAD TITLE GetMD Custo...

Page 102: ...le to all templates base includes and custom tags Collaborating custom tags that are not nested in a single tag can exchange data via the request structure You should assign a unique name for each var...

Page 103: ...h sub tags and other code contained within the base tag are processed No processing occurs in the base tag during this phase The end mode in which the base tag is processed a second time Associating s...

Page 104: ...that the variable MyQueryResults in a tag s implementation holds an important query result set and expecting users of the custom tag to manipulate MyQueryResults directly create another nested custom...

Page 105: ...valuate collectionName attributes The CFML code accessing sub tag attributes in the base tag could look like the following Protect against no sub tags CFPARAM Name thisTag assocAttribs default arrayNe...

Page 106: ...0 I m running in the context of a CFLOOP tag P CFIF Determine whether you are nested inside a custom tag Skip the first two elements of the ancestor list i e CFIF and the name of the custom tag I m in...

Page 107: ...specifying these attributes in the custom tag s attribute list ATTRIBUTECOLLECTION may be freely mixed with other attributes within the custom tag s attribute list The reserved attribute name ATTRIBU...

Page 108: ...BR end custom tag Its output will be custom tag blab X 12 16 end custom tag Executing Custom Tags Tag instance data During the execution of a custom tag template ColdFusion keeps some data related to...

Page 109: ...xecution to validate this Specifying execution modes A variable with the reserved name ThisTag ExecutionMode will specify the mode of invocation of a custom tag template The variable will have one of...

Page 110: ...enerated by the body of a given tag This includes all results generated by descendant tags too Any changes to the value of this variable will result in changes to the generated content ThisTag Generat...

Page 111: ...re a custom tag among applications in multiple directories place it in the Custom Tags folder under your ColdFusion installation directory for example C CFUSION CustomTags You can create sub folders t...

Page 112: ...stom tag code before distributing it cfencode uses the following syntax cfencode infile outfile r q h message v 2 CFMODULE Attributes Attribute Description Template Required if the NAME attribute is n...

Page 113: ...you don t specify an output file name a warning message asks if you want to continue in which case the encoded file will overwrite the source file r Recursive when used with wildcards recurses throug...

Page 114: ...88 Developing Web Applications with ColdFusion...

Page 115: ...ugh the CFTRY CFCATCH and CFTHROW tags ColdFusion Studio provides interfaces for debugging application pages and for dynamically validating multiple levels of HTML and CFML code For information on usi...

Page 116: ...www myserver com cfdocs test cfm mode debug Generating debug information for an individual query You can view debug information for an individual query by putting the DEBUG attribute into the opening...

Page 117: ...uch as ACTION or METHOD for which the value is provided at runtime These instances are validated at runtime There are two implications There will be a slight performance penalty due to runtime attribu...

Page 118: ...space ColdFusion correctly translates the sign into a space A common scenario in which this error occurs is when you dynamically generate your URL from database text fields that may have embedded spac...

Page 119: ...custom error application pages page by page but because custom error pages generally apply to an entire application it is more efficient to include the CFERROR tag in the Application cfm file After y...

Page 120: ...m The following problems occurred P Error InvalidFields BODY HTML Overview of Exception Handling in ColdFusion Ordinarily when ColdFusion encounters an error it stops processing However you can use Co...

Page 121: ...matic SQL statement for example you might narrow the focus by using a CFTRY block with a CFCATCH TYPE Database tag outputting the CFCATCH State information as well Note Do not attempt to enclose an en...

Page 122: ...CH TYPE Any Catch general application page errors The tags that throw an exception of TYPE TEMPLATE are CFINCLUDE CFMODULE and CFERROR Missing included file errors CFCATCH TYPE MissingInclude CFCATCH...

Page 123: ...ed within a CFCATCH block cannot be handled by the CFTRY block that immediately encloses the CFCATCH tag Exception Information in CFCATCH Within a CFCATCH block the active exception s properties can b...

Page 124: ...ve the following attributes TEMPLATE The pathname of the application page that contains the tag LINE and COLUMN The tag s line number and column number within the application page Note Turn off Enable...

Page 125: ...ions The values assumed by CFCATCH NATIVEERRORCODE are driver dependent If no error code is provided the value of NativeErrorCode is 1 CFCATCH SQLSTATE The SQLSTATE code associated with this exception...

Page 126: ...main processing level to gracefully terminate a subsystem s processing in case of an unexpected error Exception handling example The following example shows CFTRY and CFCATCH using a sample data sour...

Page 127: ...ing Include File H1 CFOUTPUT UL LI B Message B CFCATCH Message LI B Detail B CFCATCH Detail LI B File name B CFCATCH MissingFilename UL CFOUTPUT 4 CFCATCH Use CFCATCH to test for database errors Print...

Page 128: ...his example CFTHROW TYPE COM Allaire ProjectName ERRORCODE Dodge14B The predefined exception types except for TYPE APPLICATION are reserved for example CFTHROW TYPE Database will be rejected A CFCATCH...

Page 129: ...n also supports structures for managing lists of key value pairs This chapter explains the basics of creating and working with structures Contents About Arrays 104 Creating an Array 105 Basic Array Te...

Page 130: ...shopping cart contents can be stored in an array This allows you to make changes easily without committing the information which the user may change before completing the transaction to a database Con...

Page 131: ...y element Data stored in an array index The syntax my2darray 1 3 Paul is the same as saying My2dArray is a two dimensional array and the value of the array element index 1 3 is Paul Dynamic arrays exp...

Page 132: ...o use arrays in ColdFusion as in other languages you need to first declare the array specifying its dimension Once it s declared you can add array elements which you can then reference by index As an...

Page 133: ...t these array functions see the CFML Language Reference Note Because ColdFusion arrays are dynamic if you add or delete an element from the middle of an array subsequent index positions all change Ref...

Page 134: ...ul for adding data to an existing array In addition several basic techniques are important to master Populating an array with ArraySet Populating an array with CFLOOP Populating an array from a query...

Page 135: ...need to employ nested loops to return array data With a 1D array a single CFLOOP is sufficient to output data as in the example just above With arrays of dimension greater than one you need to maintai...

Page 136: ...A looping structure is generally required to populate an array from a query Query column data can be referenced using array like syntax For example myquery col_name 1 references data in the first row...

Page 137: ...or creating editing and handling arrays Array Functions Function Description ArrayAppend Appends an array index to the end of a specified array ArrayAvg Returns the average of the values in the specif...

Page 138: ...ort Returns the specified array with elements sorted numerically or alphanumerically ArraySum Returns the sum of values in the specified array ArraySwap Swaps array values in the specified indexes Arr...

Page 139: ...ctures Types of Structure Notation Notation Description Objects property Use to refer to values in a structure So a property prop of an object obj can be referred to as obj prop This notation is usefu...

Page 140: ...ame key value AllowOverwrite The AllowOverwrite parameter is optional and can be either TRUE or FALSE It can be used to specify whether an existing key should be overwritten or not The default is FALS...

Page 141: ...ou enumerate key value pairs using a loop the keys appear in uppercase Getting information about structures To find out if a given value represents a structure use the IsStruct function IsStruct varia...

Page 142: ...ure you want to copy and returns a new structure with all the keys and values of the named structure StructCopy structure This function throws an exception if structure doesn t exist Use the StructCop...

Page 143: ...New Employees H1 Establish parameters for first time through CFPARAM NAME FORM firstname DEFAULT CFPARAM NAME FORM lastname DEFAULT CFPARAM NAME FORM email DEFAULT CFPARAM NAME FORM phone DEFAULT CFP...

Page 144: ...e file addemployee cfm P 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 add the...

Page 145: ...nt you would use the syntax Departments John A structure s key must be a string The values associated with the key can be anything a string an integer an array another structure Looping through struct...

Page 146: ...ith all the keys and values of the specified structure StructCount Returns the number of keys in the specified structure StructDelete Removes the specified item from the specified structure StructFind...

Page 147: ...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 Updat...

Page 148: ...122 Developing Web Applications with ColdFusion...

Page 149: ...need to code Java directly Contents Creating Forms with the CFFORM Tag 124 Input Validation with CFFORM Controls 126 Input Validation with JavaScript 127 Building Tree Controls with CFTREE 129 Struct...

Page 150: ...ns you don t have to write separate CFML code specifically for input validation as you do in HTML forms Using HTML in a CFFORM You can use the HTML FORM tag in combination with the CFFORM tag ColdFusi...

Page 151: ...ER CFTEXTINPUT and CFTREE require a Java applet to run browsers that do not support Java or that have disabled Java execution will not execute the forms that contain these controls Using the NOTSUPPOR...

Page 152: ...DATE Entry Description Date Verifies US date entry in the form mm dd yyy Eurodate Verifies valid European date entry in the form dd mm yyyy Time Verifies a time entry in the form hh mm ss Float Verifi...

Page 153: ...IDATE attribute form_object input_object object_value Handling failed validation The ONERROR attribute allows you to specify a JavaScript function you want to execute in the event of a failed validati...

Page 154: ...4 SCRIPT HEAD BODY H2 JavaScript validation test H2 P Please enter your email address P CFFORM NAME UpdateForm ACTION update cfm CFINPUT TYPE text NAME inputbox1 REQUIRED YES 4 ONVALIDATE testbox MES...

Page 155: ...items in the tree control To create and populate a tree control from a query 1 Open a new file named tree1 cfm in Studio 2 Modify the page so that it appears as follows CFQUERY NAME engquery DATASOURC...

Page 156: ...s as follows CFQUERY with an ORDER BY clause CFQUERY NAME deptquery DATASOURCE CompanyInfo SELECT Department_ID FirstName LastName AS FullName FROM EMPLOYEES ORDER BY Department_ID CFQUERY Code Descri...

Page 157: ...r all levels in the tree CFTREE form variables The CFTREE tag allows you to force a user to select an item from the tree control by setting the REQUIRED attribute to YES With or without the REQUIRED a...

Page 158: ...r to select an item from the tree control In addition you can use the ONVALIDATE attribute to specify the JavaScript code to perform validation Structuring Tree Controls Tree controls built with CFTRE...

Page 159: ...oduct Two IMG document CFTREEITEM VALUE Kernel PARENT Product Two IMG document CFTREEITEM VALUE Product Three PARENT Development CFTREEITEM VALUE QA PARENT Divisions IMG folder CFTREEITEM VALUE Produc...

Page 160: ...EEITEM To embed links in a CFTREE 1 Open a new file named tree3 cfm in Studio 2 Modify the page so that it appears as follows CFFORM ACTION submit cfm CFTREE NAME oak HIGHLIGHTHREF yes HEIGHT 100 WIDT...

Page 161: ...g options as well as the option of validating user selections with a JavaScript validation script You can also do the following with CFGRID Sort data in the grid alphanumerically Update insert and del...

Page 162: ...LECT FROM Employees CFQUERY CFFORM NAME Form1 ACTION submit cfm METHOD Post CFGRID NAME employee_grid QUERY empdata SELECTMODE single CFGRIDCOLUMN NAME Employee_ID CFGRIDCOLUMN NAME LastName CFGRIDCOL...

Page 163: ...tions to update data source records Pass grid edits to a page that includes the CFGRIDUPDATE tag which passes data directly to the data source Although using CFQUERY gives you complete control over in...

Page 164: ...the file so that it appears as follows CFQUERY NAME empdata DATASOURCE CompanyInfo SELECT FROM Employees CFQUERY CFFORM NAME GridForm ACTION handle_grid cfm CFGRID NAME employee_grid HEIGHT 170 WIDTH...

Page 165: ...fy the file so that it appears as follows HTML HEAD TITLE Catch submitted grid values TITLE HEAD BODY H3 Grid values for FORM employee_grid row updates H3 CFIF IsDefined form employee_grid rowstatus a...

Page 166: ...OURCE CompanyInfo INSERT into Employees Employee_ID LastName Department_ID VALUES form employee_grid Employee_ID Counter form employee_grid LastName Counter form employee_grid Department_ID Counter CF...

Page 167: ...operation the original cell value and the edited cell value in the following arrays CFSET edittype mygrid RowStatus Action 1 BR CFSET new_value mygrid col2 1 BR CFSET old_value mygrid original col2 1...

Page 168: ...ws CFFORM NAME Form1 ACTION submit cfm METHOD Post CFSLIDER NAME myslider GROOVECOLOR black BGCOLOR white TEXTCOLOR black FONT Trebuchet MS BOLD yes RANGE 0 1000 SCALE 10 VALUE 640 FONTSIZE 24 LABEL S...

Page 169: ...iable passed from a CFTEXTINPUT control to a ColdFusion application page is determined by the entry in the CFTEXTINPUT control The form variable is passed as textinput_name textinput_value In the exam...

Page 170: ...a is used in the form variable that is passed to the application page specified in ACTION Embedding Java Applets The CFAPPLET tag allows you to embed Java applets in a CFFORM To use CFAPPLET you must...

Page 171: ...tering the Administrator password if required 2 Click the Applets button to open the Registered Applets page 3 Enter a name for the applet you want to register and click Register New Applet Enter the...

Page 172: ...cing and alignment values Height Enter a measurement in pixels for the vertical space for the applet Width Enter a measurement in pixels for the horizontal space for the applet Vspace Enter a measurem...

Page 173: ...plet method provides when it is executed in the CFFORM Not all Java applets return values Some like many graphical widgets do not return a specific value they do their flipping spinning fading explodi...

Page 174: ...148 Developing Web Applications with ColdFusion...

Page 175: ...File Types 151 Support for International Languages 152 Steps in Creating a Searchable Data Source 153 Creating a Collection 153 Populating and Indexing a Collection 157 Building a Search Interface 159...

Page 176: ...quires only that the full path to the collection be specified in the index command Index email generated by ColdFusion application pages and create a searching mechanism for the indexed messages Build...

Page 177: ...y implementation supports a wide array of document types This means you can index Web pages ColdFusion applications and many binary document types and produce search results that include summaries of...

Page 178: ...for DOS 4 5 6 Binary MS Word for Macintosh 4 0 5 0 6 0 Binary MS Notepad WordPad all Binary MS Write MS Works all Binary XYWrite 4 12 Binary Spreadsheets Corel QuattroPro 7 8 Binary Lotus 1 2 3 for D...

Page 179: ...ly 2 Populate and index the collection This involves selecting the data and generating the index 3 Design a search interface and a results page so that users can access the searchable data source Crea...

Page 180: ...top of the page You can easily enable access to a collection on the network by creating a local reference an alias for that collection It only needs to be a valid Verity collection it doesn t matter...

Page 181: ...hat do you want to do with the collection P INPUT TYPE radio NAME CollectionAction VALUE Create checked Create BR INPUT TYPE radio NAME CollectionAction VALUE Repair Repair BR INPUT TYPE radio NAME Co...

Page 182: ...The collection FORM CollectionName is created CFCASE CFCASE VALUE Repair CFCOLLECTION ACTION REPAIR COLLECTION FORM CollectionName P The collection FORM CollectionName is repaired CFCASE CFCASE VALUE...

Page 183: ...strator To use ColdFusion Administrator to index a collection 1 Select a collection name in the Verity Collections box 2 Click Index to open the index page The selected collection name appears at the...

Page 184: ...o change your server file structures to accommodate the generation of indices In your ColdFusion application you can populate and search multiple collections each of which can be designed to focus on...

Page 185: ...that you ve created and indexed a searchable data source you need to build a search interface to allow users to access the data source The CFSEARCH tag provides users with a set of operators and modi...

Page 186: ...NAME collection SIZE 25 MAXLENGTH 35 P P Select the type of search BR INPUT TYPE radio NAME type VALUE Simple checked Simple BR INPUT TYPE radio NAME type VALUE Explicit Explicit BR P Enter a search s...

Page 187: ...internal rules up to a maximum of 500 characters Summarization information is returned by default with every CFSEARCH operation For more information on this topic see the Allaire Knowledge Base articl...

Page 188: ...ers then point the CFINDEX tag at the result set from a CFQUERY CFLDAP or CFPOP query To index a ColdFusion query 1 Create the collection on the ColdFusion Administrator Verity page 2 Execute a query...

Page 189: ...ta source itself You want to improve the speed of queries You want your end users to run queries but not update a database table You do not want to expose your data source Indexing CFLDAP Query Result...

Page 190: ...ection Use the wildcard to contain the search string CFSEARCH COLLECTION ldap_query NAME s_ldap CRITERIA 617 Output returned records CFOUTPUT QUERY s_ldap Key Title Body BR CFOUTPUT Indexing CFPOP Que...

Page 191: ...o search a collection The next section expands on the capabilities of this tag for more detailed input and output options Using Query Expressions When you search a Verity collection you use the CFSEAR...

Page 192: ...t using angle brackets A simple query employs the STEM operator and the MANY modifier STEM searches for words that derive from those entered in the query expression so that entering find will return d...

Page 193: ...words you can enter the word film without modification When documents are ranked by relevance they appear in a list with the most relevant documents at the top Explicit syntax When you use explicit s...

Page 194: ...e over OR operators However terms enclosed in parenteses are evaluated first When the search engine encounters nested parentheses it starts with the innermost term Prefix and infix notation Search str...

Page 195: ...at contain any combination of a and b together Note that in this example angle brackets are used with the OR operator OR a b Delimiters in expressions Angle brackets double quotation marks and backsla...

Page 196: ...Verity Wildcard Characters Wildcard Description Question Specifies any single alphanumeric character Asterisk Specifies zero or more alphanumeric characters Avoid using the asterisk as the first char...

Page 197: ...g search parameters Operators An operator represents logic to be applied to a search element This logic defines the qualifications a document must meet to be retrieved Operators are used to refine you...

Page 198: ...in the same phrase paragraph or sentence for a document to be retrieved In the case of NEAR and NEAR N operators retrieved documents are ranked by relevance based on the proximity of the specified wor...

Page 199: ...ocuments containing two or more search terms within N number of words of each other where N is an integer between 1 and 1024 where NEAR 1 searches for two words that are next to each other The closer...

Page 200: ...are selected only if the search elements specified appear in the same sequential and contiguous order in the field value For example specifying god will match God in heaven a god among men or good go...

Page 201: ...a character string with data stored in a specified data source In the following example a data source called TEST1 contains the table YearPlaceText which itself contains three columns Year Place and T...

Page 202: ...ag CFQUERY NAME GetText DATASOURCE TEST1 SELECT Year Place AS Identifier text FROM YearPlaceText CFQUERY CFINDEX COLLECTION testcollection ACTION Update TYPE Custom TITLE Identifier KEY Identifier BOD...

Page 203: ...rch engine first calculates a separate score for each search element found in a document and then performs a mathematical operation on the individual element scores to arrive at the final score for ea...

Page 204: ...e score of an element to 1 if the element s score is non zero YESNO mainframe If the retrieval result of the search on mainframe is 0 75 the YESNO operator forces the result to 1 You can use YESNO to...

Page 205: ...ier Description CASE Specifies a case sensitive search CASE J JAVA java Searches for JAVA and Java If a search contains a mixed case string the search request will be case sensitive MANY Counts the de...

Page 206: ...x corrupted records If you suspect a collection has become corrupted it is probably safest to re populate it Optimize Packs the indexed data for better performance This is similar to database optimiza...

Page 207: ...DEX ACTION only Deletes all data and re populates the collection Securing a collection A couple of possible scenarios for restricting access to a Verity collection are The ColdFusion Administrator may...

Page 208: ...182 Developing Web Applications with ColdFusion...

Page 209: ...anding the Web Application Framework 184 Mapping Out an Application Framework 185 Creating the Application cfm File 187 Setting up client state management options 188 Managing Client State in a Cluste...

Page 210: ...es and features available across the entire application Once you have defined an application you can use the application level features in addition to all of the other features in ColdFusion Client st...

Page 211: ...in subdirectories of the root directory When any ColdFusion application page is requested ColdFusion searches up the page s directory tree for an Application cfm file When it is found the Application...

Page 212: ...le Application cfm file for your application or use different Application cfm files that govern individual sections of the application The directory trees below illustrate two approaches to implementi...

Page 213: ...oldFusion does not initiate another search up the directory tree based on the included application page This is an important behavior to understand Upon opening a requested application page ColdFusion...

Page 214: ...lue you set for the NAME attribute in CFAPPLICATION is limited to 64 characters To name the application 1 Open Studio and create a new file 2 Modify the file so that it appears as follows This example...

Page 215: ...See Administering ColdFusion Server for information on using the ColdFusion Administrator You use the CLIENTSTORAGE attribute in the CFAPPLICATION tag to specify where you want to store client variabl...

Page 216: ...clustered environment you can use server side client variables that get stored in a common back end repository that all Web servers in a multi server clustered environment can access Even though all s...

Page 217: ...rite color is Client FavoriteColor CFOUTPUT Standard client variables In addition to storing custom client variables the Client object has several standard parameters These parameters can be useful in...

Page 218: ...t Deleting client variables Unlike normal variables client variables and their values persist over time In this fashion they are akin to cookies To delete a client variable use the DeleteClientVariabl...

Page 219: ...can take it to a new machine and import it by selecting Import Registry File on the Registry Editor Registry menu Application and Session Variables In ColdFusion you use variables to work around the...

Page 220: ...es associated with a given application Sessions are specific to individual users As a result every user has a separate session and has access to a separate set of session variables This logical view o...

Page 221: ...ences could be retrieved from a database once the first time a user hits any page of an application This information would remain available throughout that user s session thereby avoiding the overhead...

Page 222: ...that application Using application variables an application could initialize itself say when the first user hit any page of that application This information could then remain available indefinitely...

Page 223: ...be running on a server Because of this sharing applications cannot assume that values saved in these variables will not be overwritten by other instances of the same application that might be simultan...

Page 224: ...sons you use CFLOCK include Protecting sections of code that manipulate shared data such as session application and server variables Ensuring that file updates do not fail because files are open for w...

Page 225: ...nvocations can guarantee that CFXs that are not implemented in a thread safe manner can be safely invoked by ColdFusion This usually only applies to CFXs developed in C using the CFAPI Any C CFX that...

Page 226: ...es you must do so in the following order 1 Lock the session scope In the CFLOCK tag specify thescope as session 2 Lock the application scope In the CFLOCK tag specify the scope as application 3 Lock t...

Page 227: ...and application variables that will be used by E Turtleneck Use the session lock for the session variables The member variable sessionID creates the session name for you CFLOCK SCOPE Session TIMEOUT...

Page 228: ...IMEOUT 30 TYPE ReadOnly CFOUTPUT Thank you for shopping E Turtleneck Today you have chosen a turtleneck in size B form size B and in the color B form color B Your order number is session sessionID CFO...

Page 229: ...SELECT TD TR TR TD Select a size TD TD SELECT TYPE Text NAME size OPTION small OPTION medium OPTION large OPTION xlarge SELECT TD TR TR TD TD TD INPUT TYPE Submit NAME submit VALUE Submit TD TR TABLE...

Page 230: ...cause this is the only place from which the CFX will be invoked CFPARAM NAME Attributes AttributeOne Default CFPARAM NAME Attributes AttributeTwo Default CFPARAM NAME Attributes AttributeThree Default...

Page 231: ...vers via the CFMAIL tag and the CFPOP tag The boom in Internet mail services makes ColdFusion s enhanced email capability a vital link to your users Contents Using ColdFusion with Mail Servers 206 Sen...

Page 232: ...and or a valid POP account In your ColdFusion application pages you use the CFMAIL and CFPOP tags to send and receive mail respectively The following sections describe ColdFusion email features and of...

Page 233: ...TO URL email SUBJECT Sample email This is a sample email to show basic email capability CFMAIL The email was sent BODY HTML 3 Save the file as sendmail cfm in myapps under the Web root directory 4 Op...

Page 234: ...t Form Subject Form InquiryText CFMAIL Sending query based email In the example below a query ProductRequests is run to retrieve a list of the customers who have inquired about a product over the last...

Page 235: ...aire com Regards ColdFusion Technical Support beta allaire com CFMAIL Note that in this example the contents of the CFMAIL tag are not dynamic that is they don t use any delimited dynamic parameters W...

Page 236: ...he Email query column causes one message to be sent to the address listed in each row of the query Also note the use of the other query columns FirstName LastName etc within the CFMAIL section to cust...

Page 237: ...ssage type as HTML The TYPE attribute which only accepts HTML as an argument informs the receiving email client that the message has embedded HTML tags that need to be processed This feature is only u...

Page 238: ...e body attachments etc 3 Decide if you need to store the retrieved messages in a database 4 Decide if you need to delete messages from the POP server once you ve retrieved them 5 Incorporate the CFPOP...

Page 239: ...y the message header 1 Create a new file in Studio 2 Modify the file so that it appears as follows HTML HEAD TITLE POP Mail Message Header Example TITLE HEAD BODY H2 This example retrieves message hea...

Page 240: ...or In addition you can process the date returned by CFPOP with ParseDateTime which accepts an argument for converting POP date time objects into GMT Greenwich Mean Time See the CFML Language Reference...

Page 241: ...POP SERVER mail company com USERNAME username PASSWORD password 4 Save the file as hdrbody cfm in myapps under the Web root directory Returning attachments with messages When you use the CFPOP tag wit...

Page 242: ...that it refers to a valid POP mail server as well as a valid user name and password CFPOP SERVER mail company com USERNAME username PASSWORD password 4 Save the file as attach cfm in myapps under the...

Page 243: ...appears as follows HTML HEAD TITLE POP Mail Message Delete Example TITLE HEAD BODY H2 This example deletes messages H2 CFPOP SERVER mail company com USERNAME username PASSWORD password ACTION Delete...

Page 244: ...218 Developing Web Applications with ColdFusion...

Page 245: ...t tasks To perform server to server operations use the CFFTP tag Contents Using CFFILE 220 Uploading Files 220 Setting File and Directory Attributes 223 Evaluating the Results of a File Upload 224 Mov...

Page 246: ...ctories on the server before allowing users access to them Uploading Files File uploading requires that you create two files An HTML form to enter file upload information An action page containing the...

Page 247: ...Modify the file so that it appears as follows HTML HEAD TITLE Upload File TITLE HEAD body H2 Upload File H2 CFFILE ACTION UPLOAD DESTINATION c inetpub wwwroot HR NAMECONFLICT Overwrite FILEFIELD File...

Page 248: ...NFLICT attribute For example you can specify the parameter NAMECONFLICT MAKEUNIQUE in the CFFILE tag to create a unique file name while keeping the file extension the same Controlling the type of file...

Page 249: ...NATION c uploads MyImage GIF NAMECONFLICT OVERWRITE ACCEPT image gif image jpeg This CFFILE specification will only save an image file but the format doesn t matter CFFILE ACTION Upload FILEFIELD Uplo...

Page 250: ...ied Example Setting file attribute This example sets the archive bit for the uploaded file CFFILE ACTION Copy SOURCE c files upload keymemo doc DESTINATION c files backup ATTRIBUTES Archive Note Be su...

Page 251: ...ubtype of the saved file such as gif for image gif ContentType MIME content type of the saved file such as image for image gif DateLastAccessed Date and time the uploaded file was last accessed FileEx...

Page 252: ...ibute in a CFFILE tag can be a dynamic parameter This makes CFFILE a very powerful tool ServerFileExt Extension of the uploaded file on the server without a period for example txt not txt ServerFileNa...

Page 253: ...ert its contents into a database Or you could read a text file and then use one of the find and replace functions to modify the contents To read a text file 1 Create a new file in Studio 2 Modify the...

Page 254: ...it VALUE Submit FORM BODY HTML 3 Save the file as writetextfileform cfm in myapps under the Web root directory To write a text file 1 Open a new file in Studio 2 Modify the file so that it appears as...

Page 255: ...me Size Directory entry size Type File type F or D for File or Directory DateLastModified Date an entry was last modified Attributes File attributes if applicable Mode Solaris only The octal value rep...

Page 256: ...ry size TD TD mydirectory type TD TD mydirectory datelastmodified TD TD mydirectory attributes TD TD mydirectory mode TD TR CFOUTPUT TABLE BODY HTML 3 Modify the line DIRECTORY c inetpub wwwroot mine...

Page 257: ...sing the CFHTTP Get Method 232 Creating a Query from a Text File 234 Using the CFHTTP Post Method 236 Using Secure Sockets Layer SSL with CFHTTP 238 Performing File Operations with CFFTP 239 Moving Co...

Page 258: ...use of CFHTTP for creating automated processes such as Search agents Transaction agents Messaging agents The video is part of Allaire Alive an educational service that offers Web videos on topics spe...

Page 259: ...w file in Studio 2 Modify the file so that it appears as follows Code Description CFHTTP METHOD Get URL http www allaire com index cfm RESOLVEURL Yes Get the page specified in the URL and make the lin...

Page 260: ...ations on the data Text files are processed in the following manner You specify a delimiter with the DELIMITER attribute If data in a field includes the delimiter character it must be quoted or qualif...

Page 261: ...e as the column names CFHTTP METHOD Get URL http 127 0 0 1 orders june orders txt NAME juneorders DELIMITER TEXTQUALIFIER CFOUTPUT QUERY juneorders OrderID OrderID BR Order Number OrderNum BR Order Da...

Page 262: ...in CFHTTP is exactly the same To pass variables to a ColdFusion page 1 Open a new file in Studio 2 Modify the file so that it appears as follows CFHTTP METHOD Post URL http 127 0 0 1 dwa_code server c...

Page 263: ...It returns the value of the variables which appears in the client s browser This example uses the CFFILE tag in the page that receives the Posted variables to upload the contents of the file variable...

Page 264: ...WinInet problem is available The workaround is to run ColdFusion as a desktop application when SSL is needed In this way WinInet will write to and read from the registry appropriately when negotiatin...

Page 265: ...ves two distinct types of operations connecting and transferring files For a complete list of attributes see the CFML Language Reference To open an FTP connection and retrieve a file listing 1 Open a...

Page 266: ...case make sure that when you use frames only one frame uses the connection object Caching connections across multiple pages CFFTP caching is maintained only in the current page unless you explicitly...

Page 267: ...vaScript objects while JavaScript data generated on the browser can be serialized which involves translating the native data structures into an abstract representation in XML and transferred to the ap...

Page 268: ...model was designed with a completely different vision of what general internetworking would look like Instead of the dumb and disconnected model of HTTP distributed computing was built on the assumpt...

Page 269: ...signed to transport application level data structures to facilitate seamless computing between the client and the server side of a web application Application level data structures generally differ fr...

Page 270: ...ialization to CFML and COM time zone information is automatically taken into account and all date time values are converted to local time In this way UTC is taken out of the picture entirely and devel...

Page 271: ...ample uses a registered ColdFusion datasource and can be run from ColdFusion Server Create a simple query CFQUERY NAME q DATASOURCE snippets SELECT Message_Id Thread_id Username Posted from messages C...

Page 272: ...GUAGE JavaScript SRC CFIDE scripts wddx js SCRIPT Add data binding code SCRIPT Generic serialization to a form field function serializeData data formField wddxSerializer new WddxSerializer wddxPacket...

Page 273: ...xPacket INPUT TYPE submit BALUE Submit P This is where the WDDX packet will be stored WDDX packet display p TEXTAREA NAME wddxPacket ROWS 10 COLS 80 WRAP Virtual TEXTAREA FORM Server side processing H...

Page 274: ...248 Developing Web Applications with ColdFusion...

Page 275: ...irectory Access Protocol LDAP API in CFML is part of Allaire s commitment to open networking standards Contents What is LDAP 250 ColdFusion Support for LDAP 252 Working with LDAP Directories 253 Viewi...

Page 276: ...are familiar to database users LDAP supports a flat or one level structure as readily as multiple levels The illustration below shows a simplified tree of entries from the root level to the individual...

Page 277: ...ce with the protocol regardless of the complexity of directory trees LDAP name syntax begins at the entry level and specifies each level up to the root In other words it proceeds from the individual t...

Page 278: ...ze extensions to the LDAP version 3 protocol and extensions to the use of LDAP on the Internet Their site is at http www ietf org html charters ldapext charter html The Directory Enabled Networks DEN...

Page 279: ...ectory s schema information as part of a special entry in the root DN You can access this information using a ColdFusion query To view the schema for an LDAP directory 1 Create a new file in Studio 2...

Page 280: ...ory CFLDAP allows you to search an LDAP directory and output the results of your query on a page You can sort query results and return them to the browser or perform further processing with CFOUTPUT C...

Page 281: ...with A B C D or E To query an LDAP directory 1 Open a new file in Studio 2 Modify the file so that it appears as follows CFLDAP NAME OrgList SERVER ldap itd umich edu ACTION QUERY ATTRIBUTES o st tele...

Page 282: ...inistration of an LDAP server is one possible using one of these options The following example runs a cycle of LDAP actions by first adding a new record then querying the LDAP directory and generating...

Page 283: ...n LEFT colheaderitalic No colheaderbold yes selectmode BROWSE picturebar no CFGRIDCOLUMN NAME cn HEADER Name CFGRIDCOLUMN NAME mail HEADER eMail Address CFGRIDCOLUMN NAME telephonenumber HEADER Phone...

Page 284: ...groups o airius com Be careful when you do this modify or you can remove attribute values you did not intend to ATTRIBUTES uniquemember uid scarter ou People o airius com uid tmorris ou People o airi...

Page 285: ...PASSWORD testldap ACTION MODIFY ATTRIBUTES UPDATE_ATTRS DN dn CFELSE If the insert parameter is sent then run this insert CFIF IsDefined Distinguished_Name CFSET ADD_ATTRS objectclass top person orga...

Page 286: ...ER sn ens cn K START o Ace Industry c US MAXROWS 50 TIMEOUT 30 HTML HEAD TITLE LDAP Directory Example TITLE HEAD P To modify the attributes of an entry select the entry and click the B Update B button...

Page 287: ...DAP to retrieve the common name and distinguished name for all employees that have a surname that contains ens and a common name that is K Search starts in the country US and organization Ace Industry...

Page 288: ...262 Developing Web Applications with ColdFusion...

Page 289: ...ColdFusion Studio before giving them access to protected resources For information on setting up security elements or using Administrator controlled security features See Administering ColdFusion Serv...

Page 290: ...ecurity framework in a team oriented ColdFusion development environment where groups of developers working in ColdFusion Studio require different levels of access to ColdFusion files and data sources...

Page 291: ...inst a security context to see if a user is allowed to access a particular resource and then takes Before you can implement user security in your applications you must make sure that your ColdFusion a...

Page 292: ...y you can encrypt strings in your applications using the Encrypt and Decrypt functions See the CFML Language Reference for descriptions of these functions Using the CFAUTHENTICATE tag The CFAUTHENTICA...

Page 293: ...nticated user has access to the named resource based on rules defined in the security context for which the user has been authenticated Using the IsAuthenticated Function The IsAuthenticated function...

Page 294: ...structured exception handling tags CFTRY and CFCATCH to catch security exceptions Setting the TYPE attribute in CFCATCH to Security enables you to catch failures in the CFAUTHENTICATE tag You can also...

Page 295: ...f functionality you d also need to provide access to some resources that you d probably rather keep protected Using CFIMPERSONATE provides access to these resources in a safe manner by wrapping the fu...

Page 296: ...as been granted access to the file by the security context MyContext If the user cannot be authenticated ColdFusion throws a SECURITY exception CFIMPERSONATE SECURITYCONTEXT MyContext USERNAME pfoley...

Page 297: ...ious page it prompts the user to provide a username and password The user s response is checked against the list of valid users defined for the current security context If the user passes the authenti...

Page 298: ...me TD TD INPUT TYPE text NAME username TD TR TR TD password TD TD INPUT TYPE password NAME password TD TR TABLE INPUT TYPE submit VALUE Login FORM CFOUTPUT CFABORT CFIF CFIF Checking for authenticatio...

Page 299: ...SERT INTO Orders Customer OrderID VALUES CFOUTPUT Customer OrderID CFOUTPUT CFQUERY CFOUTPUT QUERY AddItem Authorization Succeeded Order information added Customer OrderID BR CFOUTPUT CFELSE CFABORT S...

Page 300: ...274 Developing Web Applications with ColdFusion...

Page 301: ...ColdFusion functions While this chapter documents custom tag development using Microsoft Visual C or Java it is currently also possible to develop them in Inprise s Delphi Contents What Are CFX Tags 2...

Page 302: ...ava Then to be able to use the CFX you have to register it in the ColdFusion Administrator Before You Begin Developing CFX Tags in C Sample C CFXs Before you begin development of a CFX tag in C you ma...

Page 303: ...custom tag 4 You can optionally add text that will appear as comments in the tag s code 5 Select an MFC usage option and click Finish to generate the code 6 In Visual C select Build Build CFX_MyNewTag...

Page 304: ...ore you can set breakpoints in your code Before You Begin Developing CFX Tags in Java Because the methods and syntax are similar if you are familiar with creating CFXs using C you will be productive c...

Page 305: ...asses Consult your Java development tool s documentation to determine how to configure the compiler class path for your particular environment The classes directory created by the ColdFusion setup pro...

Page 306: ...will only work if the java compiler javac exe is in your path If it is not in your path specify the fully qualified path for example c jdk12 bin javac on Windows NT or usr java bin javac on Solaris If...

Page 307: ...buteExists Checks if the attribute was passed to this tag getAttribute Retrieves the value of the passed attribute getIntAttribute Retrieves the value of the passed attribute as an integer getAttribut...

Page 308: ...ver this behavior can cause subtle problems when attempting to perform casts on instances of classes loaded from a different ClassLoader The cast will fail even though the objects are apparently of th...

Page 309: ...FX class files have changed performance may decrease slightly Therefore when you move from development into deployment Allaire ecommends that you globally disable automatic class reloading You can do...

Page 310: ...ser using the appropriate URL for example http localhost cfdocs testjavacfx cfm ColdFusion processes the template and returns a page that displays the text Hello Robert If an error is returned instead...

Page 311: ...values String strArchive request getAttribute ARCHIVE String strName request getAttribute NAME create a query to use for returning the list of files String columns Name Size Compressed int iName 1 iS...

Page 312: ...ebugging technology to be brought to the platform If you need to debug a Java CFX while running against a live production server this is the technique you must use In addition to simply outputting deb...

Page 313: ...4 Call the DebugResponse printResults method to output the results of the request including content generated variables set queries created and so forth Once you have implemented a main method as desc...

Page 314: ...The specific constructors and methods supported by the DebugRequest DebugResponse and DebugQuery classes are as follows Note that these classes also support the other methods of the Request Response...

Page 315: ...o the main procedure of a custom tag The methods available from the request object allow the custom tag to accomplish its work See the C CFX Reference on page 293 for a detailed description of the CFX...

Page 316: ...plate To register a Java 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 C...

Page 317: ...rforms the same function on UNIX Registration Entries for C CFXs Entry Value Hive HKEY_LOCAL_MACHINE Key SOFTWARE Allaire ColdFusion CurrentVersion Cust omTags TagName LibraryPath The full path to the...

Page 318: ...CFX tag CacheLibrary 1 2 In the install script import the registry entry by including the following command in the install script regedit importfilename To import a Java custom tag 1 Export the custo...

Page 319: ...CFXQuery SetData CCFXQuery SetQueryString CCFXQuery SetTotalTime CCFXRequest Class CCFXRequest AddQuery CCFXRequest AttributeExists CCFXRequest CreateStringSet CCFXRequest Debug CCFXRequest GetAttribu...

Page 320: ...al LPCSTR GetDiagnostic The CCFXException GetDiagnostics function returns detailed error information CCFXException GetError This function provides basic user output for exception that occur during pro...

Page 321: ...al CCFXStringSet GetColumns CCFXQuery GetColumns retrieves a list of the query s column names virtual LPCSTR GetData int iRow int iColumn CCFXQuery GetData retrieves a data element from a row and colu...

Page 322: ...ry SetData iRow iZip 55105 CCFXQuery GetColumns CCFXStringSet CCFXQuery GetColumns void Retrieves a list of the column names contained in the query Returns an object of CCFXStringSet Class that contai...

Page 323: ...lumn to retrieve data from 1 based Example The following example iterates over the elements of a query and writes the data in the query back to the user in a simple space delimited format int iRow iCo...

Page 324: ...and column of the query Row and column indexes begin with 1 Before calling SetData for a given row you should be sure to call CCFXQuery AddRow and use the return value as the row index for your call...

Page 325: ...tag virtual LPCSTR GetAttribute LPCSTR lpszName CCFXRequest GetAttribute retrieves the value of the passed attribute virtual CCFXStringSet GetAttributeList CCFXRequest GetAttributeList retrieves a li...

Page 326: ...zName CCFXStringSet pColumns Adds a query to the calling template This query can then be accessed by CFML tags for example CFOUTPUT or CFTABLE within the template Note that after calling AddQuery the...

Page 327: ...named DESTINATION to the tag and throws an exception if the attribute was not passed if pRequest AttributeExists DESTINATION FALSE pRequest ThrowException Missing DESTINATION parameter You must pass a...

Page 328: ...d attribute Returns an empty string if the attribute does not exist Use CCFXRequest AttributeExists to test whether an attribute was passed to the tag Returns the value of the attribute passed to the...

Page 329: ...CFXRequest GetCustomData LPVOID CCFXRequest GetCustomData void Gets the custom tag specific data for the request This member is typically used from within subroutines of your tag implementation to ext...

Page 330: ...ork correctly CCFXRequest GetSetting LPCSTR CCFXRequest GetSetting LPCSTR lpszSettingName Retrieves the value of a global custom tag setting Custom tag settings are stored within the CustomTags sectio...

Page 331: ...ate resource cleanup here Re throw the exception pRequest ReThrowException e catch Something nasty happened pRequest ThrowException Unexpected error occurred in CFX tag CCFXRequest SetCustomData void...

Page 332: ...nner as other template variables e g MessageSent lpszName Name of variable lpszValue Value of variable Example The following example sets the value of a variable named MessageSent based on the success...

Page 333: ...eption Error occurred buffError CCFXRequest Write void CCFXRequest Write LPCSTR lpszOutput Writes text output back to the user lpszOutput Text to output Example The following example creates a buffer...

Page 334: ...end of the list virtual int GetCount CCFXStringSet GetCount gets the number of strings contained in the list virtual LPCSTR GetString int iIndex CCFXStringSet GetString gets the string located at the...

Page 335: ...mItems pStringSet GetCount for int i 1 i nNumItems i pRequest Write pStringSet GetString i pRequest Write BR CCFXStringSet GetIndexForString int CCFXStringSet GetIndexForString LPCSTR lpszString Does...

Page 336: ...are 1 based Returns the string located at the passed index iIndex Index of string to retrieve Example The following example demonstrates using GetString along with CCFXStringSet GetCount to iterate o...

Page 337: ...following CFML code could be used to call the MyCustomTag processRequest method CFX_MyCustomTag Additional attributes may also be passed to the Java CFX tag The values of these attributes are availabl...

Page 338: ...ing example retrieves the name of the query and writes it back to the user Query query request getQuery response write The query name is query getName Method Summary int addRow Adds a new row to the q...

Page 339: ...int getColumnIndex String name Retrieves the index of a column given its name The following example retrieves the index of the EMAIL column and uses it to output a list of the addresses contained in t...

Page 340: ...etData int iRow int iCol throws IndexOutOfBoundsException 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 qu...

Page 341: ...Row iState MN query setData iRow iZip 55345 Second row iRow query addRow query setData iRow iCity St Paul query setData iRow iState MN query setData iRow iZip 55105 Returns The index of the row that w...

Page 342: ...based data New value for data element Throws IndexOutOfBoundsException If an invalid index is passed to the method See Also getData addRow Interface Request public abstract interface Request Interfac...

Page 343: ...correctly Parameters name Name of the attribute to check case insenstive Returns Returns true if the attribute is available otherwise returns false See Also getAttribute getAttributeList String getAtt...

Page 344: ...then an empty string is returned See Also attributeExists getAttributeList getAttribute String String getIntAttribute getIntAttribute public int getIntAttribute String name throws NumberFormatExcepti...

Page 345: ...i String strName attribs i String strValue request getAttribute strName response write strName strValue BR Returns An array of strings containing the names of the attributes passed to the tag See Als...

Page 346: ...ow retrieves the value of a setting named VerifyAddress for a CustomTag class named MyCustomTag String strVerify request getSetting MyCustomTag VerifyAddress if Boolean valueOf strVerify Do address ve...

Page 347: ...write String output Outputs text back to the user The following example outputs the value of the DESTINATION attribute response write DESTINATION request getAttribute DESTINATION Parameters output Tex...

Page 348: ...xception If the name parameter is not a valid CFML variable name addQuery public Query addQuery String name String columns throws IllegalArgumentException Adds a query to the calling template This que...

Page 349: ...xception if the name parameter is not a valid CFML variable name See Also Query addRow Query setData writeDebug public void writeDebug String output Writes text output into the debug stream This text...

Page 350: ...324 Developing Web Applications with ColdFusion...

Page 351: ...ects created by component technologies This includes COM DCOM CORBA Java and EJB objects Contents Component Object Overview 326 Invoking Component Objects 327 Getting Started with COM DCOM 328 Creatin...

Page 352: ...3 51 4 0 and Windows 95 98 Resources To find out more about COM DCOM go to Microsoft s COM site About CORBA CORBA Common Object Request Broker Architecture is a specification for a distributed compon...

Page 353: ...e To get a property CFSET value obj property Note that parentheses are not used on the right side of the equation for property gets Calling methods Object methods usually take zero or more arguments A...

Page 354: ...dow for the component might appear on the Web server desktop not on the user s desktop This could tie up ColdFusion server threads and result in further Web server requests not being serviced ColdFusi...

Page 355: ...y to work with the CFOBJECT tag If you don t have documentation use the Object Viewer to view the component s interface Using the OLE COM Object Viewer The OLE COM Object Viewer installation installs...

Page 356: ...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 methods and properties Some obje...

Page 357: ...you want to send The SMTP Mailer component also includes a number of methods such as SendMail AddRecipient AddCC AddAttachment Connecting to COM objects There are essentially two ways specified with...

Page 358: ...fromname CFSET Mailer RemoteHost RemoteHost CFSET Mailer FromAddress form fromemail CFSET Mailer Subject Testing CFOBJECT CFSET Mailer BodyText form msgbody CFSET Mailer SMTPLog logfile Last use the...

Page 359: ...sion of the IOR ColdFusion must be able to read this IOR file at all times so it should be local to the server or on the network in an accessible location If the CONTEXT attribute is set to a NameServ...

Page 360: ...ert x l 256 CFSET temp StructInsert x d 93 45 CFIF CFSET NestedStruct StructNew CFIF IsStruct xx CFSET temp StructInsert NestedStruct f x CFSET temp StructInsert NestedStruct c b CFSET temp StructInse...

Page 361: ...n they are received as return values Calling EJBs To call an EJB you use CFOBJECT to create and call all the appropriate objects In the following example it is assumed that the Weblogic JNDI is used t...

Page 362: ...336 Developing Web Applications with ColdFusion...

Page 363: ...guage CFScript that provides ColdFusion functionality in script syntax This JavaScript like language gives developers the same control flow but without tags This chapter describes the CFScript languag...

Page 364: ...name FORM firstname CFSET employee lastname FORM lastname CFSET employee email FORM email CFSET employee phone FORM phone CFSET employee department FORM department CFOUTPUT About to add FORM firstname...

Page 365: ...tax of the CFScript language Statements Note that in CFScript semicolons define the end of a statement Line breaks in your source are insignificant You can enclose multiple statements in curly braces...

Page 366: ...ion for example A LT 5 loop LE x or Y EQ not found AND loop LT end empty Here are some examples of for loops Multiline for statement for Loop1 1 Loop1 LT 10 Loop1 Loop1 1 a loop1 loop1 Complete for lo...

Page 367: ...st be a constant i e not a variable a function or other expression Only one default statement is allowed There can be multiple case statements You cannot mix Boolean and numeric case values in a switc...

Page 368: ...FScript Variables Variables can be of any ColdFusion type such as numbers strings arrays queries and COM objects You can read and write variables within the script region Comments Comments in CFScript...

Page 369: ...ssions such as NOT AND IS and so on the following words are reserved in CFScript Do not use these words as variables or identifiers in your scripting code for while do if else switch case break defaul...

Page 370: ...ldFusion CFOUTPUT QUERY employees CFSCRIPT testres is a column in the employees query if testres EQ 1 result positive else result negative CFSCRIPT The variable result takes its value from the script...

Page 371: ...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 346 Setting Registry Va...

Page 372: ...RY with the GETaction to retrieve one entry or the GETALL action to retrieve multiple keys and values from the registry Getting all keys and values Use CFREGISTRY with the GETALL action to return all...

Page 373: ...tion specifying the branch the entry to be accessed the type optional and a variable in which to return the value CFREGISTRY ACTION Get BRANCH HKEY_LOCAL_MACHINE Software Microsoft Java VM ENTRY Class...

Page 374: ...You can use CFREGISTRY with the DELETE action to delete registry keys and values Note Be careful when using the DELETE action if you delete a key CFREGISTRY also deletes all values and subkeys define...

Page 375: ...ociative 113 creating 105 dimensions 105 elements 105 functions 111 index of 105 multidimensional 106 populating 108 referencing elements in 107 resizing 106 Attaching MIME files 210 Attribute values...

Page 376: ...91 Class loading 282 Class path 326 configuring 279 Classes debugging 286 Client state management 184 clustering 190 enabling 188 using 190 Client variables 191 creating 191 deleting 192 lists of 192...

Page 377: ...results 25 37 text 12 variables 12 Distinguished name 251 Distributing CFXs 291 Documentation conventions xxiv Double quotes 51 Drop down list boxes 143 populating 144 Dynamic parameters SQL 53 Dynami...

Page 378: ...ting data 61 Invoking component objects 327 methods in CFOBJECT 332 IsAuthenticated function 267 IsAuthorized function 267 IsDefined 51 J Java 242 Java applets 125 embedding 146 embedding in forms 144...

Page 379: ...eset buttons 31 Response object 280 Retrieving binary files 232 files 239 text 232 Reusing code 72 custom tags 73 Rows in tables 16 S Sample CFXs 276 278 Saving binary files 233 Web pages 233 Schema L...

Page 380: ...eadings 234 creating queries from 234 delimiters 234 Time zone processing 243 Transactions secure 238 Transferring data from browser to server 246 Tree controls structuring 132 Troubleshooting 91 U UP...

Reviews: