MACROMEDIA COLDFUSION MX 61-DEVELOPING COLDFUSION MX Applications

Summary of COLDFUSION MX 61-DEVELOPING COLDFUSION MX

  • Page 1

    Developing coldfusion mx applications.

  • Page 2

    Trademarks afterburner, appletace, attain, attain enterprise learning system, attain essentials, attain objects for dreamweaver, authorware, authorware attain, authorware interactive studio, authorware star, authorware synergy, backstage, backstage designer, backstage desktop studio, backstage enter...

  • Page 3: Contents

    3 contents introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 using this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 about macromedia coldfusion mx documentation . . . ....

  • Page 4

    4 contents data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 coldfusion components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 cfscript . . . . . . . . . . . . . . . . . . . . . ....

  • Page 5

    Contents 5 chapter 4: using expressions and pound signs . . . . . . . . . . . . . . . . . . . . . . . . 83 expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 operator types . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 6

    6 contents chapter 6: extending coldfusion pages with cfml scripting . . . . . . . . . . . . 127 about cfscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 comparing tags and cfscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 7

    Contents 7 part ii: reusing cfml code chapter 8: reusing code in coldfusion pages . . . . . . . . . . . . . . . . . . . . . . . . 163 about reusable cfml elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 including pages with the cfinclude tag. . . . . . . . . . ....

  • Page 8

    8 contents chapter 10: writing and calling user-defined functions . . . . . . . . . . . . . . . . 191 about user-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 calling user-defined functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 9

    Contents 9 chapter 12: building custom cfxapi tags . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 what are cfx tags?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 before you begin developing cfx tags in java . . . . . . . . . . . . . . . ...

  • Page 10

    10 contents optimizing coldfusion applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 caching coldfusion pages that change infrequently. . . . . . . . . . . . . . . . . . . . 277 caching parts of coldfusion pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 11

    Contents 11 accessing and changing session variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 ending a session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 configuring and using application variables . . . . . . . . . . . . . ....

  • Page 12

    12 contents processing a request in coldfusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 determining the character encoding of a coldfusion page. . . . . . . . . . . . . . . 378 determining the page encoding of server output . . . . . . . . . . . . . . . . . . . . . ....

  • Page 13

    Contents 13 part iv: accessing and using data chapter 19: introduction to databases and sql . . . . . . . . . . . . . . . . . . . . . . . 411 what is a database? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412 using multiple database tables . . . . ....

  • Page 14

    14 contents chapter 22: using query of queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451 about record sets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452 referencing queries as objects . . . . . . . . . . . . . . . . . ....

  • Page 15

    Contents 15 chapter 24: building a search interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 about verity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 using verity with coldfusion . . . . . . . . . . . . . . . . . . ...

  • Page 16

    16 contents requiring users to enter values in form fields . . . . . . . . . . . . . . . . . . . . . . . . . 566 form variable notes and considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567 working with queries and data . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 17

    Contents 17 chapter 28: charting and graphing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617 creating a chart. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618 chart types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 18

    18 contents using the cf.Query function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658 about cf.Query function syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658 about the cf.Query record set . . . . . . . . . . . . . . . . . . . . ....

  • Page 19

    Contents 19 using wddx. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702 using the cfwddx tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702 validating wddx data . . . . . . . . . . . . . . . . . . . . ...

  • Page 20

    20 contents using jsp tags and tag libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739 using a jsp tag in a coldfusion page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739 example: using the random tag library . . . . . . . . . . . . . . . . . ...

  • Page 21

    Contents 21 part vii: using external resources chapter 35: sending and receiving e-mail . . . . . . . . . . . . . . . . . . . . . . . . . . 789 using coldfusion with mail servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790 sending e-mail messages . . . . . . . . . . . . ....

  • Page 22

    22 contents.

  • Page 23: Introduction

    23 introduction developing coldfusion mx applications provides the tools needed to develop internet applications using macromedia coldfusion mx. This book is intended for web application programmers who are learning coldfusion mx or wish to extended their coldfusion mx programming knowledge. It prov...

  • Page 24

    24 introduction using this book this book can to help anyone with a basic understanding of html learn to develop coldfusion. However, this book is most useful if you have basic coldfusion experience, or have read getting started building coldfusion mx applications. The getting started book provides ...

  • Page 25

    Using this book 25 beginning with coldfusion if you are learning coldfusion, a path such as the following might be most effective: 1 introduction to coldfusion mx through using expressions and pound signs to learn the basics of cfml. 2 introduction to databases and sql through updating your database...

  • Page 26

    Nearly all chapters contain information that is new in coldfusion mx, so you should also review all other chapters for useful information. The index and the table of contents are useful tools for finding new features or changed documentation. About macromedia coldfusion mx documentation the coldfusi...

  • Page 27: Chapter 1

    27 chapter 1 introduction to coldfusion mx this chapter describes macromedia coldfusion mx and the role it plays in internet applications, including macromedia flash mx based applications. This chapter also introduces the topics discussed in this book. Contents about internet applications and web ap...

  • Page 28

    Chapter 1: introduction to coldfusion mx about internet applications and web application servers with coldfusion mx, you develop internet applications that run on web application servers. The following sections introduce internet applications and web application servers. Later sections explain the s...

  • Page 29

    About internet applications and web application servers 29 to extend the capabilities of a web server, you use a web application server, a software program that extends the web server’s capabilities to do tasks such as those in the preceding list. How a web server and web application server work tog...

  • Page 30

    30 chapter 1: introduction to coldfusion mx about coldfusion mx coldfusion mx is a rapid scripting environment server for creating rich internet applications. Coldfusion markup language (cfml) is an easy-to-learn tag-based scripting language, with connectivity to enterprise data and powerful built-i...

  • Page 31

    About coldfusion mx 31 cfml includes approximately one hundred tags. Coldfusion tags serve many functions. They provide programming constructs, such as conditional processing and loop structures. They also provide services, such as charting and graphing, full-text search, access to protocols such as...

  • Page 32

    32 chapter 1: introduction to coldfusion mx server-side actionscript another feature of the coldfusion scripting environment is server-side actionscript. Actionscript is the javascript-based language used to write application logic in macromedia flash mx. By bringing this language to the server, col...

  • Page 33

    About j2ee and the coldfusion architecture 33 • flash mx development application debugger lets you trace your application logic as it executes between flash and coldfusion. • coldfusion mx server-side actionscript lets flash programmers familiar with actionscript create coldfusion services, such as ...

  • Page 34

    34 chapter 1: introduction to coldfusion mx coldfusion features described in this book coldfusion provides a comprehensive set of features for developing and managing internet applications. These features enhance speed and ease-of-development, and let you dynamically deploy your applications, integr...

  • Page 35

    Coldfusion features described in this book 35 application security coldfusion provides mechanisms, including the cflogin tag, for authenticating users and authorizing them to access specific sections of your application. You can also use resource security, which secures access to coldfusion resource...

  • Page 36

    36 chapter 1: introduction to coldfusion mx com and corba objects the cfobject tag lets you use com (component object model) or dcom (distributed component object model) and corba (common object request broker) objects in your coldfusion applications. 34 e-mail messages you can add interactive e-mai...

  • Page 37

    The cfml programming language this part describes the elements of the cfml programming language. It tells you how to use cfml tags, functions, variables and expressions, the cfscript scripting language, and regular expressions. The following chapters are included: chapter 2: elements of cfml . . . ....

  • Page 39: Chapter 2

    39 chapter 2 elements of cfml this chapter provides an overview of the basic elements of cfml, including tags, functions, constants, variables, expressions, and cfscript. The chapters in part i of this book describe these topics in detail. Contents introduction . . . . . . . . . . . . . . . . . . . ...

  • Page 40

    40 chapter 2: elements of cfml introduction this chapter introduces and describes the basic elements of cfml. These elements make cfml a powerful tool for developing interactive web applications. Because cfml is a dynamic application development tool, it has many of the features of a programming lan...

  • Page 41

    Tags 41 other tags, such as cfset and cfftp , never have bodies; all the required information goes between the beginning () character, as in the following example: sometimes, although the tag can have a body, you do not need to put anything in it because the attributes specify all the required infor...

  • Page 42

    42 chapter 2: elements of cfml cfml custom tags when you write a custom tag in cfml, you can take advantage of all the features of the coldfusion language, including all built-in tags and even other custom tags. Cfml custom tags can include body sections and end tags. Because they are written in cfm...

  • Page 43

    Expressions 43 you use built-in functions throughout coldfusion pages. Built-in functions are frequently used in a cfset or cfoutput tag to prepare data for display or further use. For example, the following line displays today’s date in the format october 12, 2001: #dateformat(now(), "mmmm d, yyyy"...

  • Page 44

    44 chapter 2: elements of cfml constants the value of a constant does not change during program execution. Constants are simple scalar values that you can use within expressions and functions, such as “robert trent jones” and 123.45. Constants can be integers, real numbers, time and date values, boo...

  • Page 45

    Data types 45 data types coldfusion is considered typeless because you do not explicitly specify variable data types. However, coldfusion data, the constants and the data that variables represent, do have data types, which correspond to the ways the data is stored on the computer. Coldfusion data be...

  • Page 46

    46 chapter 2: elements of cfml for more information on coldfusion data types, see chapter 3, “using coldfusion variables,” on page 53 . Coldfusion components coldfusion components encapsulate multiple, related, functions. A coldfusion component is essentially a set of related user-defined functions ...

  • Page 47

    Flow control 47 if(find("key",strings[i],1)) break; } entry #i# starts with "key" you use cfscript to create user-defined functions. For more information on cfscript, see chapter 6, “extending coldfusion pages with cfml scripting,” on page 127 . For more information on user-defined functions, see ch...

  • Page 48

    48 chapter 2: elements of cfml cfswitch, cfcase, and cfdefaultcase the cfswitch , cfcase , and cfdefaultcase tags let you select among different code blocks based on the value of an expression. Coldfusion processes these tags as follows: 1 the cfswitch tag evaluates an expression. The cfswitch tag b...

  • Page 49

    Flow control 49 the following example shows a simple index loop: the loop index is #loopcount#. The following example shows a simple conditional loop. The code does the following: 1 sets up a ten-element array with the word “kumquats” in the fourth entry. 2 loops through the array until it encounter...

  • Page 50

    50 chapter 2: elements of cfml cfabort and cfexit the cfabort tag stops processing of the current page at the location of the cfabort tag. Coldfusion returns to the user or calling tag everything that was processed before the cfabort tag. You can optionally specify an error message to display. You c...

  • Page 51

    Reserved words 51 the output looks like this: we all said "for he's a jolly good fellow." then we said "for she's a jolly good fellow." here is a pound sign: # reserved words as with any programming tool, you cannot use just any word or name for coldfusion variables, udfs and custom tags. You must a...

  • Page 52

    52 chapter 2: elements of cfml.

  • Page 53: Chapter 3

    53 chapter 3 using coldfusion variables macromedia coldfusion variables are the most frequently used operands in coldfusion expressions. Variable values can be set and reset, and can be passed as attributes to cfml tags. Variables can be passed as parameters to functions, and can replace most consta...

  • Page 54

    54 chapter 3: using coldfusion variables creating variables you create most coldfusion variables by assigning them values. (you must use the arraynew function to create arrays.) most commonly, you create variables by using the cfset tag. You can also use the cfparam tag, and assignment statements in...

  • Page 55

    Data types 55 variable characteristics you can classify a variable using the following characteristics: • the data type of the variable value, which indicates the kind of information a variable represents, such as number, string, or date • the scope of the variable, which indicates where the informa...

  • Page 56

    56 chapter 3: using coldfusion variables data type notes although coldfusion variables do not have types, it is often convenient to use “variable type” as a shorthand for the type of data that the variable represents. Coldfusion can validate the type of data contained in form fields and query parame...

  • Page 57

    Strings 57 real numbers real numbers, numbers with a decimal part, are also known as floating point numbers. Coldfusion real numbers can range from approximately -10 300 to approximately 10 300 . A real number can have up to 12 significant digits. As with integers, you can assign a variable a value ...

  • Page 58

    58 chapter 3: using coldfusion variables to insert a pound sign in a string, you must escape the pound sign, as follows: "this is a pound sign ##" lists coldfusion includes functions that operate on lists, but it does not have a list data type. In coldfusion, a list is just a string that consists of...

  • Page 59

    Strings 59 when you do this, coldfusion stores the information as a string. If you use a date-time function, coldfusion stores the value as a date-time object, which is a separate simple data type. When possible, use date-time functions such as createdate and createtime to specify dates and times, b...

  • Page 60

    60 chapter 3: using coldfusion variables how coldfusion stores dates and times coldfusion stores and manipulates dates and times as date-time objects. Date-time objects store data on a time line as real numbers. This storage method increases processing efficiency and directly mimics the method used ...

  • Page 61

    Strings 61 complex data types arrays, structures, and queries are coldfusion built-in complex data types. Structures and queries are sometimes referred to as objects, because they are containers for data, not individual data values. For details on using arrays and structures, see chapter 5, “using a...

  • Page 62

    62 chapter 3: using coldfusion variables you can use either of the following methods to reference elements stored in a structure: • structurename.Keyname • structurename["keyname"] the following examples show these methods: depts.John="sales" depts["john"]="sales" when you assign an existing structu...

  • Page 63

    Strings 63 when you reference query columns inside tags, such as cfoutput and cfloop , in which you specify the query name in a tag attribute, you do not have to specify the query name. You can access query columns as if they are one-dimensional arrays. For example, the following line assigns the co...

  • Page 64

    64 chapter 3: using coldfusion variables using a query column when you are not inside a cfloop , cfoutput , or cfmail tag that has a query attribute, you can treat a query column as an array. However, query column references do not always behave as you might expect. This section explains the behavio...

  • Page 65

    Using periods in variable references 65 with the exception of cookie and client scope variables, which must always be simple variable types, you cannot normally include periods in simple variable names. However, coldfusion makes some exceptions that accommodate legacy and third-party code that does ...

  • Page 66

    66 chapter 3: using coldfusion variables for example, assume you have the following code: if a variable myvar does not exist, it does the following: 1 creates a structure named myvar. 2 creates a structure named a in the structure myvar. 3 creates a key named b in myvar.A. 4 gives it the value "this...

  • Page 67

    Data type conversion 67 creating client and cookie variables with periods to create a client or cookie variable with a name that includes one or more periods, simply assign the variable a value. For example, the following line creates a cookie named user.Preferences.Creditcard: data type conversion ...

  • Page 68

    68 chapter 3: using coldfusion variables the following table explains how conversions are performed. The first column shows values to convert. The remaining columns show the result of conversion to the listed data type. Coldfusion cannot convert complex types, such as arrays, queries, and com object...

  • Page 69

    Data type conversion 69 converting binary data coldfusion cannot automatically convert binary data to other data types. To convert binary data, use the tobase64 and tostring functions. For more information, see “binary data type and base64 encoding” on page 60 . Converting date and time data to ensu...

  • Page 70

    70 chapter 3: using coldfusion variables however, if myvariable has a numeric value such as 12, only the first example produces a result. In the second case, the value of myvariable is not converted to a boolean data type, because the is operator does not require a specific data type and just tests ...

  • Page 71

    Data type conversion 71 if you use sql to insert data into a database or in a where clause to select data from a database, and the database driver does not support odbc-formatted dates, use the dateformat function to convert the date-time value to a valid format for the driver. This rule also applie...

  • Page 72

    72 chapter 3: using coldfusion variables example 2 true and 2 * 3 result value as string: "yes" explanation: 6 is converted to boolean true because it is nonzero; true and true is true. Example 3 "five is " & 5 result value as string: "five is 5" explanation: 5 is converted to the string "5". Exampl...

  • Page 73

    About scopes 73 url contains parameters passed to the current page in the url that is used to call it. The parameters are appended to the url in the format ?Variablename = value[&variablename=value...]; for example www.Mycompany.Com/ inputpage.Cfm?Productcode=a12cd1510& quantity=3. Note: if a url in...

  • Page 74

    74 chapter 3: using coldfusion variables caution: to prevent data corruption, you lock code that uses session, application, or server scope variables. For more information, see chapter 15, “using persistent data and locking,” on page 315 . Session contains variables that are associated with one clie...

  • Page 75

    About scopes 75 creating and using variables in scopes the following table shows how you create and refer to variables in different scopes in your code. For more information on the mechanisms for creating variables in most scopes, see “creating variables” on page 54 . Scope prefix (type) prefix requ...

  • Page 76

    76 chapter 3: using coldfusion variables cffile yes following an invocation of cffile . A cffile tag. Cookie no for one client in one or more applications and pages, over multiple browser sessions. A cfcookie tag. You can also set memory-only cookies by specifying the prefix cookie when you create t...

  • Page 77

    About scopes 77 using scopes the following sections provide details on how you can create and use variables in different scopes. Evaluating unscoped variables if you use a variable name without a scope prefix, coldfusion checks the scopes in the following order to find the variable: 1 arguments 2 va...

  • Page 78

    78 chapter 3: using coldfusion variables caution: do not call structclear (session) to clear session variables. This deletes the sessionid , cfid , and cftoken built-in variables, effectively ending the session. If you want to use structclear to delete your application variables, put those variables...

  • Page 79

    Ensuring variable existence 79 • you can use a cfform input tag with a hidden attribute to tell coldfusion to display a helpful message to any user who does not enter data in a required field. For more information on this technique, see chapter 26, “requiring users to enter values in form fields,” o...

  • Page 80

    80 chapter 3: using coldfusion variables • with only the name attribute to test that a required variable exists. If it does not exist, the coldfusion server stops processing the page and displays an error message. • with the name and default attributes to test for the existence of an optional variab...

  • Page 81

    Validating data types 81 • use the cfqueryparam tag in a sql where clause to validate query parameters. For information on this technique, see chapter 20, “using cfqueryparam,” on page 435 . Note: data validation using the cfparam, cfqueryparam, and form tags is done by the server. Validation using ...

  • Page 82

    82 chapter 3: using coldfusion variables passing variables to custom tags and udfs the following sections describe rules for how data gets passed to custom tags and user-defined functions that are written in cfml, and to cfx custom tags that are written in java or c++. Passing variables to cfml tags...

  • Page 83: Chapter 4

    83 chapter 4 using expressions and pound signs this chapter discusses how to use expressions in cfml. It discusses the elements of coldfusion expressions and how to create expressions. It also describes the correct use of pound signs to indicate expressions in coldfusion tags such as cfoutput , in s...

  • Page 84

    84 chapter 4: using expressions and pound signs expressions coldfusion expressions consist of operands andoperators. Operands are comprised of constants and variables. Operators, such as the multiplication symbol, are the verbs that act on the operands; functions are a form of operator. The simplest...

  • Page 85

    Expressions 85 boolean operators boolean, or logical, operators perform logical connective and negation operations. The operands of boolean operators are boolean (true/false) values.The following table describes the boolean operators: decision operators the coldfusion decision, or comparison, operat...

  • Page 86

    86 chapter 4: using expressions and pound signs alternative notation for decision operators you can replace some decision operators with alternative notations to make your cfml more compact, as shown in the following table: decision operator rules the following rules apply to decision operators: • w...

  • Page 87

    Expressions 87 string operators there is one string operator, which is the concatenation operator. Operator precedence and evaluation ordering the order of precedence controls the order in which operators in an expression are evaluated. The order of precedence is as follows: unary +, unary - ^ *, / ...

  • Page 88

    88 chapter 4: using expressions and pound signs function syntax the following table shows function syntax and usage guidelines: all functions return values. In the following example, the cfset tag sets a variable to the value returned by the now function: you can use the values returned by functions...

  • Page 89

    Using pound signs 89 5 executes the ucase function on the string argument "we all need more sleep!" to get "we all need more sleep!". 6 assigns the string value "we all need more sleep!" to the variable mystringvar. Coldfusion completes steps 1-3 before invoking the function. Using pound signs pound...

  • Page 90

    90 chapter 4: using expressions and pound signs note: you do not need to use pound signs when you use the cfset tag to assign one variable’s value to another value. For example, the following tag assigns the value of the oldvar variable to the new variable, newvar: . Using pound signs in tag bodies ...

  • Page 91

    Using pound signs 91 as with the cfoutput statement, two expressions can be adjacent to each other in strings, as in the following example: the double quotes around "moon" and "monkey" do not need to be escaped (as in ""moon"" and ""monkey""). This is because the text between the pound signs is trea...

  • Page 92

    92 chapter 4: using expressions and pound signs dynamic expressions and dynamic variables this section discusses the advanced topics of dynamic expressions, dynamic evaluation, and dynamic variable naming. Many coldfusion programmers never encounter or need to use dynamic expressions. However, dynam...

  • Page 93

    Dynamic expressions and dynamic variables 93 selecting how to create variable names the following two examples describes cases when you need dynamic variable names: • form applications where the number and names of fields on the form vary dynamically. In this case, the form posts only the names and ...

  • Page 94

    94 chapter 4: using expressions and pound signs dynamic variable limitation when you use a dynamic variable name in quotes on the left side of an assignment, the name must be either a simple variable name or a complex name that uses object.Property notation (such as mystruct.#keyname#). You cannot u...

  • Page 95

    Dynamic expressions and dynamic variables 95 function argument evaluation considerations it is important to remember that coldfusion always evaluates function arguments before the argument values are passed to a function: for example, consider the following de function: #de("1" & "2")# you might exp...

  • Page 96

    96 chapter 4: using expressions and pound signs reviewing the code the following table describes how coldfusion processes this code: as you can see, using dynamic expressions can result in substantial expression evaluation overhead, and the code can be confusing. Therefore, you should avoid using dy...

  • Page 97

    Dynamic expressions and dynamic variables 97 example 2 this example shows how you can use an associative array reference in place of an evaluate function. This technique is powerful because: • most coldfusion scopes are accessible as structures. • you can use coldfusion expressions in the indexes of...

  • Page 98

    98 chapter 4: using expressions and pound signs in the second line, enclosing the myvar#i# variable name in quotation marks tells coldfusion to evaluate the name and process any text in pound signs as a variable or function. Coldfusion replaces the #i# with the value of the variable i, so that if th...

  • Page 99

    Dynamic expressions and dynamic variables 99 hello #i# example: a dynamic shopping cart the following example dynamically creates and manipulates variable names without using dynamic expression evaluation by using associative array notation. You need to dynamically generate variable names in applica...

  • Page 100

    100 chapter 4: using expressions and pound signs checked> passthrough = "readonly = 'true'"> passthrough = "readonly = 'true'"> 2 save the page as shoppingcartform.Cfm. Reviewing the code the following table describes the code: code description cartitems=4; cart = arraynew(1); for ( i=1; i le #carti...

  • Page 101

    Dynamic expressions and dynamic variables 101 to create the action page: 1 create a file in your editor. 2 enter the following text: you have ordered the following items: productname: #form["product_" & i]# product code: #form["sku_" & i]# quantity: #form["qty_" & i]# 3 save the file as shoppingcart...

  • Page 102

    102 chapter 4: using expressions and pound signs reviewing the code the following table describes the code: code description run the cfml on this page only if it is called by submitting a form. This is not needed if there are separate form and action pages, but is required if the form and action pag...

  • Page 103: Chapter 5

    103 chapter 5 using arrays and structures coldfusion supports dynamic multidimensional arrays. This chapter explains the basics of creating and handling arrays. It also provides several examples showing how arrays can enhance your coldfusion application code. Coldfusion also supports structures for ...

  • Page 104

    104 chapter 5: using arrays and structures about arrays traditionally, an array is a tabular structure used to hold data, much like a spreadsheet table with clearly defined limits and dimensions. In coldfusion, you typically use arrays to temporarily store data. For example, if your site lets users ...

  • Page 105

    About arrays 105 a conventional 2d array is like a fixed-size table made up of individual cells, as the following figure shows: the following figure represents a coldfusion 2d array: a coldfusion 2d array is actually a one-dimensional array that contains a series of additional 1d arrays. Each of the...

  • Page 106

    106 chapter 5: using arrays and structures basic array techniques the following sections describe how to reference array elements, create arrays, add and remove array elements, and copy arrays. Referencing array elements you reference array elements by enclosing the index with brackets: arrayname[x]...

  • Page 107

    Basic array techniques 107 the best way to understand an asymmetrical array is by looking at it. The following example creates an asymmetric, multidimensional array and the cfdump tag displays the resulting array structure. Several array elements do not yet contain data. Note: the cfdump tag display...

  • Page 108

    108 chapter 5: using arrays and structures adding elements to an array you can add an element to an array by assigning the element a value or by using a coldfusion function. Adding an array element by assignment you can add elements to an array by defining the value of an array element, as shown in ...

  • Page 109

    Basic array techniques 109 for more information about these array functions, see cfml reference. Deleting elements from an array use the arraydeleteat function to delete data from the array at a particular index, instead of setting the data value to zero or an empty string. If you remove data from a...

  • Page 110

    110 chapter 5: using arrays and structures change the values in the new array. Contents of the original array after the changes: contents of the new array after the changes: the change to the new array also changes the contents of the structure in the original array. To make a complete copy of an ar...

  • Page 111

    Populating arrays with data 111 #months[loopcount]# using nested loops for 2d and 3d arrays to output values from 2d and 3d arrays, you must employ nested loops to return array data. With a one-dimensional (1d) array, a single cfloop is sufficient to output data, as in the previous example. With arr...

  • Page 112

    112 chapter 5: using arrays and structures populating an array from a query when populating an array from a query, keep the following things in mind: • you cannot add query data to an array all at once. A looping structure is generally required to populate an array from a query. • you can reference ...

  • Page 113

    About structures 113 array functions the following functions are available for creating, editing, and handling arrays: for more information about each of these functions, see cfml reference. About structures coldfusion structures consist of key-value pairs. Structures let you build a collection of r...

  • Page 114

    114 chapter 5: using arrays and structures a structure’s key must be a string. The values associated with the key can be any valid coldfusion value or object. It can be a string or integer, or a complex object such as an array or another structure. Because structures can contain any kind of data the...

  • Page 115

    About structures 115 value of the first key #mystruct.Key1# #mystruct["key1"]# #mystruct[key1var]# value of the second entry in the key2 array #mystruct.Key2[2]# #mystruct["key2"][2]# #mystruct[key2var][2]# #mystruct[key2var][var2]# value of the struct2key2 entry in the key3 structure #mystruct.Key3...

  • Page 116

    116 chapter 5: using arrays and structures creating and using structures this section explains how to create and use structures in coldfusion. The sample code in this section uses a structure called employee, which is used to add new employees to a corporate information system. Creating structures y...

  • Page 117

    Creating and using structures 117 adding data elements to structures you add an element to a structure by assigning the element a value or by using a coldfusion function. It is cleaner and more efficient to use direct assignment, so only this technique is described. You add structure key-value pairs...

  • Page 118

    118 chapter 5: using arrays and structures to discover whether a specific structure contains data, use the structisempty function, as follows: structisempty(structure_name) this function returns true if the structure is empty, and false if it contains data. Finding a specific key and its value to de...

  • Page 119

    Creating and using structures 119 copying structures coldfusion provides several ways to copy structures and create structure references. The following table lists these methods and describes their uses: the following example shows the different effects of copying, duplicating, and assigning structu...

  • Page 120

    120 chapter 5: using arrays and structures change a string, array element, and structure value in the structcopy copy. Original structure copied structure duplicated structure structure reference change a string, array element, and structure value in the duplicate original structure copied structure...

  • Page 121

    Creating and using structures 121 deleting structure elements and structures to delete a key and its value from a structure, use the structdelete function, as follows: structdelete(structure_name, key [, indicatenotexisting ]) the indicatenotexisting argument tells the function what to do if the spe...

  • Page 122

    122 chapter 5: using arrays and structures structure example structures are particularly useful for grouping together a set of variables under a single name. The example in this section uses structures to collect information from a form, and to submit that information to a custom tag, named cf_addem...

  • Page 123

    Structure example 123 last name: email: phone: department: reviewing the code the following table describes the code: code description set default values of all form fields so that they exist the first time this page is displayed and can be tested. Please fill out the form. Test the value of the for...

  • Page 124

    124 chapter 5: using arrays and structures example file addemployee.Cfm the following file is an example of a custom tag used to add employees. Employee information is passed through the employee structure (the empinfo attribute). For databases that do not support automatic key generation, you must ...

  • Page 125

    Structure functions 125 reviewing the code the following table describes the code: structure functions you can use the following functions to create and manage structures in coldfusion applications. The table describes each function’s purpose and provides specific, but limited, information that can ...

  • Page 126

    126 chapter 5: using arrays and structures all functions except structdelete throw an exception if a referenced key or structure does not exist. For more information on these functions, see cfml reference. Structfindvalue searches through a structure for the specified simple data value (for example,...

  • Page 127: Chapter 6

    127 chapter 6 extending coldfusion pages with cfml scripting coldfusion mx offers a server-side scripting language, cfscript, that provides coldfusion functionality in script syntax. This javascript-like language gives developers the same control flow as coldfusion, but without tags. You can also us...

  • Page 128

    128 chapter 6: extending coldfusion pages with cfml scripting about cfscript cfscript is a language within a language. It is a scripting language that is similar to javascript but is simpler to use. Also, unlike javascript, cfscript only runs on the coldfusion server; it does not run on the client s...

  • Page 129

    The cfscript language 129 using cfscript if (isdefined("form.Submit")) { if ((form.Lastname neq "") and (form.Department neq "")) { employee=structnew(); employee.Firstname=form.Firstname; employee.Lastname=form.Lastname; employee.Email=form.Email; employee.Phone=form.Phone; employee.Department=form...

  • Page 130

    130 chapter 6: extending coldfusion pages with cfml scripting the following rules apply to statements: • you must put a semicolon at the end of a statement. • line breaks are ignored. A single statement can cross multiple lines. • white space is ignored. For example, it does not matter whether you p...

  • Page 131

    The cfscript language 131 • the end of a multiline comment can be followed on the same line by active code. For example, the following line is valid, although it is poor coding practice: end of my long comment */ foo = "bar"; • you can use multiline format for a comment on a single line, for example...

  • Page 132

    132 chapter 6: extending coldfusion pages with cfml scripting using cfscript statements the following sections describe how to use these cfscript statements: • assignment statements and functions • conditional processing statements • looping statements using assignment statements and functions cfscr...

  • Page 133

    Using cfscript statements 133 using if and else statements the if and else statements have the following syntax: if(expr) statement [else statement] in its simplest form, an if statement looks like this: if(value eq 2700) message = "you’ve reached the maximum"; a simple if-else statement looks like ...

  • Page 134

    134 chapter 6: extending coldfusion pages with cfml scripting • the statements following the colon in a case statement block do not have to be in braces. If a constant value equals the switch expression, coldfusion executes all statements through the break statement. • the break statement at the end...

  • Page 135

    Using cfscript statements 135 using for loops the for loop has the following format: for (initial-expression; test-expression; final-expression) statement the initial-expression and final-expression can be one of the following: • a single assignment expression; for example, x=5 or loop=loop+1 • any ...

  • Page 136

    136 chapter 6: extending coldfusion pages with cfml scripting if(find("key",strings[indx],1)) { writeoutput("found key at " & indx & "."); break; } else if (indx is arraylen(strings)) { writeoutput("exited at " & indx & "."); break; } } this example shows one important issue that you must remember w...

  • Page 137

    Using cfscript statements 137 the do while statement does the following: 1 executes the statement, which can be a single semicolon-terminated statement or a statement block in curly braces. 2 evaluates the expression. 3 if the expression is true, it returns to step 1. If the expression is false, pro...

  • Page 138

    138 chapter 6: extending coldfusion pages with cfml scripting note: unlike the cfloop tag, cfscript for-in loops do not provide built-in support for looping over queries and lists. Using continue and break statements the continue and break statements enable you to control the processing inside loops...

  • Page 139

    Handling exceptions 139 handling exceptions coldfusion provides two statements for exception handling in cfscript: try and catch . These statements are equivalent to the cfml cftry and cfcatch tags. Note: this section does not explain exception-handling concepts. For a discussion of exception handli...

  • Page 140

    140 chapter 6: extending coldfusion pages with cfml scripting cfscript example the example in this section uses the following cfscript features: • variable assignment • function calls • for loops • if-else statements • writeoutput functions • switch statements the example uses cfscript without any o...

  • Page 141

    Cfscript example 141 writeoutput("reject reason: score was too low."); break; case "late": writeoutput("reject reason: application was late."); break; default: writeoutput("rejected with invalid reason code."); } //end switch } //end if else { writeoutput("reject reason was not defined."); } //end e...

  • Page 142

    142 chapter 6: extending coldfusion pages with cfml scripting if (structkeyexists(rejectcode,applicant)) { switch(rejectcode[applicant]) { case "score": writeoutput("reject reason: score was too low."); break; case "late": writeoutput("reject reason: application was late."); break; default: writeout...

  • Page 143: Chapter 7

    143 chapter 7 using regular expressions in functions regular expressions let you perform string matching operations using coldfusion functions. This chapter describes how regular expressions work with the following functions: • refind • refindnocase • rereplace • rereplacenocase this chapter does no...

  • Page 144

    144 chapter 7: using regular expressions in functions about regular expressions in traditional string matching, as used by the coldfusion find and replace functions, you provide the string pattern to search for and the string to search. The following example searches a string for the pattern " big "...

  • Page 145

    Regular expression syntax 145 basic regular expression syntax the simplest regular expression contains only a literal characters. The literal characters must match exactly the text being searched. For example, you can use the regular expression function refind to find the string pattern " big ", jus...

  • Page 146

    146 chapter 7: using regular expressions in functions note: the * only applies to the character set that immediately precedes it, not to the entire regular expression. A + after the closing square bracket specifies to find one or more occurrences of the character set. You interpret the regular expre...

  • Page 147

    Regular expression syntax 147 • { m ,} where m is 0 or greater. Match at least m occurrences. The syntax {, n } is not allowed. The expression {1,} is equivalent to the special character +, and {0,} is equivalent to *. • { m } where m is 0 or greater. Match exactly m occurrences. Case sensitivity in...

  • Page 148

    148 chapter 7: using regular expressions in functions the following table describes the special characters for regular expressions: special character description \ a backslash followed by any special character matches the literal character itself, that is, the backslash escapes the special character...

  • Page 149

    Regular expression syntax 149 (?X) if at the beginning of a regular expression, it specifies to ignore whitespace in the regular expression and lets you use ## for end-of-line comments. You can match a space by escaping it with a backslash. For example, the following regular expression includes comm...

  • Page 150

    150 chapter 7: using regular expressions in functions you must be aware of the following considerations when using special characters in character sets, such as [a-z]: • to include a hyphen (-) in the square brackets of a character set as a literal character, you cannot escape it as you can other sp...

  • Page 151

    Regular expression syntax 151 using character classes in character sets within regular expressions, you can include a character class. You enclose the character class inside square brackets, as the following example shows: rereplace (“macromedia web site”,”[[:space:]]”,”*”,”all”) this code replaces ...

  • Page 152

    152 chapter 7: using regular expressions in functions using backreferences you use parenthesis to group components of a regular expression into subexpressions. For example, the regular expression "(ha)+" matches one or more occurrences of the string "ha". Coldfusion performs an additional operation ...

  • Page 153

    Using backreferences 153 using backreferences in replacement strings you can use backreferences in the replacement string of both the rereplace and rereplacenocase functions. For example, to replace the first repeated word in a text string with a single word, use the following syntax: rereplace("the...

  • Page 154

    154 chapter 7: using regular expressions in functions for example, the following statement replaces the uppercase string "hello" with a lowercase "hello". This example uses backreferences to perform the replacement. For more information on using backreferences, see “using backreferences in replaceme...

  • Page 155

    Returning matched subexpressions 155 to find the second occurrence of the string, you must know that the first string occurred at index 5 and that the string’s length was 5. However, refind only returns starting index of the string, not its length. So, you either must know the length of the matched ...

  • Page 156

    156 chapter 7: using regular expressions in functions the following figure shows the output of the cfdump tag: if you include subexpressions in your regular expression, each element of pos and len after element one contains the position and length of the first occurrence of each subexpression in the...

  • Page 157

    Returning matched subexpressions 157 the following figure shows the output of the cfdump tag: for a full discussion of subexpression usage, see the sections on refind and refindnocase in the coldfusion functions chapter in cfml reference. Specifying minimal matching the regular expression quantifier...

  • Page 158

    158 chapter 7: using regular expressions in functions however, sometimes you might want to override this default behavior to find the shortest string that matches the regular expression. Coldfusion includes minimal-matching quantifiers that let you specify to match on the smallest string. The follow...

  • Page 159

    Types of regular expression technologies 159 regular expressions in cfml the following examples of cfml show some common uses of regular expression functions: types of regular expression technologies many types of regular expression technologies are available to programmers. Javascript, perl, and po...

  • Page 160

    160 chapter 7: using regular expressions in functions the following perl statements are not supported: • lookbehind (? • \x{hhhh} • • \p • \c an excellent reference on regular expressions is mastering regular expressions, by jeffrey e. F. Friedl, o'reilly & associates, inc., 1997, isbn: 1-56592-2...

  • Page 161: Part II

    Part ii reusing cfml code this part describes techniques for reusing code in coldfusion pages. These techniques let you write your code once and use it, without copying it, in many places. These techniques include the cfinclude tag, user-defined functions, custom tags, coldfusion components, and col...

  • Page 163: Chapter 8

    163 chapter 8 reusing code in coldfusion pages this chapter describes techniques for reusing code in coldfusion pages. These techniques let you write your code once and use it, without copying it, in many places. This chapter describes the techniques and their features, and provides advice on select...

  • Page 164

    164 chapter 8: reusing code in coldfusion pages about reusable cfml elements coldfusion provides you with several types of reusable elements, sections of code that you can create once and use multiple times in an application. Many of these elements also let you extend the built-in capabilities of co...

  • Page 165

    Including pages with the cfinclude tag 165 the model of an included page is that it is part of your page; it just resides in a separate file. The cfinclude tag cannot pass parameters to the included page, but the included page has access to all the variables on the page that includes it. The followi...

  • Page 166

    166 chapter 8: reusing code in coldfusion pages 3 save the file as includeheader.Cfm and view it in a browser. The header should appear along with the logo. Recommended uses consider using the cfinclude tag in the following cases: • for page headers and footers • to divide a large page into multiple...

  • Page 167

    Using custom cfml tags 167 consider using udfs in the following circumstances: • you must pass in a number of arguments, process the results, and return a value. Udfs can return complex values, including structures that contain multiple simple values. • you want to provide logical units, such as dat...

  • Page 168

    168 chapter 8: reusing code in coldfusion pages although a custom tag and a coldfusion page that you include using the cfinclude tag are both coldfusion pages, they differ in how they are processed. When a page calls a custom tag, it hands processing off to the custom tag page and waits until the cu...

  • Page 169

    Using cfx tags 169 recommended uses coldfusion custom tags let you abstract complex code and programming logic into simple units. These tags let you maintain a cfml-like design scheme for your code. You can easily distribute your custom tags and share tags with others. For example, the macromedia co...

  • Page 170

    170 chapter 8: reusing code in coldfusion pages recommended uses cfx tags provide one way of using c++ or java code. However, you can also create java classes and com objects and access them using the cfobject tag. Cfx tags, however, provide some built-in features that the cfobject tag does not have...

  • Page 171

    Selecting among coldfusion code reuse methods 171 recommended uses consider using coldfusion components when doing the following: • creating web services. (to create web services in coldfusion, you must use components.) • creating services that are callable by flash clients. • creating libraries of ...

  • Page 172

    172 chapter 8: reusing code in coldfusion pages provide accessibility from flash clients. A a p use built-in user security features. A p encapsulate multiple related functions and properties. P create web services. P implement object-oriented coding methodologies. P purpose cfinclude tag custom tag ...

  • Page 173: Chapter 9

    173 chapter 9 creating and using custom cfml tags this chapter describes how to create and use custom cfml tags that encapsulate common code. Contents creating custom tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 passing data t...

  • Page 174

    174 chapter 9: creating and using custom cfml tags creating custom tags custom tags let you extend cfml by adding your own tags to the ones supplied with coldfusion. After you define a custom tag, you can use it on a coldfusion page just as you would any of the standard cfml tags, such as cfquery an...

  • Page 175

    Creating custom tags 175 5 view callingdate.Cfm in your browser. This custom tag returns the current date in the format dd-mmm-yy. As you can see from this example, creating a custom tag in cfml is no different from writing any coldfusion page. You can use all cfml constructs, as well as html. You a...

  • Page 176

    176 chapter 9: creating and using custom cfml tags for example, the following code specifies to execute the custom tag defined by the mytag.Cfm page in the parent directory of the calling page: for more information on using the cfmodule tag, see cfml reference. Calling custom tags using the cfimport...

  • Page 177

    Passing data to custom tags 177 securing custom tags the coldfusion security framework enables you to selectively restrict access to individual tag files and tag directories. This can be an important safeguard in team development. For details, see configuring and administering coldfusion mx. Accessi...

  • Page 178

    178 chapter 9: creating and using custom cfml tags variables created within a custom tag are deleted when the processing of the tag terminates. Therefore, if you want to pass information back to the calling page, you must write that information back to the caller scope of the calling page. You canno...

  • Page 179

    Passing data to custom tags 179 • use the cfparam tag with a default attribute at the top of a custom tag to test for and assign defaults for optional attributes that are passed from a calling page. For example: • use the cfparam tag or a cfif tag with an isdefined function at the top of a custom ta...

  • Page 180

    180 chapter 9: creating and using custom cfml tags 4 save the page as getmd.Cfm . 5 open the file callingpage.Cfm in your browser. The calling page uses the getmd custom tag and displays the results. Reviewing the code the following table describes the code and its function: passing custom tag attri...

  • Page 181

    Managing custom tags 181 custom tag processing reserves the attributecollection attribute to refer to the structure holding a collection of custom tag attributes. If attributecollection does not refer to such a collection, coldfusion generates a template exception. The following example uses an attr...

  • Page 182

    182 chapter 9: creating and using custom cfml tags the cfencode tag uses the following syntax: cfencode infile outfile [/r /q] [/h "message"] /v"2" the following table describes the options: note: although it is possible to encode binary files with cfencode, it is not recommended. Executing custom t...

  • Page 183

    Executing custom tags 183 the following example accesses the executionmode variable of the thistag structure from within a custom tag: handling end tags the examples of custom tags shown so far in this chapter all reference a custom tag using just a start tag, as in: in this case, coldfusion calls t...

  • Page 184

    184 chapter 9: creating and using custom cfml tags • inactive mode when the custom tag uses nested tags. For more information, see “nesting custom tags” on page 186 . If an end tag is not explicitly provided, coldfusion invokes the custom tag page only once, in start mode. A custom tag page named bo...

  • Page 185

    Executing custom tags 185 processing body text body text is any text that you include between the start and end tags when you call a custom tag; for example: happy birthday ellen! May you have many more! In this example, the two lines of code after the start tag are the body text. You can access the...

  • Page 186

    186 chapter 9: creating and using custom cfml tags the following table summarizes cfexit behavior: nesting custom tags a custom tag can call other custom tags from within it’s body text, thereby nesting tags. Coldfusion uses nested tags such as cfgraph and cfgraphdata , cfhttp and cfhttpparam , and ...

  • Page 187

    Nesting custom tags 187 nested custom tags operate through three modes of processing, which are exposed to the base tags through the variable thistag.Executionmode : • the start mode, in which the base tag is processed for the first time. • the inactive mode, in which sub tags and other code contain...

  • Page 188

    188 chapter 9: creating and using custom cfml tags where is data accessible? Two custom tags can be related in a variety of ways in a page. Ancestor and descendant relationships are important because they relate to the order of tag nesting. A tag’s descendants are inactive while the page is executed...

  • Page 189

    Nesting custom tags 189 the code accessing sub-tag attributes in the base tag could look like the following: ancestor data access the ancestor’s data is represented by a structure object that contains all the ancestor’s data. The following functions provide access to ancestral data: • getbasetaglist...

  • Page 190

    190 chapter 9: creating and using custom cfml tags to create the second custom tag page: 1 create a coldfusion page with the following content: i'm custom tag #listgetat(ancestorlist,1)# ancestorlist entry #loopcount# n is #listgetat(ancestorlist,loopcount)# list="#listrest(ancestorlist)#" list="#li...

  • Page 191: Chapter 10

    191 chapter 10 writing and calling user-defined functions this chapter describes how to create and call user-defined functions (udfs). Contents about user-defined functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 calling user-defined func...

  • Page 192

    192 chapter 10: writing and calling user-defined functions about user-defined functions you can create user-defined functions, or udfs (also known as custom functions), and use them in your application pages as you do standard coldfusion functions. This lets you create a function for an algorithm or...

  • Page 193

    Creating user-defined functions 193 you might call the function with argument names, as follows: interest: #totalinterest(principal=form.Principal, annualpercent=form.Percent, months=form.Months)# creating user-defined functions you can use tags or cfscript to create a udf. Each technique has advant...

  • Page 194

    194 chapter 10: writing and calling user-defined functions rules for function definitions the following rules apply to functions that you define using cfscript or the cffunction tag: • the function name must be unique. It must be different from any existing variable, udf, or built-in function name. ...

  • Page 195

    Creating user-defined functions 195 the following sections describe the general rules for using the arguments scope as an array and a structure. For more information on using the arguments scope in functions defined using cfscript, see “using the arguments scope in cfscript” on page 199 . For more i...

  • Page 196

    196 chapter 10: writing and calling user-defined functions using the arguments scope as an array the following rules apply to referencing arguments scope as an array: • if you call the function using unnamed arguments, the array index is the position of the argument in the function call. • if you us...

  • Page 197

    Creating user-defined functions 197 using the arguments scope as a structure the following rule applies when referencing arguments scope as a structure: • use the argument names as structure keys. For example, if your function definition includes a principal argument, refer to the argument as argume...

  • Page 198

    198 chapter 10: writing and calling user-defined functions defining functions in cfscript you define functions using cfscript in a manner similar to defining javascript functions. You can define multiple functions in a single cfscript block. Note: for more information on using cfscript, see chapter ...

  • Page 199

    Creating user-defined functions 199 a simple cfscript example the following example function adds the two arguments and returns the result: function sum(a,b) { var sum = a + b; return sum; } in this example, a single line declares the function variable and uses an expression to set it to the value t...

  • Page 200

    200 chapter 10: writing and calling user-defined functions note: avoid referring to a required argument in the body of a function by both the argument name and its place in the arguments scope array or structure, as this can be confusing and makes it easier to introduce errors. For more information ...

  • Page 201

    Creating user-defined functions 201 you must use cfargument tags for required function arguments. All cfargument tags must precede any other cfml code in cffunction tag body. Therefore, put the cfargument tags immediately following the cffunction opening tag. The cfargument tag takes the following a...

  • Page 202

    202 chapter 10: writing and calling user-defined functions using a cfml tag in a user-defined function the most important advantage of using the cffunction tag over defining a function in cfscript is that you can include cfml tags in the function. Thus, udfs can encapsulate activities, such as datab...

  • Page 203

    Calling functions and using variables 203 referencing caller variables a function can use and change any variable that is available in the calling page, including variables in the caller’s variables (local) scope, as if the function was part of the calling page. For example, if you know that the cal...

  • Page 204

    204 chapter 10: writing and calling user-defined functions using arguments function arguments can have the same names, but different values, as variables in the caller. Avoid such uses for clarity, however. The following rules apply to argument persistence: • because simple variable and array argume...

  • Page 205

    A user-defined function example 205 reviewing the code the following table describes the code: defining the function using the cffunction tag the following code replaces cfscript statements with their equivalent cfml tags. (((1+ interestrate)^years)-1)> code description function totalinterest(princi...

  • Page 206

    206 chapter 10: writing and calling user-defined functions using udfs effectively this section provides information that will help you use user-defined functions more effectively. Using application.Cfm and function include files consider the following techniques for making your functions available t...

  • Page 207

    Using udfs effectively 207 selecting a function scope the following table describes the advantages and disadvantages of scopes that you might considering using for your functions: using the request scope you can effectively manage functions that are used in application pages and custom tags by doing...

  • Page 208

    208 chapter 10: writing and calling user-defined functions using the request scope for static variables and constants this section describes how to partially break the rule described in the section “referencing caller variables” on page 203 . Here, the function defines variables in the request scope...

  • Page 209

    Using udfs effectively 209 for example, the following code defines a function to combine a single first name and last name to make a full name. It queries the companyinfo database to get the first and last names of all employees, then it uses a cfoutput tag to loop through the query and call the fun...

  • Page 210

    210 chapter 10: writing and calling user-defined functions writeoutput("myfunc is not defined"); you do not surround the argument to iscustomfunction in quotation marks, so you can use this function to determine if function arguments are themselves functions. Using the evaluate function if your user...

  • Page 211

    Using udfs effectively 211 passing arrays if you want your function to modify the caller’s copy of the array, the simplest solution is to pass the array to the function and return the changed array to the caller in the function return statement. In the caller, use same variable name in the function ...

  • Page 212

    212 chapter 10: writing and calling user-defined functions you must use the same structure element name for the array (in this case array) in the calling page and the function. Using recursion a recursive function is a function that calls itself. Recursive functions are useful when a problem can be ...

  • Page 213

    Using udfs effectively 213 for example, the following variation on a “hello world” function displays an error message if you do not enter a name in the form: enter your name: function hellofriend(name) { if (name is "") writeoutput("you forgot your name!"); else writeoutput("hello " & name &"!"); re...

  • Page 214

    214 chapter 10: writing and calling user-defined functions providing status information in some cases, such as those where the function cannot provide a corrective action, the function cannot, or should not, handle the error directly. In these cases, your function can return information to the calli...

  • Page 215

    Using udfs effectively 215 reviewing the code the following table describes the code that has been changed or added to the previous version of this example. For a description of the initial code, see “a user-defined function example” on page 204 . Calling the function the code that calls the functio...

  • Page 216

    216 chapter 10: writing and calling user-defined functions using exceptions udfs written in cfscript can handle exceptions using the try and catch statements. Udfs written using the cffunction tag can use the cftry , cfcatch , cfthrow , and cfrethrow tags. Using exceptions corresponds to the way man...

  • Page 217

    Using udfs effectively 217 generating exceptions in udfs if you define your function using the cffunction tag, you can use the cfthrow and cfrethrow tags to throw errors to the page that called the function. You can use this technique whenever your udf identifies an error, instead of displaying a me...

  • Page 218

    218 chapter 10: writing and calling user-defined functions.

  • Page 219: Chapter 11

    219 chapter 11 building and using coldfusion components coldfusion components (cfcs) let you do the following tasks: • encapsulate and reuse code in logical units. • build applications that take advantage of cfc object-oriented features. • generate web services. • create services for macromedia flas...

  • Page 220

    220 chapter 11: building and using coldfusion components about coldfusion components this section describes coldfusion components (cfcs). It introduces basic cfc concepts and features. Basic component concepts the following sections introduce coldfusion components and define the basic vocabulary and...

  • Page 221

    About coldfusion components 221 this chapter describes how to use cfc object-oriented features. It does not discuss general object-oriented programming concepts or methods. When to use cfcs you can use cfcs in several ways: • to develop structured, reusable coldfusion code • to create web services •...

  • Page 222

    222 chapter 11: building and using coldfusion components creating web services coldfusion mx can automatically publish cfc methods as web services. To publish a cfc method as a web service, you specify the access="remote" attribute in the method’s cffunction tag. Coldfusion generates all the require...

  • Page 223

    About coldfusion components 223 elements of a cfc a cfc definition has the following characteristics: • it is a single cfml page with a .Cfc file extension. The component name is the same as the filename. For example, if the file is mycomponent.Cfc, the component name is mycomponent. • the page is s...

  • Page 224

    224 chapter 11: building and using coldfusion components you can create persistent cfcs by assigning the cfc instance to a persistent scope, such as the session or application scope. This way, you can create cfcs for objects, such as shopping carts or logged-in users, that must persist for sessions....

  • Page 225

    Using coldfusion components 225 • if you invoke a cfc method remotely, using a specific url, form field, flash remoting mx, or a web service invocation, coldfusion looks in the specified path relative to the web root. For form fields and urls specified directly on local web pages, coldfusion also se...

  • Page 226

    226 chapter 11: building and using coldfusion components invoking cfc methods with the cfinvoke tag the cfinvoke tag can invoke cfc methods transiently or invoke methods on a cfc instance. You can also use the cfinvoke tag to invoke cfc methods from within a cfc. Invoking component methods transient...

  • Page 227

    Using coldfusion components 227 to invoke a method of a component instance using the cfinvoke tag: 1 create a file named telltime2.Cfc with the following code: servertime=now(); utctime=gettimezoneinfo(); utcstruct=structnew(); utcstruct.Hour=datepart("h", servertime); utcstruct.Minute=datepart("n",...

  • Page 228

    228 chapter 11: building and using coldfusion components using cfinvoke within the cfc definition you can use the cfinvoke tag to invoke a component method within the component definition; for example, to call a utility method that provides a service to other methods in the component. To use cfinvok...

  • Page 229

    Using coldfusion components 229 passing parameters using the cfinvokeargument tag to pass parameters in the cfinvoke tag body, use the cfinvokeargument tag. Using the cfinvokeargument tag, for example, you can build conditional processing that passes a different parameter based on user input. The fo...

  • Page 230

    230 chapter 11: building and using coldfusion components in the example, the three cfscript statements do the following: 1 the createobject function instantiates the telltime cfc as telltimecfc. 2 the first writeoutput function displays text followed by the results returned by the getlocaltime metho...

  • Page 231

    Using coldfusion components 231 note: to use url invocation, you must set the cffunction tag’s access attribute to remote. To pass parameters to component methods using a url, append the parameters to the url in standard url query-string, name-value pair syntax; for example: http://localhost:8500/co...

  • Page 232

    232 chapter 11: building and using coldfusion components 2 create a corpquery.Cfc, specifying access="remote" for each cffunction tag, as the following example shows: access="remote"> select lastname, firstname, email from tblemployees where lastname like '#arguments.Lastname#' results filtered by #...

  • Page 233

    Using coldfusion components 233 introspection: getting information about components coldfusion provides several ways to get information about components: • requesting a component page from the browser • using the coldfusion component browser • using the dreamweaver component browser • using the getm...

  • Page 234

    234 chapter 11: building and using coldfusion components add (addition function) using the coldfusion component browser you can also browse the components available in coldfusion using the component browser, which is located at [webroot]\cfide\componentutils\componentdoc.Cfm. The browser has three p...

  • Page 235

    Building coldfusion components 235 using the getmetadata function the cfml getmetadata function returns a structure containing all the metadata of a cfc instance. This structure contains substantially more data about the cfc than cfdump shows, and includes the following information: • all attributes...

  • Page 236

    236 chapter 11: building and using coldfusion components initializing instance data some components have instance data, data that persists as long as the component instance exists. For example, a shopping cart component might have instance data that includes the ids and quantities of items the user ...

  • Page 237

    Building coldfusion components 237 the following cffunction tag attributes are used only for cfcs: • the displayname and hint attributes document the cfc; for more information, see “documenting cfcs” on page 240 . • the access attribute controls access to the cfc; for more information , see “using a...

  • Page 238

    238 chapter 11: building and using coldfusion components defining and using method parameters to define the component method parameter, use the cfargument tag in the cffunction tag body. To define multiple parameters, use multiple cfargument tags. You can create cfc methods that do not use cfargumen...

  • Page 239

    Building coldfusion components 239 in the example, the cfargument attributes specify the following: • the name attributes define the parameter names • the type attribute for the lastname argument specifies that the parameter must be a text string. The type attribute for the cost argument specifies t...

  • Page 240

    240 chapter 11: building and using coldfusion components note: if a cfc is invoked using a url or by submitting a form, coldfusion mx returns the variable as a wddx packet. Coldfusion mx cannot return methods to flash. Therefore, a cfc that is invoked by flash remoting mx must not return the this sc...

  • Page 241

    Building coldfusion components 241 in this case, a coldfusion page with the following code sets the metatypeinfo variable to float: note: avoid using expressions in custom metadata attributes. Using expressions in metadata attributes can cause unpredictable behavior, because all metadata expressions...

  • Page 242

    242 chapter 11: building and using coldfusion components establishing a descriptive naming convention is a good practice, especially if the components will be installed as part of a packaged application. Cfc variables this section describes how cfcs use variables and interact with coldfusion scopes....

  • Page 243

    Building coldfusion components 243 example: sharing the variables scope the following example shows how a cfc can change data in the calling page’s variables scope. The callgreetme.Cfm page before invoking the cfc variables.Myname is #variables.Myname#. Calling greetme cfc. It returns: #mygreetings....

  • Page 244

    244 chapter 11: building and using coldfusion components you can access variables in the arguments scope using structure notation (arguments.Variablename) or array notation (arguments[1] or arguments[“variablename”]). The arguments scope does not last between calls to cfc methods. These variables ar...

  • Page 245

    Building coldfusion components 245 • the super keyword lets a component that overrides a base component method execute the original base component method. This technique lets your subclassed component override a method without losing the ability to call the original version of the method. The follow...

  • Page 246

    246 chapter 11: building and using coldfusion components 3 create a coldfusion page with the following code, and save it as inherit.Cfm in your web root directory: when you execute the inherit.Cfm file, the getlocaltime component method executes even though it is invoked using the corpquery componen...

  • Page 247

    Building coldfusion components 247 using component packages components stored in the same directory are members of a component package. Component packages help prevent naming conflicts and facilitate easy component deployment. For example: • coldfusion searches the current directory first for a cfc....

  • Page 248

    248 chapter 11: building and using coldfusion components code that manipulates persistent scope cfc properties must be locked, just as all other code that manipulates persistent scope properties must be locked. Therefore, you must lock both of the following types of application code: • code that dir...

  • Page 249

    Building coldfusion components 249 using role-based security if you specify a roles attribute in a cffunction tag, as the following example shows, only users who are logged in with one of the specified roles can execute the function: when a user tries to invoke a method that he or she is not authori...

  • Page 250

    250 chapter 11: building and using coldfusion components.

  • Page 251: Chapter 12

    251 chapter 12 building custom cfxapi tags sometimes, the best approach to application development is to develop elements of your application by building executables to run with coldfusion. Perhaps the application requirements go beyond what is currently feasible in cfml. Perhaps you can improve app...

  • Page 252

    252 chapter 12: building custom cfxapi tags what are cfx tags? Coldfusion extension (cfx) tags are custom tags written against the coldfusion extension application programming interface. Generally, you create a cfx tag if you want to do something that is not possible in cfml, or if you want to impro...

  • Page 253

    Writing a java cfx tag 253 setting up your development environment to develop cfx tags in java you can use a wide range of java development environments, including the java development kit (jdk) version 1.3.1 from sun, to build java cfx tags. You can download the jdk from sun http://java.Sun.Com/j2s...

  • Page 254

    254 chapter 12: building custom cfxapi tags to create a java cfx tag: 1 create a new source file in your editor with the following code: import com.Allaire.Cfx.* ; public class myhellocoldfusion implements customtag { public void processrequest( request request, response response ) throws exception ...

  • Page 255

    Writing a java cfx tag 255 2 save the file in a directory configured to serve coldfusion pages. For example, you can save the file as c:\inetpub\wwwroot\cfdocs\testjavacfx.Cfm on windows or /home/docroot/cfdocs/ testjavacfx.Cfm on unix. 3 if you have not already done so, register the cfx tag in the ...

  • Page 256

    256 chapter 12: building custom cfxapi tags response object the response object is passed to the processrequest method of the customtag interface. The following table lists the methods of the response object for writing output, generating queries, and setting variables within the calling page: for d...

  • Page 257

    Zipbrowser example 257 automatic class reloading you can determine how the server treats changed java cfx class files by specifying the reload attribute when you use a cfx tag in your coldfusion page. The following table describes the allowable values for the reload attribute: the default value is r...

  • Page 258

    258 chapter 12: building custom cfxapi tags 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 reques...

  • Page 259

    Approaches to debugging java cfx tags 259 approaches to debugging java cfx tags java cfx tags are not stand-alone applications that run in their own process, like typical java applications. Rather, they are created and invoked from an existing process. This makes debugging java cfx tags more difficu...

  • Page 260

    260 chapter 12: building custom cfxapi tags 5 debug your application by setting breakpoints, single stepping, displaying variables, or by performing other debugging actions. Using the debugging classes to develop and debug java cfx tags in isolation from the coldfusion, you use three special debuggi...

  • Page 261

    Developing cfx tags in c++ 261 { "lynne", "teague", "developer" } } ; debugquery query = new debugquery( "employees", columns, data ) ; // create tag, process debugging request, and print results outputquery tag = new outputquery() ; debugrequest request = new debugrequest( attributes, query ) ; deb...

  • Page 262

    262 chapter 12: building custom cfxapi tags compiling c++ cfx tags cfx tags built in windows and on unix must be thread-safe. Compile cfx tags for solaris with the -mt switch on the sun compiler. Locating your c++ library files on unix on unix systems, your c++ library files can be in any directory ...

  • Page 263

    Developing cfx tags in c++ 263 registering cfx tags to use a cfx tag in your coldfusion applications, first register it in the extensions, cfx tags page in the coldfusion mx administrator. To register a c++ cfx tag: 1 on the coldfusion mx administrator server tab, select extensions > cfx tags to ope...

  • Page 264

    264 chapter 12: building custom cfxapi tags.

  • Page 265: Part III

    Part iii developing cfml applications this part describes how to develop coldfusion applications. It describes the elements of a coldfusion application and how to structure an application, handle errors, use variables that are shared among pages, lock code segments, and secure your application. It a...

  • Page 267: Chapter 13

    267 chapter 13 designing and optimizing a coldfusion application this chapter describes the elements that make your coldfusion pages into an effective internet application. It provides an overview of application elements, describes how you can structure an application on your server, and provides de...

  • Page 268

    268 chapter 13: designing and optimizing a coldfusion application about applications the term application can mean many things. An application can be as simple as a guest book or as sophisticated as a full internet commerce system with catalog pages, shopping carts, and reporting. However, an applic...

  • Page 269

    Elements of a coldfusion application 269 this chapter does not provide information on how to use or develop a specific application framework. However, it does discuss how an application’s directory structure affects the application and how you can map the directory structure. For more information on...

  • Page 270

    270 chapter 13: designing and optimizing a coldfusion application for an overview of these elements, and information about how to choose among them, see chapter 8, “reusing code in coldfusion pages,” on page 163 . Shared variables the following coldfusion variable scopes maintain data that lasts bey...

  • Page 271

    Mapping an application 271 processing the application.Cfm and onrequestend.Cfm pages coldfusion uses similar, but different, rules to locate and process the application.Cfm and onrequestend.Cfm pages. Processing the application.Cfm page when coldfusion receives a request for an application page, it ...

  • Page 272

    272 chapter 13: designing and optimizing a coldfusion application you can divide your logical web application into multiple coldfusion applications by using multiple application.Cfm pages with different application names. Alternatively, you can use multiple application.Cfm pages that specify the sam...

  • Page 273

    Creating the application.Cfm page 273 • login processing • application-specific error handling naming the application in coldfusion, you define an application by giving it a name using the cfapplication tag. By using a specific application name in a cfapplication tag, you define a set of pages as pa...

  • Page 274

    274 chapter 13: designing and optimizing a coldfusion application defining page processing settings the cfsetting tag lets you specify the following page processing attributes that you might want to apply to all pages in your application: often, you use the cfsetting tag on individual pages, but you...

  • Page 275

    Creating the application.Cfm page 275 you can also use the application.Cfm page to develop more sophisticated application-wide error- handling techniques, including error-handling methods that provide specific messages or use structured error-handling techniques. For more information on error pages ...

  • Page 276

    276 chapter 13: designing and optimizing a coldfusion application reviewing the code the following table describes the code and its function: code description clientmanagement="yes" clientstorage="mycompany" sessionmanagement="yes"> names the application, enables client and session scope variables, ...

  • Page 277

    Optimizing coldfusion applications 277 optimizing coldfusion applications you can optimize your coldfusion application in many ways. Much of optimizing coldfusion involves good development and coding practices. For example, good database design and usage is a prime contributor to efficient coldfusio...

  • Page 278

    278 chapter 13: designing and optimizing a coldfusion application • the directory on the server in which to store the cached pages. The default directory is cf_root/ cache. It is a good practice to create a separate cache directory for each application. Doing so can prevent the cfcache tag flush act...

  • Page 279

    Optimizing coldfusion applications 279 the cfsavecontent tag saves the results of processing the tag body in a variable. For example, if the body of the cfsavecontent tag contains a cfexecute tag that runs an executable program that displays data, the variable saves the output. You can use the cfsav...

  • Page 280

    280 chapter 13: designing and optimizing a coldfusion application #application.Productcache# reviewing the code the following table describes the code and its function: code description welcome to our home page. The time is #timeformat(now())#. Your lucky number is: #randrange(1,1000)# displays the ...

  • Page 281

    Optimizing coldfusion applications 281 optimizing database use two important coldfusion mx tools for optimizing your use of databases are the cfstoredproc tag and the cfquery tag cachedwithin attribute. Note: poor database design and incorrect or inefficient use of the database are among the most co...

  • Page 282

    282 chapter 13: designing and optimizing a coldfusion application variable = foo dbvarname = @param2> the output param value: '#foo#' the results information variable = foo dbvarname = @param2> the output param value: '#foo#' #name#,#date_col# record count: #rs1.Recordcount# columns: #rs1.Columnlist...

  • Page 283

    Optimizing coldfusion applications 283 for more information on creating stored procedures, see your database management software documentation. For more information on using the cfstoredproc tag, see cfml reference. Using the cfquery tag cachedwithin attribute the cfquery tag cachedwithin attribute ...

  • Page 284

    284 chapter 13: designing and optimizing a coldfusion application you must use the createtimespan function to specify the cachedwithin attribute value (in days, hours, minutes, seconds format). For example, the following code caches the results of getting the contents of the employees table of the c...

  • Page 285: Chapter 14

    285 chapter 14 handling errors coldfusion includes many tools and techniques for responding to errors that your application encounters. These tools include error handling mechanisms and error logging tools. This chapter describes these tools and how to use them. This chapter does not discuss techniq...

  • Page 286

    286 chapter 14: handling errors about error handling in coldfusion by default, coldfusion generates its own error messages when it encounters errors. In addition, it provides a variety of tools and techniques for you to customize error information and handle errors when they occur. You can use any o...

  • Page 287

    Understanding errors 287 errors such as validation errors, for which the application cannot continue processing the request, but can provide an error-specific response, can also be considered recoverable. For example, an error that occurs when a user enters text where a number is required can be con...

  • Page 288

    288 chapter 14: handling errors about coldfusion exceptions you can categorize coldfusion exceptions in two ways: • when they occur • their type when exceptions occur coldfusion errors can occur at two times, when the cfml is compiled into java and when the resulting java executes, called runtime ex...

  • Page 289

    Understanding errors 289 basic exception types all coldfusion exceptions except for custom exceptions belong to a basic type category. These types consist of a broadly-defined categorization of coldfusion exceptions. The following table describes the basic exception types: note: the any type include...

  • Page 290

    290 chapter 14: handling errors advanced exception types the advanced exceptions consist of a set of specific, narrow exception types. These types are supported in coldfusion mx for backward-compatibility. For a list of advanced exception types, see “advanced exception types” in chapter 2, “coldfusi...

  • Page 291

    Error messages and the standard error format 291 ■ if the administrator settings site-wide error handler field specifies an error handler page, coldfusion displays the specified error page. ■ otherwise, coldfusion reports the error using the standard error message format described in “error messages...

  • Page 292

    292 chapter 14: handling errors tip: if you get a message that does not explicitly identify the cause of the error, check the key system parameters, such as available memory and disk space. Determining error-handling strategies coldfusion provides you with many options for handling errors, particula...

  • Page 293

    Determining error-handling strategies 293 handling compiler exceptions you cannot handle compiler exceptions directly on the page where they occur, because the exception is caught before coldfusion starts running the page code. You should fix all compiler exceptions as part of the development proces...

  • Page 294

    294 chapter 14: handling errors specifying custom error messages with cferror custom error pages let you control the error information that users see. You can specify custom error pages for different types of errors and handle different types of errors in different ways. For example, you can create ...

  • Page 295

    Specifying custom error messages with cferror 295 the following cferror tag specifies a custom error page for exceptions that occur in locking code and informs the error page of the of an e-mail address it can use to send a notification each time this type of error occurs: exception = "lock" templat...

  • Page 296

    296 chapter 14: handling errors the following table describes the variables available on error pages: exception error pages can also use all of the exception variables listed in the section “exception information in cfcatch blocks” on page 301 . To use these variables, replace the cfcatch prefix wit...

  • Page 297

    Logging errors with the cflog tag 297 example of a request error page the following example shows a custom error page for a request error: an error occurred when you requested this page. Please send e-mail with the following information to #error.Mailto# to report this error. Date and time: #error.D...

  • Page 298

    298 chapter 14: handling errors the cflog tag lets you specify the following information: • a custom file or standard coldfusion log file in which to write the message. • text to write to the log file. This can include the values of all available error and cfcatch variables. • message severity (type...

  • Page 299

    Handling runtime exceptions with coldfusion tags 299 diagnostics: cannot find cfml template for custom tag testcase. Cannot find cfml template for custom tag testcase. Coldfusion attempted looking in the tree of installed custom tags but did not find a custom tag with this name." the text consists o...

  • Page 300

    300 chapter 14: handling errors for example, you can use cftry to catch errors in code that enters data from a user registration form to a database. The cfcatch code could do the following: 1 retry the query, so the operation succeeds if the resource was only temporarily unavailable. 2 if the retrie...

  • Page 301

    Handling runtime exceptions with coldfusion tags 301 if an exception occurs in the first level of exception-handling code, the inner cfcatch block can catch and handle it. (an exception in a cfcatch block cannot be handled by cfcatch blocks at the same level as that block.) • coldfusion always respo...

  • Page 302

    302 chapter 14: handling errors note: if you use cfdump to display the cfcatch variable, the display does not include variables that do not have values. The cfcatch.Tagcontext variable contains an array of tag information structures. Each structure represents one level of the active tag context at t...

  • Page 303

    Handling runtime exceptions with coldfusion tags 303 expression exceptions the following variable is only available for expression exceptions: locking exceptions the following additional information is available for exceptions related to errors that occur in cflock tags: missing include exceptions t...

  • Page 304

    304 chapter 14: handling errors department: #dept_id# last name: #lastname# first name: #firstname#.

  • Page 305

    Handling runtime exceptions with coldfusion tags 305 use the following procedure to test the code. Testing the code: 1 make sure there is no includeme.Cfm file and display the page. The cfcatch type="missinginclude" block displays the error. 2 create a nonempty includeme.Cfm file and display the pag...

  • Page 306

    306 chapter 14: handling errors reviewing the code the following table describes the code: code description initializes the employee id to a valid value. An application would get the value from a form or other source. Sets the default errorcaught variable value to the empty string (to indicate no er...

  • Page 307

    Handling runtime exceptions with coldfusion tags 307 using the cfthrow tag you can use the cftry tag to raise your own, custom exceptions. When you use the cfthrow tag, you specify any or all of the following information: all of these values are optional. You access the attribute values in cfcatch b...

  • Page 308

    308 chapter 14: handling errors catching and displaying thrown errors the cfcatch tag catches a custom exception when you use any of the following values for the cfcatch type attribute: • the custom exception type specified in the cfthrow tag. • a custom exception type that hierarchically matches th...

  • Page 309

    Handling runtime exceptions with coldfusion tags 309 for example, on a form action page or custom tag used to set a password, the application can determine whether the password entered is a minimum length, or contains both letters and number, and throw an error with a message that indicates the pass...

  • Page 310

    310 chapter 14: handling errors • the custom tag finds all records in the companyinfo database with a matching last name, and returns the results in a caller variable. If it fails to connect with the main database, it tries a backup database. The calling page the calling page represents a section fr...

  • Page 311

    Handling runtime exceptions with coldfusion tags 311 select * from employee where lastname = ’#attributes.Empname#’ "im002")> select * from employee where lastname = ’#attributes.Empname#’ "im002")> select * from employee where lastname = ’#attributes.Empname#’ an unexpected error happened in proces...

  • Page 312

    312 chapter 14: handling errors reviewing the code the following table describes the code: code description message = "last name was not supplied to the cf_getemps tag."> makes sure the calling page specified an empname attribute. If not, throws a custom error that indicates the problem and exits th...

  • Page 313

    Handling runtime exceptions with coldfusion tags 313 testing the code to test the various ways errors can occur and be handled in this example, try the following: • in the calling page, change the attribute name to any other value; for example, my attrib. Then change it back. • in the first cfquery ...

  • Page 314

    314 chapter 14: handling errors.

  • Page 315: Chapter 15

    315 chapter 15 using persistent data and locking coldfusion mx provides several variable scopes in which data persists past the life of a single request. These are the client, application, session, and server scopes. These scopes let you save data over time and share data between pages and even appl...

  • Page 316

    316 chapter 15: using persistent data and locking about persistent scope variables coldfusion mx provides four variable scopes, described in the following table, that let you maintain data that must be available to multiple applications or users or must last beyond the scope of the current request. ...

  • Page 317

    About persistent scope variables 317 note: although you can use the structclear function to clear your data from the server scope, the function does not delete the names of the variables, only their values, and it does not delete the contents of the server.Os and server.Coldfusion structures. Using ...

  • Page 318

    318 chapter 15: using persistent data and locking managing the client state because the web is a stateless system, each connection that a browser makes to a web server is unique to the web server. However, many applications must keep track of users as they move through the pages within the applicati...

  • Page 319

    Managing the client state 319 maintaining client identity because the web is a stateless system, client management requires some method for maintaining knowledge of the client between requests. Normally you do this using cookies, but you can also do it by passing information between application page...

  • Page 320

    320 chapter 15: using persistent data and locking to use coldfusion client or session variables without using cookies, each page must pass the cfid and cftoken values to any page that it calls as part of the request url. If a page contains any html href a= links, cflocation tags, form tags, or cffor...

  • Page 321

    Configuring and using client variables 321 providing session security coldfusion uses the same client identifiers for the client scope and the standard session scope. Because the cftoken and cfid values are used to identify a client over a period of time, they are normally saved as cookies on the us...

  • Page 322

    322 chapter 15: using persistent data and locking the coldfusion mx administrator client variables page controls the default client variable location. You can override the default location by specifying a clientstorage attribute in the cfapplication tag. You can specify the following values in the c...

  • Page 323

    Configuring and using client variables 323 the cdata table must have the following columns: the cglobal table must have the following columns: note: different databases use different names for their data types. The names in the preceding tables are common, but your database might use other names. To...

  • Page 324

    324 chapter 15: using persistent data and locking creating a client variable to create a client variable and set its value, use the cfset or cfparam tag and use the client scope identifier as a variable prefix; for example: after you set a client variable this way, it is available for use within any...

  • Page 325

    Configuring and using client variables 325 you use the client.Cfid , client.Cftoken , and client.Urltoken variables if your application supports browsers that do not allow cookies. For more information on supporting browsers that do not allow cookies, see “using client and session variables without ...

  • Page 326

    326 chapter 15: using persistent data and locking exporting the client variable database if your client variable database is stored in the windows system registry and you need to move it to another machine, you can export the registry key that stores your client variables and take it to your new ser...

  • Page 327

    Configuring and using session variables 327 coldfusion and j2ee session management the coldfusion server can use either of the following types of session management: • coldfusion session management • j2ee servlet session management coldfusion session management uses the same client identification me...

  • Page 328

    328 chapter 15: using persistent data and locking enabling session variables in your application you must also enable session variables in the cfapplication tag in your application.Cfm file. Do the following in the application.Cfm file to enable session variables: • set sessionmanagement="yes" • use...

  • Page 329

    Configuring and using session variables 329 note: coldfusion lets you delete or change the values of the built-in session variables. As a general rule, avoid doing so. If you enable client variables and coldfusion session management, coldfusion uses the same values for the client and session scope c...

  • Page 330

    330 chapter 15: using persistent data and locking accessing and changing session variables you use the same syntax to access a session variable as for other types of variables. However, you must lock any code that accesses or changes session variables. For example, to display the number of items in ...

  • Page 331

    Configuring and using application variables 331 configuring and enabling application variables to use application variables, do the following: • ensure that they are enabled in the coldfusion mx administrator. (they are enabled by default.) • specify the application name in the cfapplication tag for...

  • Page 332

    332 chapter 15: using persistent data and locking because each application scope variable is shared in memory by all requests in the application, these variables can become bottlenecks if used inappropriately. Whenever a request is reading or writing an application scope variable, any other requests...

  • Page 333

    Locking code with cflock 333 locking code with cflock the cflock tag controls simultaneous access to coldfusion code. The cflock tag lets you do the following: • protect sections of code that access and manipulate shared data in the session, application, and server scopes. • ensure that file updates...

  • Page 334

    334 chapter 15: using persistent data and locking sample locking scenarios the following examples present scenarios in which you need to lock coldfusion code. These scenarios show only two of the circumstances where locking is vital. Reading and writing a shared variable if you have an application-w...

  • Page 335

    Locking code with cflock 335 11 order 2 exits the lock tag, which frees the application scope lock. Coldfusion can process another order. The resulting application.Totaltickessold value is now correct. Ensuring consistency of multiple variables often an application sets multiple shared scope variabl...

  • Page 336

    336 chapter 15: using persistent data and locking lock types the cflock tag offers two modes of locking, specified by the type attribute: • exclusive locks (the default lock type) allow only one request to process the locked code. No other requests can run code inside the tag while a request has an ...

  • Page 337

    Locking code with cflock 337 if multiple code sections share a lock, the following rules apply: • when code is running in a cflock tag block with the type attribute set to exclusive , code in cflock tag blocks with the same scope attribute is not allowed to run. They wait until the code with the exc...

  • Page 338

    338 chapter 15: using persistent data and locking considering lock granularity when you design your locking strategy, consider whether you should have multiple locks containing small amounts of code or few locks with larger blocks of code. There is no simple rule for making such a decision, and you ...

  • Page 339

    Locking code with cflock 339 note: you can skip any pair of lock and unlock steps in the preceding list if you do not need to lock a particular scope. For example, you can omit steps 3 and 4 if you do not need to lock the server scope. Copying shared variables into the request scope you can avoid lo...

  • Page 340

    340 chapter 15: using persistent data and locking ... Examples of cflock the following examples show how to use cflock blocks in a variety of situations. Example with application, server, and session variables this example shows how you can use cflock to guarantee the consistency of data updates to ...

  • Page 341

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

  • Page 342

    342 chapter 15: using persistent data and locking red white blue turquoise black forest green small medium large xlarge note: in this simple example, the application.Cfm page displays the application.Number variable value. Because the application.Cfm file is processed before any code on each coldfus...

  • Page 343

    Examples of cflock 343 example of protecting coldfusion extensions the following example shows how you can build a custom tag wrapper around a cfx tag that is not thread-safe. The wrapper forwards attributes to the non-thread-safe cfx tag that is used inside a cflock tag. Type="exclusive" name="cfx_...

  • Page 344

    344 chapter 15: using persistent data and locking.

  • Page 345: Chapter 16

    345 chapter 16 securing applications coldfusion mx has two major security features: • sandbox security (coldfusion mx enterprise) or resource security (coldfusion mx standard), where security restricts access to specific resources, such as tags and files. • user security, which depends on a user ide...

  • Page 346

    346 chapter 16: securing applications coldfusion security features coldfusion provides scalable, granular security for building and deploying your coldfusion applications. Coldfusion provides the following types of security resources: • development coldfusion mx administrator is protected by a passw...

  • Page 347

    About resource and sandbox security 347 resource control coldfusion lets you control access to the following resources: note: for more information on configuring resource and sandbox security, see configuring and administering coldfusion mx and the coldfusion mx administrator online help. Sandbox se...

  • Page 348

    348 chapter 16: securing applications about user security user security lets your application use security rules to determine what it displays. It has two elements: • authentication ensures that a valid user is logged-in, based on an id and password provided by the user. Coldfusion (or, in some case...

  • Page 349

    About user security 349.

  • Page 350

    350 chapter 16: securing applications authenticating users you can use either, or both, of the following forms of authentication to secure your coldfusion application: • web server authentication, where the web server authenticates the user and does not allow access to the website by users without v...

  • Page 351

    About user security 351 about application authentication with application authentication, you do not rely on the web server to enforce application security. The application performs all user authentication and authorization. The application displays a login page, checks the user’s identity and login...

  • Page 352

    352 chapter 16: securing applications if you do not enable the session scope, the authentication information is not kept in a persistent scope. Instead, the detailed login information is put in a memory-only cookie (cfauthorization_applicationname) with a base64-encoded string that contains the user...

  • Page 353

    Using coldfusion security tags and functions 353 using the cflogin tag the cflogin tag executes only if there is no currently logged-in user. It has the following three optional arguments that control the characteristics of a coldfusion login: login identification scope and the applicationtoken attr...

  • Page 354

    354 chapter 16: securing applications the cflogin structure provides a consistent interface for determining the user’s login id and password, independent of the technique you use for displaying the login form. Caution: login forms send the username and password without encryption. Basic http authent...

  • Page 355

    Security scenarios 355 security scenarios the following sections provide two detailed security scenarios. The first scenario uses the web server to perform the authentication against its user and password database. The second scenario uses coldfusion for all authentication and authorization. A web s...

  • Page 356

    356 chapter 16: securing applications an application authentication security scenario an application that does its own authentication might work as follows. The example in “application-based user security example” on page 360 implements this scenario. 1 whenever coldfusion receives a request for a c...

  • Page 357

    Security scenarios 357.

  • Page 358

    358 chapter 16: securing applications implementing user security the following sections provide several examples of ways to implement security using basic authentication and application authentication. Web-server–based authentication user security example the example in this section shows how you mi...

  • Page 359

    Implementing user security 359 the following table describes the cfml code in application.Cfm and its function: example: securitytest.Cfm the securitytest.Cfm page shows how any application page can use coldfusion user authorization features. The web server ensures the existence of an authenticated ...

  • Page 360

    360 chapter 16: securing applications reviewing the code the following table describes the securitytest.Cfm page cfml code and its function: application-based user security example the example in this section shows how you might implement user security by authenticating users and then allowing users...

  • Page 361

    Implementing user security 361 example: application.Cfm the application.Cfm page consists of the following: select userid, roles from logininfo where userid = '#cflogin.Name#' and password = '#cflogin.Password#' roles="#loginquery.Roles#"> your login information is not valid. Roles="#loginquery.Role...

  • Page 362

    362 chapter 16: securing applications the following table describes the cfml code in application.Cfm and its function: . Code description sessionmanagement="yes" > loginstorage=”session” identifies the application, enables the session scope, and enables storing login information in the session scope...

  • Page 363

    Implementing user security 363 example: loginform.Cfm the loginform.Cfm page consists of the following: ends the loginquery.Roles test code. Ends the form entry empty value test. Ends the form entry existence test. Ends the cflogin tag body. Method="post"> value="logout"> if a user is logged-in, dis...

  • Page 364

    364 chapter 16: securing applications reviewing the code the following table describes the loginform.Cfm page cfml code and its function: example: securitytest.Cfm the securitytest.Cfm page shows how any application page can use coldfusion user authorization features. Application.Cfm ensures the exi...

  • Page 365

    Implementing user security 365 if (isuserinrole("contractor")) writeoutput("contractors see this message."); reviewing the code the following table describes the securitytest.Cfm page cfml code and its function: code description displays a welcome message that includes the user’s login id. All logge...

  • Page 366

    366 chapter 16: securing applications using an ldap directory for security information ldap directories are often used to store security information. The following example of an application.Cfm page with a cflogin tag checks an ldap directory to authenticate the user and retrieve the user’s roles. T...

  • Page 367

    Implementing user security 367 alert("uid for #cflogin.Name# not found"); action="query" name="auth" attributes="cn" start="ou=product support,dc=allaire,dc=com" scope="subtree" server="#ldap_server#" port="#ldap_port#" filter="(&(objectclass=groupofuniquenames)(uniquemember= #usersearch.Dn#))" user...

  • Page 368

    368 chapter 16: securing applications reviewing the code the following table describes the code and its function. Comments and some tab characters have been removed for brevity. Code description (uid=#cflogin.Name#))"> manager"> starts the cflogin tag body. Sets several of the values used as attribu...

  • Page 369

    Implementing user security 369 cfcatch.Detail)> alert("user id or password invalid for user: #cflogin.Name#") alert("unknown error for user: #cflogin.Name##cfcatch. Detail#") cfcatch.Detail)> alert("user id or password invalid for user: #cflogin.Name#") alert("unknown error for user: #cflogin.Name##...

  • Page 370

    370 chapter 16: securing applications.

  • Page 371: Chapter 17

    371 chapter 17 developing globalized applications coldfusion mx lets you develop dynamic applications for the internet. Many coldfusion applications are accessed by users from different countries and geographical areas. One design detail that you must consider is the globalization of your applicatio...

  • Page 372

    372 chapter 17: developing globalized applications introduction to globalization globalization lets you create applications for all of your customers in all the languages that you support. In some cases, globalization can let you accept data input using a different character set than the one you use...

  • Page 373

    Introduction to globalization 373 importance of globalization in coldfusion applications the internet has no country boundaries. Customers can access websites from anywhere in the world, at any time, or on any date. Unless you want to lock your customers into using a single language, such as english...

  • Page 374

    374 chapter 17: developing globalized applications a locale identifies the exact language and cultural settings for a user. The locale controls how dates and currencies are formatted, how to display time, and how to display numeric data. For example, the locale english (us) determines that a currenc...

  • Page 375

    About character encodings 375 computers often must convert between character encodings. In particular, the character encodings most commonly used on the internet are not used by java or windows. Character sets used on the internet are typically single-byte or multiple-byte (including dbcs character ...

  • Page 376

    376 chapter 17: developing globalized applications similar issues can arise if you convert between other character encodings; for example, if you read files encoded in the japanese windows default encoding and display them using shift-jis. To prevent these problems, ensure that the display encoding ...

  • Page 377

    Processing a request in coldfusion 377 the current locale has two effects: • when coldfusion formats date, time, currency, or numeric output, it determines how to format the output. You can change the locale multiple times on a coldfusion page to format information according to different locale conv...

  • Page 378

    378 chapter 17: developing globalized applications the default language of a website might be different from that of the person connecting to it. For example, you could connect to an english website from a french computer. When coldfusion generates a response, the response must be formatted in the w...

  • Page 379

    Tags and functions for globalizing 379 determining the page encoding of server output before coldfusion can return a response to the client, it must determine the encoding to use for the data in the response. By default, coldfusion returns character data using the unicode utf-8 format. Coldfusion pa...

  • Page 380

    380 chapter 17: developing globalized applications tags and functions for controlling character encoding the following tags and functions let you specify the character encoding of text that coldfusion generates and interprets: tag or function attribute or parameter use cfprocessingdirective pageenco...

  • Page 381

    Tags and functions for globalizing 381 functions for controlling and using locales coldfusion mx provides the following functions that let you specify and identify the locale and format text based on the locale: note: many functions that have names starting with ls have corresponding functions that ...

  • Page 382

    382 chapter 17: developing globalized applications format the date part of a date/time value using the locale convention. Index = "locale" delimiters = ","> #locale# #lsdateformat(now(), "mmm-dd-yyyy")# #lsdateformat(now(), "mmmm d, yyyy")# #lsdateformat(now(), "mm/dd/yyyy")# #lsdateformat(now(), "d...

  • Page 383

    Handling data in coldfusion mx 383 general character encoding issues applications developed for earlier versions of coldfusion that assumed that the character length of a string was the same as the byte length might produce errors in coldfusion mx. The byte length of a string depends on the characte...

  • Page 384

    384 chapter 17: developing globalized applications handling url strings url requests to a server often contain name/value pairs as part of the request. For example, the following url contains name/value pairs as part of the url: http://company.Com/prod_page.Cfm?Name=stephen;id=7645 as discussed prev...

  • Page 385

    Handling data in coldfusion mx 385 to work around this issue, use the setencoding function to specify the character encoding of input form text. The setencoding function takes two parameters: the first specifies the variable scope and the second specifies the character encoding used by the scope. Si...

  • Page 386

    386 chapter 17: developing globalized applications database administrators configure data sources and usually are required to specify the character encodings for character column data. Many of the major vendors, such as oracle, sybase, and informix, support storing character data in many character e...

  • Page 387

    Handling data in coldfusion mx 387 as long as you are using corba later than version 2.0, which includes support for the idl types wchar and wstring, which map to java types char and string respectively, you do not have to do anything to support double-byte characters. However, if you are using a ve...

  • Page 388

    388 chapter 17: developing globalized applications.

  • Page 389: Chapter 18

    389 chapter 18 debugging and troubleshooting applications coldfusion mx provides detailed debugging information to help you resolve problems with your application. This chapter describes how you configure coldfusion mx to provide debugging information, how to understand the information it provides, ...

  • Page 390

    390 chapter 18: debugging and troubleshooting applications configuring debugging in the coldfusion mx administrator coldfusion can provide important debugging information for every application page requested by a browser. The coldfusion mx administrator lets you specify which debugging information t...

  • Page 391

    Configuring debugging in the coldfusion mx administrator 391 the following figure shows a sample debugging output using the classic output format: variables enables the display of coldfusion variable values. When this option is cleared, disables display of all coldfusion variables in the debugging o...

  • Page 392

    392 chapter 18: debugging and troubleshooting applications debugging ip addresses page by default, when you enable debugging output, the output is visible only to local users (that is, via ip address 127.0.0.1). You can specify additional ip addresses whose users can see debugging output, or even di...

  • Page 393

    Using debugging information from browser pages 393 general debugging information coldfusion displays general debugging information. In the classic.Cfm output format, the information is at the top of the debugging output. In the dockable.Cfm output format, it looks like the following figure: (in the ...

  • Page 394

    394 chapter 18: debugging and troubleshooting applications execution time the execution time section displays the time required to process the request. It displays information about the time required to process all pages required for the request, including the application.Cfm and onrequestend.Cfm pa...

  • Page 395

    Using debugging information from browser pages 395 the next to last line of the output displays the time that coldfusion took to parse, compile, and load pages, and to start and end page processing. This figure is not included in the individual page execution times. The last line shows the sum of al...

  • Page 396

    396 chapter 18: debugging and troubleshooting applications • coldfusion took 125 ms for processing that was not associated with a specific page. • the total processing time was 328 milliseconds, the sum of 125 + 203. Database activity in the administrator, when database activity is selected on the d...

  • Page 397

    Using debugging information from browser pages 397 stored procedures the stored procedures section displays information about the results of using the cfstoredproc tag to execute a stored procedure in a database management system. The stored procedures section looks as follows in the classic.Cfm out...

  • Page 398

    398 chapter 18: debugging and troubleshooting applications the exception information includes information about any application exceptions that are caught and handled by your application code or by coldfusion mx. Exceptions represent events that disrupt the normal flow of an application. You should ...

  • Page 399

    Using debugging information from browser pages 399 using the dockable.Cfm output format the dockable.Cfm output format has several features that are not included in the classic.Cfm debugging display, as shown in the following figure of a docked debug pane: application page selections coldfusion disp...

  • Page 400

    400 chapter 18: debugging and troubleshooting applications controlling debugging information in cfml the following sections describe how you can use cfml tags and functions to display or hide debugging and tracing information. Generating debugging information for an individual query in the administr...

  • Page 401

    Using the cftrace tag to trace execution 401 you can use the isdebugmode function to selectively log information only when debugging is enabled. Because you control the log output, you have the flexibility of silently logging information without displaying trace information in the browser. For examp...

  • Page 402

    402 chapter 18: debugging and troubleshooting applications • in-line in your application page when you specify the inline attribute in a cftrace tag, coldfusion displays the trace output on the page at the cftrace tag location . ( an inline cftrace tag does not display any output if it is inside a c...

  • Page 403

    Using the cftrace tag to trace execution 403 the following table lists the contents of the trace message and the log entries. For more information on the log file format, see chapter 14, “logging errors with the cflog tag,” on page 297 . Using tracing as its name indicates, the cftrace tag is design...

  • Page 404

    404 chapter 18: debugging and troubleshooting applications • if a page has many nested cfif and cfelseif tags you can put cftrace tags in each conditional block to trace the execution flow. When you do this, you should use the condition variable in the message or var attribute. • if you find that th...

  • Page 405

    Using the code compatibility analyzer 405 note: if you specify inline trace output, and a cftrace tag is inside a cfsilent tag block, coldfusion does not display the trace information in line, but does include it in the standard debugging display. The following cftrace tag displays the information s...

  • Page 406

    406 chapter 18: debugging and troubleshooting applications you can run the code compatibility analyzer from the coldfusion mx administrator. Select code analyzer from the list of debugging & logging pages. Note: the cfml analyzer does not execute the pages that it checks. Therefore, it cannot detect...

  • Page 407

    Troubleshooting common problems 407 problem : you suspect that there are problems with the structure or contents of a complex data variable, such as a structure, array, query object, or wddx-encoded variable. Use the cfdump tag to generate a table-formatted display of the variable’s structure and co...

  • Page 408

    408 chapter 18: debugging and troubleshooting applications.

  • Page 409: Part IV

    Part iv accessing and using data this part describes how to access and use sources of data, including sql (structured query language) databases, ldap (lightweight directory access protocol) directories, and verity document collections. It provides an introduction to the sql language, describes how t...

  • Page 411: Chapter 19

    411 chapter 19 introduction to databases and sql coldfusion mx lets you create dynamic applications to access and modify data stored in a database. You do not need a thorough knowledge of databases to develop coldfusion applications, but you must know some basic concepts and techniques. This chapter...

  • Page 412

    412 chapter 19: introduction to databases and sql what is a database? A database defines a structure for storing information. Databases are typically organized into tables, which are collections of related items. You can think of a table as a grid of columns and rows. Coldfusion mx works primarily w...

  • Page 413

    What is a database? 413 to access the table to read or modify table data, you use the sql programming language. For example, the following sql statement returns all rows from the table where the department id is 3: select * from employees where deptid=3 note: in this chapter, sql keywords and syntax...

  • Page 414

    414 chapter 19: introduction to databases and sql database permissions in many database environments, a database administrator defines the access privileges for users accessing the database, usually through username and password. When a person attempts to connect to a database, the database ensures ...

  • Page 415

    Using sql 415 database design guidelines from this basic description, the following database design rules emerge: • each record should contain a unique identifier as the primary key such as an employee id, a part number, or a customer number. The primary key is typically the column used to maintain ...

  • Page 416

    416 chapter 19: introduction to databases and sql you interpret this statement as "select the columns firstname and lastname from the table employees where the deptid is 3". In addition to with reading data from a table, you can write data to a table using the sql insert statement. The following sta...

  • Page 417

    Using sql 417 case sensitivity with databases coldfusion mx is a case-insensitive programming environment. Case insensitivity means the following statements are equivalent: however, many databases, especially unix databases, are case-sensitive. Case sensitivity means that you must match exactly the ...

  • Page 418

    418 chapter 19: introduction to databases and sql reading data from a database you use the sql select statement to read data from a database. The sql statement has the following general syntax: select column_names from table_names [ where search_condition ] [ group by group_expression ] [having cond...

  • Page 419

    Using sql 419 filtering results the select statement lets you filter the results of a query to return only those records that meet specific criteria. For example, if you want to access all database records for employees in department 3, you use the following query: select * from employees where dept...

  • Page 420

    420 chapter 19: introduction to databases and sql accessing multiple tables in a database, you can have multiple tables containing related information. You can extract information from multiple tables as part of a query. In this case, you specify multiple table names in the select statement, as foll...

  • Page 421

    Using sql 421 where: • column_names specifies a comma-separated list of columns. • value_list specifies a comma-separated list of values. The order of values has to correspond to the order that you specified column names. Note: there are additional options to insert depending on your database. For a...

  • Page 422

    422 chapter 19: introduction to databases and sql deleting data from a database the delete statement removes rows from a table. The delete statement has the following syntax: delete from table_name [ where search_condition ] note: there are additional options to delete depending on your database. Fo...

  • Page 423

    Writing queries using an editor 423 the simple recordset dialog box appears: 4 complete the dialog box. 5 click the test button to execute the query and ensure that it retrieves the information you intended. If you defined a filter that uses parameters input by users, the test button displays the te...

  • Page 424

    424 chapter 19: introduction to databases and sql the advanced recordset dialog box appears: 4 complete the dialog box. 5 click the test button to execute the query and ensure that it retrieves the information you intended. If you defined a filter that uses parameters input by users, the test button...

  • Page 425

    Writing queries using an editor 425 the sql builder interface the following figure shows the sql builder interface: the sql builder is divided into the following four sections: writing sql statements sql builder opens a select statement by default, since this is the most common type of query. Sql bu...

  • Page 426

    426 chapter 19: introduction to databases and sql.

  • Page 427: Chapter 20

    427 chapter 20 accessing and retrieving data this chapter describes how to retrieve data from a database and work with query data. This chapter also shows how to use the cfquery tag to query a data source, and use the cfoutput tag to output the query results to a web page. Contents working with dyna...

  • Page 428

    428 chapter 20: accessing and retrieving data working with 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 ret...

  • Page 429

    Retrieving data 429 the cfquery tag the cfquery tag is one of the most frequently used cfml tags. You use it with the cfoutput tag to retrieve and reference the data returned from a query. When coldfusion encounters a cfquery tag on a page, it does the following: • connects to the specified data sou...

  • Page 430

    430 chapter 20: accessing and retrieving data building queries as discussed earlier in this chapter, you build queries using the cfquery tag and sql. Note: this and many subsequent procedures use the companyinfo data source that connects to the company.Mdb database. This data source is installed by ...

  • Page 431

    Outputting query data 431 coldfusion creates the emplist data set, but only html and text return to the browser. When you view the page’s source, you see only html tags and the heading “employee list.” to display the data set on the page, you must code tags and variables to output the data. Reviewin...

  • Page 432

    432 chapter 20: accessing and retrieving data #emplist.Firstname#, #emplist.Lastname#, #emplist.Salary#, #emplist.Contract# 2 save the file and view it in your web browser: a list of employees appears in the browser, with each line displaying one row of data. Note: you might need to refresh your bro...

  • Page 433

    Getting information about query results 433 query output notes and considerations when outputting query results, keep the following guidelines in mind: • a cfquery must precede the cfoutput that references its results. Both must be on the same page (unless you use the cfinclude tag; for more informa...

  • Page 434

    434 chapter 20: accessing and retrieving data the query returned #emplist.Recordcount# records. 2 save the file and view it in your web browser: the number of employees now appears below the list of employees. You might have to refresh your browser and scroll to see the recordcount output. Note: the...

  • Page 435

    Enhancing security with cfqueryparam 435 • do not use the cfoutput tag query attribute when you output the recordcount or columnlist property. If you do, you get one copy of the output for each row. Instead, prefix the variable with the name of the query. Enhancing security with cfqueryparam some db...

  • Page 436

    436 chapter 20: accessing and retrieving data the cfqueryparam tag checks that the value of emp_id is an integer data type. If anything else in the query string is not an integer, such as a sql statement to delete a table, the cfquery tag does not execute. Instead, the cfqueryparam tag returns the f...

  • Page 437: Chapter 21

    437 chapter 21 updating your database this chapter describes how to use coldfusion to insert, update, and delete information in a database. Contents about updating your datasbase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438 inserting data . . . . ...

  • Page 438

    438 chapter 21: updating your database about updating your datasbase coldfusion was originally developed as a way to readily interact with databases. You can quickly insert, update, and delete the contents of your database by using coldfusion forms, which are typically a pair of pages. One page disp...

  • Page 439

    Inserting data 439 to create an insert form: 1 create a coldfusion page with the following content: value="clear form"> 2 save the file as insert_form.Cfm in the myapps directory under your web_root and view it in your web browser. Note: the form will not work until you write an action page for it. ...

  • Page 440

    440 chapter 21: updating your database data entry form notes and considerations if you use the cfinsert tag in the action page to insert the data into the database, you should follow these rules for creating the form page: • you only need to create html form fields for the database columns into whic...

  • Page 441

    Inserting data 441 reviewing the code the following table describes the code and its function: note: if you use form variables in cfinsert or cfupdate tags, coldfusion automatically validates any form data it sends to numeric, date, or time database columns. You can use the hidden field validation f...

  • Page 442

    442 chapter 21: updating your database 2 save the page. 3 view insert_form.Cfm in your web browser and enter values. 4 click submit. Coldfusion inserts your values into the employee table and displays a confirmation message. Reviewing the code the following table describes the highlighted code and i...

  • Page 443

    Updating data 443 creating an update form the following are the key differences between an update form and an insert form: • an update form contains a reference to the primary key of the record that is being updated. A primary key is a field(s) in a database table that uniquely identifies each recor...

  • Page 444

    444 chapter 21: updating your database yes 2 save the file as update_form.Cfm. 3 view update_form.Cfm in your web browser by specifying the page url and an employee id; for example, enter the following: http://localhost/myapps/update_form.Cfm?Emp_id=3 note: although you can view an employee’s inform...

  • Page 445

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

  • Page 446

    446 chapter 21: updating your database tablename="employee"> employee updated tablename="employee"> you have updated the information for #form.Firstname# #form.Lastname# in the employee database. 2 save the page as update_action.Cfm. 3 view update_form.Cfm in your web browser by specifying the page ...

  • Page 447

    Updating data 447 reviewing the code the following table describes the code and its function: creating an update action page with cfquery for more complicated updates, you can use a sql update statement in a cfquery tag instead of a cfupdate tag. The sql update statement is more flexible for complic...

  • Page 448

    448 chapter 21: updating your database you have updated the information for #form.Firstname# #form.Lastname# in the employee database. 2 save the page. 3 view update_form.Cfm in your web browser by specifying the page url and an employee id; for example, type the following: http://localhost/myapps/u...

  • Page 449

    Deleting data 449 to delete one record from a database: 1 in update_form.Cfm, change the title to “delete form” and the text on the submit button to “delete record”. 2 change the form tag so that it appears as follows: 3 save the modified file as delete_form.Cfm. 4 create a coldfusion page with the ...

  • Page 450

    450 chapter 21: updating your database deleting multiple records you can use a sql condition to delete several records. The following example deletes the records for everyone in the sales department (which has dept_id number 4) from the employee table: delete from employee where dept_id = 4 to delet...

  • Page 451: Chapter 22

    451 chapter 22 using query of queries a query that retrieves data from a record set is called a query of queries. After you generate a record set, you can interact with its results as if they were database tables by using query of queries. This chapter describes the benefits and procedures for this ...

  • Page 452

    452 chapter 22: using query of queries about record sets query of queries is based on manipulating the record set, which you can create using the cfquery tag and other ways. When you execute a database query, coldfusion retrieves the data in a record set. In addition to presenting record set data to...

  • Page 453

    About record sets 453 creating a record set with a function in addition to creating a record set by using a cfquery or other cfml tags, you can create it with the querynew () function. To create a record set with the querynew() function: 1 create a coldfusion page with the following content: years_p...

  • Page 454

    454 chapter 22: using query of queries the following figure shows how the output appears: note: when you create a record set, you can store in it complex objects, such as arrays and structures. However, you cannot use query of queries on a record set that contains complex objects. For more informati...

  • Page 455

    About query of queries 455 • you can obtain drill-down, master-detail information for which you do not access the database for the details. For example, you can select information about departments and employees in a query, and cache the results. You can then display the employees’ names. When users...

  • Page 456

    456 chapter 22: using query of queries output using a query of query: #emp_id#: #firstname# #lastname# columns in the master query: #master.Columnlist# columns in the detail query: #detail.Columnlist# 2 save the page as query_of_query.Cfm in the myapps directory under the web_root. 3 in your browser...

  • Page 457

    About query of queries 457 reviewing the code the master query retrieves the entire employee table from the companyinfo data source (the companyinfo database). The detail query selects only the three columns to display for employees with the specified last name. The following table describes the cod...

  • Page 458

    458 chapter 22: using query of queries select * from employee order by lastname select firstname, lastname, salary from getsals order by lastname firstname lastname salary "#maxrows#"> #getsals2.Currentrow# #firstname# #lastname# #salary# "#maxrows#"> #getsals2.Currentrow# #firstname# #lastname# #sa...

  • Page 459

    About query of queries 459 maxrows)#">see next #maxrows# rows 2 save the page as qoq_next_row.Cfm in the myapps directory under the web_root . 3 in your web browser, enter the following url to display the query results: http://127.0.0.1/myapps/qoq_next_row.Cfm the following figure shows how the outp...

  • Page 460

    460 chapter 22: using query of queries to use query of queries with a verity record set: 1 create a coldfusion page with the following content: collection="bbb" type = "simple" criteria="film"> master query dump: collection="bbb" type = "simple" criteria="film"> select * from quick where quick.Score...

  • Page 461

    About query of queries 461 the first cfdump tag shows the master query, which retrieves all records. The second cfdump shows the query of queries results. Tip: adjust the score criterion of the detail query to reflect the contents of your collection. The next example shows how a query of queries com...

  • Page 462

    462 chapter 22: using query of queries the following figure shows how the output appears: query of queries user guide the following sections discuss query of queries functionality. If you know sql or have interacted with databases, you might be familiar with some of these features. Using dot notatio...

  • Page 463

    Query of queries user guide 463 coldfusion supports inner joins between two tables, as the following example shows. This operation is the most common type of join. Select dog_id, breed_id from dogs, breed where dogs.Dog_id = breed.Dog_id; using unions the union operator lets you combine the results ...

  • Page 464

    464 chapter 22: using query of queries the union statement produces the following result (union) table: using aliases for column names the column names of a union table are the column names in the result set of the first select statement in the union operation; coldfusion ignores the column names in...

  • Page 465

    Query of queries user guide 465 union select * from tablec in the first statement, there are no duplicates in the union between tableb and tablec. Then, in the union between that set and tablea, the all keyword includes the duplicates. In the second statement, duplicates are included in the union be...

  • Page 466

    466 chapter 22: using query of queries comparison conditional this conditional lets you compare an expression against another expression of the same data type (numeric, string, date, or boolean). You can use it to selectively retrieve only the relevant rows of a record set. Syntax comparison_cond ::...

  • Page 467

    Query of queries user guide 467 like conditional this conditional lets you perform wildcard searches, in which you compare your data to search patterns. This strategy differs from other conditionals, such as between or in, because the like conditional compares your data to a value that is partially ...

  • Page 468

    468 chapter 22: using query of queries the following example is not case-sensitive; it uses the lower() function to treat 'sylvester', 'sylvester', 'sylvester', and so on as all lowercase, and matches them with the all lowercase string, ‘sylvester’: select dog_name from dogs where lower(dog_name) li...

  • Page 469

    Query of queries user guide 469 example the following example uses the avg() function to retrieve the average iq of all terriers: select dog_name, avg(dog_iq) as avg_iq from dogs where breed like '%terrier'; arbitrary expressions in aggregate functions coldfusion supports aggregate functions of any ...

  • Page 470

    470 chapter 22: using query of queries examples the following example shows a simple sort using an order by clause: select acetylcholine_levels, dopamine_levels from results order by dopamine_levels the following example shows a more complex sort; results are first sorted by ascending levels of dopa...

  • Page 471

    Query of queries user guide 471 having example select (lorange+hirange)/2 as x, count(*) from roysched group by x having x > 10000 handling null values coldfusion uses boolean logic to handle conditional expressions. Proper handling of null values requires the use of ternary logic. The is [not] null...

  • Page 472

    472 chapter 22: using query of queries the following table lists coldfusion reserved keywords: absolute action add all allocate alter and any are as asc assertion at authorization avg begin between bit bit_length both by cascade cascaded case cast catalog char character character_ length char_length...

  • Page 473

    Query of queries user guide 473 using queries of queries with numeric dates if you create a query object with querynew() and populate a column with dates in numeric format (for example, 12/24/02), the dates are preserved as a string inside the query object until a query of queries is applied to the ...

  • Page 474

    474 chapter 22: using query of queries when working with a query resulting from a sql join, query of queries performs as follows: • query of queries is very efficient for simple joins in which there is only one equality between two column references; for example: select t1.A, b, c, d from t1, t2 whe...

  • Page 475

    Bnf for query of queries 475 null_cond ::= row_constructor ( )? Comparison_cond ::= row_constructor comparison_operator row_constructor between_cond ::= row_constructor ( )? Row_constructor row_constructor in_cond ::= row_constructor ( )? ( expression_list ) row_constructor ::= expression comparison...

  • Page 476

    476 chapter 22: using query of queries.

  • Page 477: Chapter 23

    477 chapter 23 managing ldap directories cfml applications use the cfldap tag to access and manage ldap (lightweight directory access protocol) directories. This chapter provides information on how to use this tag to view, query, and update ldap directories. This chapter teaches you how to query and...

  • Page 478

    478 chapter 23: managing ldap directories about ldap the ldap protocol enables organizations to arrange and access directory information in a hierarchy. In this context, directory refers to a collection of information, such as a telephone directory, not a collection of files in a folder on a disk dr...

  • Page 479

    The ldap information structure 479 the following figure show such an asymmetric directory: in this directory structure, the second level of the tree divides the directory into two organizational units: people and groups. The third level contains entries with information that is specific to the organ...

  • Page 480

    480 chapter 23: managing ldap directories entry the basic information object of ldap is the entry. An entry is composed of one or more attributes. Entries are subject to content rules defined by the directory schema (see “schema” on page 481 ). Each node, not just the terminal nodes, of an ldap dire...

  • Page 481

    The ldap information structure 481 an entry’s dn consists of an entry’s rdn followed by the dn of its parent. In other words, it consists of the rdns for the entry and each of the entry’s parent entries, up to the root of the directory tree. The rdns are separated by commas and optional spaces. For ...

  • Page 482

    482 chapter 23: managing ldap directories attribute type a schema’s attribute type specification defines the following properties: • the attribute type name • a unique object id that identifies the attribute type • (optional) an indication of whether the type is single-valued or multivalued (the def...

  • Page 483

    Querying an ldap directory 483 querying an ldap directory the cfldap tag lets you search an ldap directory. The tag returns a coldfusion query object with the results, which you can use as you would any query result. When you query an ldap directory, you specify the directory entry where the search ...

  • Page 485

    Querying an ldap directory 485 • if you use filter operators to construct sophisticated search criteria, performance might degrade if the ldap server is slow to process the synchronous search routines that cfldap supports. You can use the cfldap tag timeout and maxrows attributes to control the appa...

  • Page 486

    486 chapter 23: managing ldap directories enter a full name, first name, last name, or name fragment. Server="ldap.Airius.Com" action="query" name="results" start="ou=people, o=airius.Com" scope="onelevel" filter="(&(cn=*#form.Name#*)(l=santa clara))" attributes="cn,sn,ou,mail,telephonenumber" sort=...

  • Page 487

    Querying an ldap directory 487 reviewing the code the following table describes the code: code description uses a form to get the name or name fragment to search for. And (form.Name is not ""))> ensures that the user has submitted the form. This is necessary because the form page is also the action ...

  • Page 488

    488 chapter 23: managing ldap directories this search shows the use of a logical and statement in a filter. It returns one attribute, the surname, that is used only for sorting the results. In this query, the ou attribute value consists of two values in a comma-delimited list. One is the department ...

  • Page 489

    Updating an ldap directory 489 adding a directory entry when you add an entry to an ldap directory, you specify the dn, all the required attributes, including the entry’s object class, and any optional attributes. The following example builds a form that adds an entry to an ldap directory. To add an...

  • Page 490

    490 chapter 23: managing ldap directories name="fullname" value=#fullnamevalue# size="20" maxlength="30" tabindex="1"> name="surname" value= "#surnamevalue#" size="20" maxlength="20" tabindex="2"> name="email" value="#emailvalue#" size="20" maxlength="20" tabindex="3"> name="phone" value="#phonevalu...

  • Page 491

    Updating an ldap directory 491 action="query" attributes="cn,sn,mail,telephonenumber,uid" start="o=airius.Com" scope="subtree" filter="ou=human resources" sort="sn,cn" sortcontrol="asc, nocase"> 2 at the top of the file, change the myserver, myusername, and mypassword variable assignments to values ...

  • Page 492

    492 chapter 23: managing ldap directories or trim(form.Surname) is "" or trim(form.Email) is "" or trim(form.Phone) is ""> you must enter a value in every or trim(form.Surname) is "" or trim(form.Email) is "" or trim(form.Phone) is ""> field. Form.Fullname> form.Surname> if any field in the submitte...

  • Page 493

    Updating an ldap directory 493 deleting a directory entry to delete a directory entry, you must specify the entry dn. The following example builds on the code that adds an entry. It adds retrieve and delete buttons. The retrieve button lets you view a user’s information in the form before you delete...

  • Page 494

    494 chapter 23: managing ldap directories username=#myusername# password=#mypassword#> entry for user id #form.Uid# has been deleted 3 at the end of the code for the add button (the input tag with value=add at the bottom of the form ) , delete the end tag. 4 after the end of the add button input tag...

  • Page 495

    Updating an ldap directory 495 updating a directory entry the cfldap tag lets you change the values of entry attributes. To do so, you specify the entry dn in the dn attribute, and list the attributes to change and their new values in the attributes attribute. The following example builds on the cod...

  • Page 496

    496 chapter 23: managing ldap directories reviewing the code the following table describes the code: adding and deleting attributes of a directory entry the following table lists the cfldap tag attributes that you must specify to add and delete ldap attributes in an entry: you can add or delete mult...

  • Page 497

    Advanced topics 497 changing a directory entry’s dn to change the dn of an entry, you must provide the following information in the cfldap tag: dn="original dn" action="modifydn" attributes="dn=new dn" for example: dn="#old_uid#, ou=people, o=airius.Com" attributes="uid=#newuid#" server=#myserver# u...

  • Page 498

    498 chapter 23: managing ldap directories using cfldap output you can create a searchable verity collection from ldap data. For an example of building a verity collection using an ldap directory, see chapter 24, “indexing cfldap query results,” on page 530 . The ability to generate queries from othe...

  • Page 499

    Advanced topics 499 thiselement = trim(thiselement); nameloc = find("name", thiselement); descloc = find("desc", thiselement); suploc = find("sup", thiselement); mustloc = find("must", thiselement); mayloc = find("may", thiselement); endloc = len(thiselement); mayloc-mustloc-9), " $ ", ", ", "all")#...

  • Page 500

    500 chapter 23: managing ldap directories endloc = len(thiselement); 2 change the server from ldap.Mycorp.Com to your ldap server. You might also need to specify a user id and password in the cfldap tag. 3 save the template as ldapschema.Cfm in myapps under your web root directory and view it in you...

  • Page 501

    Advanced topics 501 #entrylist2.Objectclasses#> thiselement = trim(thiselement); nameloc = find("name", thiselement); descloc = find("desc", thiselement); suploc = find("sup", thiselement); mustloc = find("must", thiselement); mayloc = find("may", thiselement); endloc = len(thiselement); displays th...

  • Page 502

    502 chapter 23: managing ldap directories referrals an ldap database can be distributed over multiple servers. If the requested information is not on the current server, the ldap v3 standard provides a mechanism for the server to return a referral to the client that informs the client of an alternat...

  • Page 503

    Advanced topics 503 managing ldap security when you consider how to implement ldap security, you must consider server security and application security. Server security the cfldap tag supports secure socket layer (ssl) v2 security. This security provides certificate- based validation of the ldap ser...

  • Page 504

    504 chapter 23: managing ldap directories the port attribute specifies the server port used for secure ldap communications, which is 636 by default. If you do not specify a port, coldfusion attempts to connect to the default, nonsecure, ldap port 389. Application security to ensure application secur...

  • Page 505: Chapter 24

    505 chapter 24 building a search interface you can provide a full-text search capability for documents and data sources on a coldfusion site by enabling the verity search engine. This chapter describes how to build a verity search interface with which users can perform powerful searches on your appl...

  • Page 506

    506 chapter 24: building a search interface about verity to efficiently search through paragraphs of text or files of varying types, you need full-text search capabilities. Coldfusion includes the verity search engine, which provides full-text indexing and searching. The verity engine performs searc...

  • Page 507

    About verity 507 advantages of using verity verity can index the output from queries so that you or a user can search against the record sets. Searching query results has a clear advantage over using sql to search a database directly in speed of execution because metadata from the record sets are st...

  • Page 508

    508 chapter 24: building a search interface • microsoft works (v1.0, 2.0, 3.0, 4.0) • microsoft write (v1.0, 2.0, 3.0) • pdf (verity pdf filter) • text files (verity text filter) • unicode text (all versions) • wordperfect (v5.X, 6, 7, 8) • wordperfect mac (v2, 3) • xywrite (v4.12) spreadsheet forma...

  • Page 509

    About verity 509 • microsoft windows metafile (wmf) • pc paintbrush (pcx) • portable network graphics (png) • sun raster sgi rgb • truevision targa • tiff • wordperfect graphics (wpg) v1, 2 multimedia formats • audio interchange file format (aiff) • microsoft sound (wav) • midi (mid) • mpeg 1 video ...

  • Page 510

    510 chapter 24: building a search interface you can register collections in the administrator or by creating a collection with the cfcollection tag. If you register a given collection with coldfusion and you specify a language attribute, then you do not have to specify the language attribute when us...

  • Page 511

    Creating a search tool for coldfusion applications 511 creating a search tool for coldfusion applications there are three main tasks in creating a search tool for your coldfusion application: 1 create a collection. 2 index the collection. 3 design a search interface. You can perform each task progra...

  • Page 512

    512 chapter 24: building a search interface creating a collection with the coldfusion mx administrator use the following procedure to quickly create a collection with the coldfusion mx administrator: to create a collection with the coldfusion mx administrator: 1 in the coldfusion mx administrator, s...

  • Page 513

    Creating a search tool for coldfusion applications 513 note: you can map a collection currently available on your network or local disk by creating a local reference (an alias) for that collection. In this procedure, enter the collection alias as the collection name, and enter a unc (universal namin...

  • Page 514

    514 chapter 24: building a search interface indexing and building a search interface with the verity wizard if you have homesite+, you can use the verity wizard to generate a basic search and index interface. Use the following procedure to quickly create a search application for a collection. This p...

  • Page 515

    Creating a search tool for coldfusion applications 515 5 click next. The select collection window appears: 6 enter the following information: 7 click next. The indexing settings window appears: field description example collection name the name of the collection you created in the coldfusion mx admi...

  • Page 516

    516 chapter 24: building a search interface 8 enter the following information: 9 click finish. The wizard generates four coldfusion pages to the directory you specified in step 4, and displays an output summary. Note: the filenames are in the format pagetitle_vpagename.Cfm, where pagetitle is the va...

  • Page 517

    Creating a search tool for coldfusion applications 517 13 click the web browser’s back button to return to the search form. 14 enter your search term(s); for example, verity and data source. Tip: for more information on the verity search syntax, see “using verity search expressions” on page 535 . 15...

  • Page 518

    518 chapter 24: building a search interface creating a coldfusion search tool programmatically you can create a verity search tool for your coldfusion application in cfml. Although writing cfml code can take more development time than using these tools, there are situations in which writing code is ...

  • Page 519

    Creating a search tool for coldfusion applications 519 name="collectionaction" value="repair">repair name="collectionaction" value="optimize">optimize name="submit" value="submit"> 2 save the file as collection_create_form.Cfm in the myapps directory under the web root directory . Note: the form wil...

  • Page 520

    520 chapter 24: building a search interface 2 save the file as collection_create_action.Cfm in the myapps directory under the web root directory . 3 in the web browser, enter the following url to display the form page: http://127.0.0.1/myapps/collection_create_form.Cfm the following figure shows how...

  • Page 521

    Creating a search tool for coldfusion applications 521 you can use form and action pages similar to the following examples to select and index a collection. To select which collection to index: 1 create a coldfusion page with the following content: enter the collection you want to index: enter the l...

  • Page 522

    522 chapter 24: building a search interface the following figure shows how the output appears: 1 enter a collection name; for example, codecoll. 2 enter a file location; for example, c:\cfusionmx\wwwroot\vw_files. 3 click index. A confirmation message appears upon successful completion. Note: for in...

  • Page 523

    Using the cfsearch tag 523 this interface lets you easily build a very specific index based on the file extension and path information you enter. In most cases, you do not need to change your server file structures to accommodate the generation of indices. Using the cfsearch tag you use the cfsearch...

  • Page 524

    524 chapter 24: building a search interface enter search term(s) in the box below. You can use and, or, not, and parentheses. Surround an exact phrase with quotation marks. 2 save the file as collection_search_form.Cfm. Enter a search target word(s) in this form, which passes this as the variable cr...

  • Page 525

    Using the cfsearch tag 525 3 view collection_search_form.Cfm in the web browser: 4 enter a target word(s) and click search. The following figure shows how the output appears: note: as part of the indexing process, verity automatically produces a summary of every document file or every query record s...

  • Page 526

    526 chapter 24: building a search interface working with record sets the cfquery , cfldap , and cfpop tags return the results of a database query in a record set. In some cases, you might want to search the record set. This section describes the reasons and procedures for indexing the results of dat...

  • Page 527

    Working with record sets 527 to index a coldfusion query: 1 create a coldfusion page with the following content: select * from employee query="getemps" collection="codecoll" action="update" type="custom" key="emp_id" title="emp_id" body="emp_id,firstname,lastname,salary"> indexing complete query="ge...

  • Page 528

    528 chapter 24: building a search interface the resulting record set appears: using the cfindex tag for indexing tabular data is similar to indexing documents, with the following exceptions: • you set the type attribute to custom when indexing tabular data. • you refer to column names from the cfque...

  • Page 529

    Working with record sets 529 2 save the file as collection_db_search_form.Cfm in the myapps directory under the web_root. This file is similar to collection_search_form.Cfm, except the form uses collection_db_results.Cfm, which you create in the next step, as its action page. 3 create another coldfu...

  • Page 530

    530 chapter 24: building a search interface the following figure shows how the output appears: indexing cfldap query results the widespread use of the lightweight directory access protocol (ldap) to build searchable directory structures, internally and across the web, gives you opportunities to add ...

  • Page 531

    Working with record sets 531 start="c=us"> dn: #dn# o: #o# telephonenumber: #telephonenumber# mail: #mail# ============================= collection="ldap_query" key="dn" type="custom" title="o" query="orglist" body="telephonenumber"> name="s_ldap" criteria="*617*"> #key#, #title#, #body# indexing cf...

  • Page 532

    532 chapter 24: building a search interface collection="pop_query" key="messagenumber" type="custom" title="subject" query="p_messages" body="body"> name="s_messages" criteria="action"> #key#, #title# using database-directed indexing you can use the cfindex tag with a database that contains informat...

  • Page 533

    Working with record sets 533 key="description" urlpath="url"> key="description" urlpath="url"> use the following code to search the snippets collection and display the results: the following code shows how to populate the snippets collection with paths that are specified in the description column of...

  • Page 534

    534 chapter 24: building a search interface.

  • Page 535: Chapter 25

    535 chapter 25 using verity search expressions this chapter describes verity search expressions and how you can refine your searches to yield the most accurate results. Contents about verity query types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ....

  • Page 536

    536 chapter 25: using verity search expressions about verity query types when you search a verity collection, you can use either a simple or explicit query. The following table compares the two types: the query type determines whether the search words that you enter are stemmed, and whether the retr...

  • Page 537

    Using simple queries 537 stemming in simple queries by default, verity interprets words in a simple query as if you entered the stem operator (and many modifier). The stem operator searches for words that derive from a common stem. For example, a search for instructional returns files that contain i...

  • Page 538

    538 chapter 25: using verity search expressions the results of this search show the effects of the stem operator and many modifier: in cfml, enter your search term(s) in the criteria attribute of the cfsearch tag: collection="bbb" type="simple" criteria="instructional"> preventing stemming when ente...

  • Page 539

    Using explicit queries 539 using explicit queries in an explicit query, the verity search engine literally interprets your search terms. The following are two ways to perform an explicit query: • on a search form, use quotation marks around your search term(s). • in cfml, use type=”explicit ” in the...

  • Page 540

    540 chapter 25: using verity search expressions the following table gives examples of searches and their results: using wildcards and special characters part of the strength of the verity search is its use of wildcards and special characters to refine searches. Wildcard searches are especially usefu...

  • Page 541

    Using explicit queries 541 to search for a wildcard character as a literal, place a backslash character before it; for example: • to match a question mark or other wildcard character, precede the ? With one backslash. For example, type the following in a search form: checkers\? • to match a literal ...

  • Page 542

    542 chapter 25: using verity search expressions you can use paired backquotes or backslashes to escape special characters. There is no functional difference between the two. For example, you can query for the term: using \ or `` as your search term. Composing search expressions the following rules a...

  • Page 543

    Composing search expressions 543 precedence rules expressions are read from left to right. The and operator takes precedence over the or operator; however, terms enclosed in parentheses are evaluated first. When the search engine encounters nested parentheses, it starts with the innermost term. Deli...

  • Page 544

    544 chapter 25: using verity search expressions the following operator types are available: the following table shows the operators, according to type, that are available for conducting searches of coldfusion verity collections: concept operators concept operators combine the meaning of search eleme...

  • Page 545

    Composing search expressions 545 relational operators relational operators search document fields (such as author) that you defined in the collection. Documents containing specified field values are returned. Documents retrieved using relational operators are not ranked by relevance, and you cannot ...

  • Page 546

    546 chapter 25: using verity search expressions the following relational operators compare text and match words and parts of words: for example, assume a document field named source includes the following values: • computer • computerworld • computer currents • pc computing to locate documents whose...

  • Page 547

    Composing search expressions 547 to locate documents whose source is computer, computerworld, computer currents, and pc computing, enter the following: source *comput* for an example of coldfusion code that uses the contains relational operator, see “field searches” on page 553 . You can use the sub...

  • Page 548

    548 chapter 25: using verity search expressions search results -- should be 1 row #gettext_search.Title# evidence operators evidence operators let you specify a basic word search or an intelligent word search. A basic word search finds documents that contain only the word or words specified in the q...

  • Page 549

    Composing search expressions 549 the following example uses an evidence operator: collection="bbb" type = "explicit" criteria="film"> proximity operators proximity operators specify the relative location of specific words in the document. To retrieve a document, the specified words must be in the sa...

  • Page 550

    550 chapter 25: using verity search expressions the following example uses a proximity operator: collection="bbb" type = "explicit" criteria="redsocks"> for an example using the in proximity operator to search xml documents , see “zone searches” on page 552 . Score operators score operators control ...

  • Page 551

    Composing search expressions 551 modifiers you combine modifiers with operators to change the standard behavior of an operator in some way. The following table describes the available modifiers: modifier description example case specifies a case-sensitive search. Normally, verity searches are case-i...

  • Page 552

    552 chapter 25: using verity search expressions refining your searches with zones and fields one of the strengths of verity is its ability to perform full-text searches on documents of many formats. However, there are often times when you want to restrict a search to certain portions of a document, ...

  • Page 553

    Refining your searches with zones and fields 553 the above search for pete returns this xml file because this search target is in the comment_a field. In contrast, pete is the lead guitarist in the following xml file: pete roger john kenny who knows who's better than this band? Ticket prices correla...

  • Page 554

    554 chapter 25: using verity search expressions you can specify the values for the cfindex attributes title, key, url, and custom as document fields for use with relational operators in the criteria attribute. (the score and summary attributes are automatically returned by a cfsearch ; these attribu...

  • Page 555

    Refining your searches with zones and fields 555 the following code shows the cfindex tag for indexing the collection (the type attribute is set to custom for tablular data): query = "calls" collection = "training" action = "update" type = "custom" title = "short_description" key = "call_id" body = ...

  • Page 556

    556 chapter 25: using verity search expressions.

  • Page 557: Part V

    Part v requesting and presenting information this part describes how to dynamically request information from users and display information on their browsers. It includes information on using the html form tag, cfml cfform tag, and other coldfusion tags to request data from users; how to use the cfch...

  • Page 559: Chapter 26

    559 chapter 26 retrieving and formatting data this chapter explains how to use html forms to control the data displayed by a dynamic web page. It also describes how to populate an html table with query results and how to use coldfusion functions to format and manipulate data. Contents using forms to...

  • Page 560

    560 chapter 26: retrieving and formatting data using forms to specify the data to retrieve in the examples in previous chapters, you retrieved all of the records from a database table using a sql query. However, there are many instances when you want to retrieve data based on certain criteria. For e...

  • Page 561

    Using forms to specify the data to retrieve 561 form controls within the form, you describe the form controls needed to gather and submit user input. There are a variety of form controls types available. You select form control input types based on the type input you want to user to provide. The fol...

  • Page 562

    562 chapter 26: retrieving and formatting data first name: maxlength="35"> last name: salary: city arlington boston cambridge minneapolis seattle department: training sales value="marketing">marketing> contractor? Value="yes" checked>yes 2 save the page as formpage.Cfm within the myapps directory un...

  • Page 563

    Using forms to specify the data to retrieve 563 reviewing the code the following table describes the highlighted code and its function: form notes and considerations when using forms, keep the following guidelines in mind: • to make the coding process easy to follow, name form controls the same as t...

  • Page 564

    564 chapter 26: retrieving and formatting data • check boxes, radio buttons, and multiple select boxes do not pass to action pages unless they are selected on a form. If you try to reference these variables on the action page, you receive an error if they are not present. For information on how to d...

  • Page 565

    Working with action pages 565 however, instead of putting the lastname directly in the sql where clause, you can use the text that the user entered in the form for comparison: select firstname, lastname, salary from employee where lastname= cfsqltype="cf_sql_varchar"> for security, this example enca...

  • Page 566

    566 chapter 26: retrieving and formatting data reviewing the code the following table describes the highlighted code and its function: testing for a variable's existence before relying on a variable’s existence in an application page, you can test to see if it exists using the coldfusion isdefined f...

  • Page 567

    Working with queries and data 567 to require entry in an input field, use a hidden field that has a name attribute composed of the field name and the suffix "_required." for example, to require that the user enter a value in the firstname field, use the following syntax: if the user leaves the first...

  • Page 568

    568 chapter 26: retrieving and formatting data select firstname, lastname, salary from employee where lastname= cfsqltype="cf_sql_varchar"> employee data based on criteria from form cfsqltype="cf_sql_varchar"> first name last name salary #firstname# #lastname# #salary# first name last name salary #f...

  • Page 569

    Working with queries and data 569 formatting individual data items you can format individual data items. For example, you can format the salary field as a monetary value. To format the salary using the dollar format, you use the cfml expression dollarformat (number) . To change the format of the sal...

  • Page 570

    570 chapter 26: retrieving and formatting data 3 save the file. 4 view formpage.Cfm in your browser. 5 select a department, optionally enter a last name, and submit the form. Reviewing the code the following table describes the highlighted code and its function: returning results to the user when yo...

  • Page 571

    Returning results to the user 571 handling no query results your code must accommodate the cases where a query does not return any records. To determine whether a search has retrieved records, use the recordcount query variable. You can use the variable in a conditional logic expression that determi...

  • Page 572

    572 chapter 26: retrieving and formatting data 3 save the file. 4 return to the form, enter search criteria, and submit the form. 5 if no records match the criteria you specified, the message appears. Returning results incrementally you can use the cfflush tag to incrementally output long-running re...

  • Page 573

    Returning results to the user 573 the following example uses the cfloop tag and the rand random number generating function to artificially delay the generation of data for display. It simulates a situation in which it takes time to retrieve the first data and additional information becomes available...

  • Page 574

    574 chapter 26: retrieving and formatting data dynamically populating list boxes in “form controls” on page 561 , you hard-coded a form's list box options. Instead of manually entering the information on a form, you can dynamically populate a list box with database fields. When you code this way, th...

  • Page 575

    Dynamically populating list boxes 575 #getdepartments.Location# department: training sales marketing hr contractor? 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. Review...

  • Page 576

    576 chapter 26: retrieving and formatting data creating dynamic check boxes and multiple-selection list boxes when an html form contains either a list of check boxes with the same name or a multiple- selection list box (that is, where users can select multiple items from the list), the user's entrie...

  • Page 577

    Creating dynamic check boxes and multiple-selection list boxes 577 the coldfusion server sends the following statement to the database: select * from departmt where dept_id in ( 2,4 ) handling string values to search for a database field containing string values (instead of numeric), you must modify...

  • Page 578

    578 chapter 26: retrieving and formatting data multiple selection lists coldfusion treats the result when a user selects multiple choices from a list box (html input type select with attribute multiple ) just like results of selecting multiple check boxes. The data made available to your page from a...

  • Page 579

    Validating form field data types 579 the following statement is sent to the database: select * from departmt where dept_name in ('marketing','sales') validating form field data types one limitation of standard html forms is that you cannot validate that users input the type or range of data you expe...

  • Page 580

    580 chapter 26: retrieving and formatting data to validate the data that users enter in the insert form: 1 create a new page with the following text: name="startdate_required" value="you must enter a start date."> name="startdate_date" value="enter a valid date as the start date."> name="salary_requ...

  • Page 581

    Validating form field data types 581 because numeric values often contain commas and dollar signs, these characters are automatically deleted from fields with _integer , _float , or _range rules before the form field is validated and the data is passed to the form's action page. Reviewing the code t...

  • Page 582

    582 chapter 26: retrieving and formatting data.

  • Page 583: Chapter 27

    583 chapter 27 building dynamic forms this chapter describes how to use the cfform tag to enrich your html forms with sophisticated graphical controls, including several java applet-based controls. You can use these controls without writing a line of java code. Contents creating forms with the cffor...

  • Page 584

    584 chapter 27: building dynamic forms creating forms with the cfform tag you already learned how to use html forms to gather user input (see chapter 26, “retrieving and formatting data,” on page 559 ). This chapter shows you how to use the cfform tag to create dynamic forms in cfml. In addition to ...

  • Page 585

    Creating forms with the cfform tag 585 preserving input data with preservedata the cfform attribute preservedata tells coldfusion to continue displaying the data that a user entered in the form after the user submits the form. Data is preserved in the cfinput , cfslider , cftextinput , and cftree co...

  • Page 586

    586 chapter 27: building dynamic forms because java is handled by the plug-in and not directly by the browser, disabling java execution in the browser does not affect the operation of the controls. If for some other reason, however, the browser is unable to render the controls as requested, a "notsu...

  • Page 587

    Building tree controls with cftree 587 the following figure shows the output of this code: reviewing the code the following table describes the highlighted code and its function: grouping output from a query in a query that you display using a cftree control, you might want to organize your employee...

  • Page 588

    588 chapter 27: building dynamic forms to organize the tree based on ordered results of a query: 1 create a coldfusion page named tree2.Cfm with the following content: select dept_id, firstname + ' ' + lastname as fullname from employee order by dept_id hscroll="no" border="yes" height="350" require...

  • Page 589

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

  • Page 590

    590 chapter 27: building dynamic forms structuring tree controls tree controls built with cftree can be very complex. Knowing how to specify the relationship between multiple cftreeitem entries helps you handle the most complex of cftree constructs. Creating a one-level tree control the following ex...

  • Page 591

    Building tree controls with cftree 591 the following code populates the tree directly, not from a query: border="no"> parent="divisions" img="folder"> parent="development"> parent="development"> parent="product two" img="document"> parent="product two" img="document"> parent="development"> parent="d...

  • Page 592

    592 chapter 27: building dynamic forms • folder • floppy • fixed • remote note: you can also control the tree appearance by using the lookandfeel attribute to specify a windows, motif, or metal look. Embedding urls in a cftree the href attribute in the cftreeitem tag lets you designate tree items as...

  • Page 593

    Building drop-down list boxes 593 reviewing the code the following table describes the highlighted code and its function: specifying the tree item in the url when a user clicks on a tree item to link to a url, the cftreeitemkey variable, which identifies the selected value, is appended to the url in...

  • Page 594

    594 chapter 27: building dynamic forms size="8"> 2 save the file as selectbox.Cfm and view it in your browser. The following figure shows the output of this code: because the tag includes the multiple attribute, the user can select multiple entries in the list box. Also, because the value tag specif...

  • Page 595

    Creating data grids with cfgrid 595 2 save the file as textentry.Cfm and view it in your browser. The following figure shows the output of this code: to get the value of the input text in the action page, use the variable form.Textinput_name; in this case, form.Entertext. Building slider bar control...

  • Page 596

    596 chapter 27: building dynamic forms you can also do the following tasks with cfgrid : • sort data in the grid alphanumerically • update, insert, and delete data • display images in the grid users can sort the grid entries in ascending order by double-clicking any column header. Double- clicking a...

  • Page 597

    Creating data grids with cfgrid 597 to populate a grid from a query: 1 create a new coldfusion page named grid1.Cfm with the following contents: select * from employee selectmode="single"> note: use the cfgridcolumn display="no" attribute to hide columns that you want to include in the grid but not ...

  • Page 598

    598 chapter 27: building dynamic forms reviewing the code the following table describes the highlighted code and its function: code description query="empdata" create a grid named "employee_grid" and populate it with the results of the query "empdata". If you specify a cfgrid tag with a query attrib...

  • Page 599

    Creating data grids with cfgrid 599 creating an editable grid you can build grids to allow users to edit data within them. Users can edit individual cell data, as well as insert, update, or delete rows. To enable grid editing, you specify selectmode="edit" in the cfgrid tag. To let users add or dele...

  • Page 600

    600 chapter 27: building dynamic forms how user edits are returned coldfusion creates the following arrays as form variables to return edits to grid rows and cells: when a user selects and changes data in a row, coldfusion creates arrays to store the following information for rows that are updated, ...

  • Page 601

    Creating data grids with cfgrid 601 editing data in cfgrid to enable grid editing, specify the selectmode="edit" attribute. When enabled, a user can edit cell data and insert or delete grid rows. When the user submits a cfform tag containing a cfgrid tag, data about changes to grid cells gets return...

  • Page 602

    602 chapter 27: building dynamic forms the following figure shows the output of this code: the following sections describe how to write handle_grid.Cfm to process user edits to the grid. Reviewing the code the following table describes the code and its function: code description height=425 width=300...

  • Page 603

    Creating data grids with cfgrid 603 updating the database with cfgridupdate the cfgridupdate tag provides a simple mechanism for updating the database, including inserting and deleting records. It can add, update, and delete records simultaneously. It is particularly convenient because it automatica...

  • Page 604

    604 chapter 27: building dynamic forms to update the data source with cfquery: 1 create a coldfusion page with the following content: #arraylen(form.Employee_grid.Rowstatus.Action)#> the row action for #counter# is: #form.Employee_grid.Rowstatus.Action[counter]# datasource="companyinfo"> delete from...

  • Page 605

    Creating data grids with cfgrid 605 values ( value="#form.Employee_grid.Lastname[counter]#" cfsqltype="cf_sql_varchar" >, cfsqltype="cf_sql_integer" >) click here to display updated grid. Value="#form.Employee_grid.Lastname[counter]#" cfsqltype="cf_sql_varchar" >, cfsqltype="cf_sql_integer" >) click...

  • Page 606

    606 chapter 27: building dynamic forms embedding java applets the cfapplet tag lets you embed java applets either on a coldfusion page or in a cfform . To use cfapplet , you must first register your java applet using the coldfusion mx administrator java applets page (under extensions). In the admini...

  • Page 607

    Embedding java applets 607 the java applets page appears. 3 click the register new applet button. The add/registered java applet page appears. 4 enter options for the following settings: 5 click submit. Applet registration fields the following table explains the applet registration fields: setting d...

  • Page 608

    608 chapter 27: building dynamic forms using cfapplet to embed an applet after you register an applet, you can use the cfapplet tag to place the applet in a coldfusion page. The cfapplet tag has two required attributes: appletsource and name . Because you registered the applet and you defined each a...

  • Page 609

    Input validation with cfform controls 609 handling form variables from an applet the cfapplet tag requires you to specify a form variable name for the applet. This variable, referenced like other coldfusion form variables, form.Variable_name holds the value the applet method returns when it is execu...

  • Page 610

    610 chapter 27: building dynamic forms when you specify an input type in the validate attribute, coldfusion tests for the specified input type when you submit the form, and submits form data only on a successful match. A successful form submission returns the value true and returns the value false i...

  • Page 611

    Input validation with cfform controls 611 • you can make regular expressions case insensitive by substituting individual characters with character sets, for example, [nn][ii][cc][kk]. • you can use the following escape sequences to match specific characters or character classes: multicharacter regul...

  • Page 612

    612 chapter 27: building dynamic forms • the dollar sign ($) at the end of a regular expression matches the end of the field. • the concatenation of regular expressions creates a regular expression that matches the corresponding concatenation of strings. For example, [a-z][a-z]* matches any capitali...

  • Page 613

    Input validation with javascript 613 exact and partial matches entered data is normally valid if any of it matches the regular expression pattern. Often you might ensure that the entire entry matches the pattern. If so, you must “anchor” it to the beginning and end of the field as follows: • if a ca...

  • Page 614

    614 chapter 27: building dynamic forms coldfusion passes the following arguments to the javascript function you specify in the onvalidate attribute: • the form object • the javascript input object corresponding to the tag whose value is being validated • the value of the control to validate for exam...

  • Page 615

    Input validation with javascript 615 example: validating an e-mail address the following example validates an e-mail entry. If the string is invalid, it displays a message box. If the address is valid, it redisplays the page. To be valid, the e-mail address must not be an empty string, contain an at...

  • Page 616

    616 chapter 27: building dynamic forms reviewing the code the following table describes the highlighted code and its function: code description javascript code that tests for valid entry in the text box. The if statement checks to making sure that the field is not empty and contains an at sign (@) t...

  • Page 617: Chapter 28

    617 chapter 28 charting and graphing data this chapter explains how to use the cfchart tag to display charts and graphs. It describes ways that you can chart data and gives you the tools you need to create effective charts. Contents creating a chart . . . . . . . . . . . . . . . . . . . . . . . . . ...

  • Page 618

    618 chapter 28: charting and graphing data creating a chart the ability to display data in a chart or graph can make data interpretation much easier. Rather than present a simple table of numeric data, you can display a bar, pie, line, or other applicable type of chart using colors, captions, and a ...

  • Page 619

    Creating a chart 619 creating a basic chart to create a chart, you use the cfchart tag along with at least one cfchartseries tag. You can optionally include one or more cfchartdata tags within a cfchartseries tag. The following table describes these tags: the following shows the basic code you use t...

  • Page 620

    620 chapter 28: charting and graphing data in this example, the data from the query column avgbydept supplies the data for the y-axis, and the query column dept_name provides the data for the x-axis. The resulting chart looks like the following: administering charts use the coldfusion mx administrat...

  • Page 621

    Charting data 621 charting data one of the most important considerations when you chart data is the way you supply the data to the cfchart tag. You can supply data in the following ways: • provide all the data in a single query using cfchartseries tags. • specify individual data points using cfchart...

  • Page 622

    622 chapter 28: charting and graphing data to chart a query of queries: 1 create a new coldfusion page with the following content: select departmt.Dept_name, employee.Salary from departmt, employee where departmt.Dept_id = employee.Dept_id select dept_name, avg(salary) as avgbydept from getsalaries ...

  • Page 623

    Charting data 623 2 save the page as chartdata.Cfm in myapps under the web root directory. For example, the directory path on windows might be c:\inetpub\wwwroot\myapps. 3 return to your browser and enter the following url to view chartdata.Cfm: http://127.0.0.1/myapps/chartdata.Cfm the following fi...

  • Page 624

    624 chapter 28: charting and graphing data you can also rewrite this example to use the cfoutput and cfchartdata tags within the cfchartseries tag, instead of using the loop, to round the salary data, as the following code shows: type="bar" seriescolor="olive" paintstyle="plain"> type="bar" seriesco...

  • Page 625

    Charting data 625 the cfchartdata tag lets you specify the following information about a data point: combining a query and data points to chart data from both query and individual data values, you specify the query name, and related attributes, in the cfchartseries tag, and provide additional data p...

  • Page 626

    626 chapter 28: charting and graphing data the following figure shows these options for combining two bar charts: you can also combine chart types. The following is a combination bar and line chart: the only chart type that you cannot mix with others is the pie chart. If you define one of the data s...

  • Page 627

    Charting data 627 type="bar" query="deptsalaries" valuecolumn="avgbydept" itemcolumn="dept_name" seriescolor="gray" paintstyle="plain" serieslabel="dept. Average salaries" /> 3 save the page as chart2queries.Cfm in myapps under the web root directory. For example, the directory path on windows might...

  • Page 628

    628 chapter 28: charting and graphing data action="write" charset="iso-8859-1" file="c:\inetpub\wwwroot\charts\vehicle.Jpg" output="#mychart#"> height=240 width=320> 2 save the page as charttofile.Cfm in myapps under the web root directory. 3 return to your browser and enter the following url to vie...

  • Page 629

    Controlling chart appearance 629 controlling chart appearance use the cfchart and cfchartseries tags to customize the appearance of your charts. Common chart characteristics you can optionally specify the following characteristics to cfchart on all types of charts: chart characteristic attributes us...

  • Page 630

    630 chapter 28: charting and graphing data you can also use the cfchartseries tag to specify attributes of chart appearance. The following table describes these attributes: multiple series showlegend seriesplacement showlegend specifies to display the chart’s legend when the chart contains more than...

  • Page 631

    Controlling chart appearance 631 setting x-axis and y-axis characteristics you can specify the following additional characteristics to control the look of the x-axis and y-axis of charts, except for pie charts: creating a bar chart the example in the following procedure adds a title to the bar chart...

  • Page 632

    632 chapter 28: charting and graphing data valuecolumn="avgbydept" itemcolumn="dept_name" /> 3 save the file. 4 return to your browser and enter the following url to view chartdata.Cfm: http://127.0.0.1/myapps/chartdata.Cfm reviewing the code the following table describes the highlighted code and it...

  • Page 633

    Controlling chart appearance 633 group by dept_name 1000)*1000> 1000)*1000> 3 add the following cfchart tag: tipstyle="mousedown" font="times" fontsize=14 fontbold="yes" backgroundcolor = "##ccffff" show3d="yes" > type="pie" query="deptsalaries" valuecolumn="sumbydept" itemcolumn="dept_name" colorli...

  • Page 634

    634 chapter 28: charting and graphing data reviewing the code the following table describes the highlighted code and its function: creating an area chart the example in the following procedure adds an area chart showing the average salary by start date to the salaries analysis page. It shows the use...

  • Page 635

    Controlling chart appearance 635 select startdate, avg(salary) as avgbystart from getsalaries group by startdate 1000)*1000> 4 add the following cfchart tag before the end of the body tag block: chartwidth=400 backgroundcolor="##ffff00" show3d="yes" > type="area" query="hiresalaries" valuecolumn="av...

  • Page 636

    636 chapter 28: charting and graphing data setting curve chart characteristics curves use the attributes already discussed. However, you should be aware that curve charts require a large amount of processing to render. For fastest performance, create them offline, write them to a file or variable, t...

  • Page 637

    Linking charts to urls 637 for example, to let users click on the graph to open the page moreinfo.Cfm, and pass all three values to the page, you code the url attribute as follows: url="moreinfo.Cfm?Series=$serieslabel$&item=$itemlabel$&value=$value$" the variables are not enclosed in # signs like o...

  • Page 638

    638 chapter 28: charting and graphing data 2 save the page as salary_details.Cfm in myapps under the web root directory. Reviewing the code the following table describes the code and its function: code description datasource="companyinfo"> select departmt.Dept_name, employee.Firstname, employee.Last...

  • Page 639

    Linking charts to urls 639 part 2: making the chart dynamic 1 open chartdata.Cfm in your editor. 2 edit the cfchart tag for the pie chart so it appears as follows: font="times" fontbold="yes" backgroundcolor="##ccffff" show3d="yes" url="salary_details.Cfm?Item=$itemlabel$" > type="pie" query="deptsa...

  • Page 640

    640 chapter 28: charting and graphing data xaxistitle="department" yaxistitle="salary average" tipstyle=none url="javascript:chart_onclick('$serieslabel$','$itemlabel$','$value$');" > xaxistitle="department" yaxistitle="salary average" tipstyle=none url="javascript:chart_onclick('$serieslabel$','$it...

  • Page 641: Chapter 29

    641 chapter 29 using the flash remoting service using the macromedia flash remoting service of macromedia coldfusion mx, coldfusion developers can work together with macromedia flash mx designers to build dynamic flash user interfaces for coldfusion applications. Contents about using the flash remot...

  • Page 642

    642 chapter 29: using the flash remoting service about using the flash remoting service with coldfusion using the flash remoting service of coldfusion mx, coldfusion developers can work together with macromedia flash mx designers to build flash user interfaces (uis) for coldfusion applications. Buil...

  • Page 643

    Using the flash remoting service with coldfusion pages 643 using the flash remoting service with coldfusion pages when building a coldfusion page that interacts with flash movies, the directory name that contains the coldfusion pages translates to the flash service name in actionscript. The individu...

  • Page 644

    644 chapter 29: using the flash remoting service accessing parameters passed from flash to access variables passed from flash movies, you append the parameter name to the flash scope or use the flash.Params array. Depending on how the values were passed from flash, you refer to array values using or...

  • Page 645

    Using the flash remoting service with coldfusion pages 645 in this example, the query results are filtered by the value of flash.Paramname , which references the first parameter in the array. If the parameters were passed as an ordered array from flash, you use standard structure name syntax; for ex...

  • Page 646

    646 chapter 29: using the flash remoting service to create a coldfusion page that returns a incremental record set to flash: 1 create a coldfusion page, and save it as getdata.Cfm in the helloexamples directory. 2 modify getdata.Cfm so that the code appears as follows: select * from tblparks in this...

  • Page 647

    Using flash with coldfusion components 647 to create a coldfusion component that interacts with a flash movie: 1 create a coldfusion component, and save it as flashcomponent.Cfc in the helloexamples directory. 2 modify the code in flashcomponent.Cfc so that it appears as follows: in this example, th...

  • Page 648

    648 chapter 29: using the flash remoting service in this example, the description attribute of the cffunction tag supplies a short text description of the component method. 2 save the file. 3 open the flash mx authoring environment, and open the service browser. 4 if not already present, add your fl...

  • Page 649

    Using the flash remoting service with coldfusion java objects 649 for example, the following server-side actionscript function definition returns a recordset object: function basicquery() { mydata = cf.Query({datasource:"customers", sql:"select * from mytable"}); return mydata; } note: for more info...

  • Page 650

    650 chapter 29: using the flash remoting service handling errors with coldfusion and flash to help with debugging, use the cftry and cfcatch tags to return error messages to the flash player, as in the following example: in this example, the first cfset tag fails to assign the value into flash.Resul...

  • Page 651: Chapter 30

    651 chapter 30 using server-side actionscript macromedia coldfusion mx server configuration includes the macromedia flash remoting service, a module that lets macromedia flash mx developers create server-side actionscript. These actionscript files can directly access macromedia coldfusion mx query a...

  • Page 652

    652 chapter 30: using server-side actionscript about server-side actionscript macromedia coldfusion mx includes a module called the macromedia flash remoting service that acts as a broker for interactions between macromedia flash mx and coldfusion mx. Flash remoting supports a range of object types,...

  • Page 653

    About server-side actionscript 653 server-side requirements creating actionscript that executes on the server helps leverage your knowledge of actionscript. It also provides direct access to coldfusion mx query and http features. The cf.Query and cf.Http actionscript functions let you perform coldfu...

  • Page 654

    654 chapter 30: using server-side actionscript you could, for example, create a server-side actionscript file that defines a whole library of sql query methods. With these query methods defined on the server side, your flash designers only have to invoke the specific query function they want to retu...

  • Page 655

    Using server-side actionscript functions 655 2 since the flash remoting service serves as a broker for calls to server-side actionscript functions, you must identify the flash remoting service url as an argument in the netservices.Setdefaultgatewayurl function. For example: netservices.Setdefaultgat...

  • Page 656

    656 chapter 30: using server-side actionscript using results returned by the cf.Query function you use functions in the recordset actionscript object to access the data returned in a cf.Query record set; for example, how many records are in the record set and the names of the columns. You can also u...

  • Page 657

    About the cf.Query function and data sources 657 about the cf.Query function and data sources you use the cf.Query function to populate macromedia flash mx movie elements with data retrieved from a macromedia coldfusion mx data source. To use the cf.Query function you do the following: to pull data ...

  • Page 658

    658 chapter 30: using server-side actionscript you use server-side actionscript in coldfusion mx to return record set data to a flash mx client from a coldfusion mx data source. You specify the coldfusion mx data source name and the sql statement you execute on the data source as arguments in the cf...

  • Page 659

    Using the cf.Query function 659 using cf.Query positional argument syntax positional arguments support a subset of cf.Query arguments, and you can create more efficient code. The following is the syntax for the positional argument style: // cf.Query positional argument syntax cf.Query(datasource, sq...

  • Page 660

    660 chapter 30: using server-side actionscript these functions are available for every recordset object returned by the cf.Query function to the flash mx client. You invoke these functions as follows: objectname.Functionname(); for example, in the result function that you create to handle record set...

  • Page 661

    Building a simple application 661 writing the server-side actionscript function the example in this section creates a search function that performs a simple search operation against a coldfusion mx data source. This function accepts two arguments, firstname and lastname, and returns any records foun...

  • Page 662

    662 chapter 30: using server-side actionscript submitting user data to the flash remoting service to send data to server-side actionscript, you must create a function that passes the data from the flash movie to server-side actionscript. The search function, applied at the frame level, collects the ...

  • Page 663

    About the cf.Http function 663 reviewing the code the following table describes the code and its function: checking for a flash remoting service connection to ensure that the flash movie is connected to the flash remoting service, you use an if statement; for example: if (inited == null) { inited = ...

  • Page 664

    664 chapter 30: using server-side actionscript the client-side example could look like the following: #include "netservices.As" netservices.Setdefaultgatewayurl("http://mycfserver:8500"); gatewayconnnection = netservices.Creategatewayconnection(); myhttp = gatewayconnnection.Getservice("httpfuncs", ...

  • Page 665

    Using the cf.Http function 665 referencing http post parameters in the cf.Http function to pass http post parameters in the cf.Http function, you must construct an array of objects and assign this array to a variable named params . The following arguments can only be passed as an array of objects in...

  • Page 666

    666 chapter 30: using server-side actionscript for example, when you build an html form using the post method, you specify the name of the page to which form data is passed. You use the post method in the cf.Http function in a similar way. However, with the cf.Http function, the page that receives t...

  • Page 667: Part VI

    Part vi using web elements and external objects this part describes how you can use web elements such as xml, web services, enterprise javabeans (ejbs), jsp pages, and java servlets in coldfusion applications. It also describes how to use external objects, including java, component object model (com...

  • Page 669: Chapter 31

    669 chapter 31 using xml and wddx this chapter describes how to use coldfusion to create, use, and manipulate xml documents. This chapter also presents web distributed data exchange (wddx), an xml dialect for transmitting structured data, and describes how to use it to transfer data between applicat...

  • Page 670

    670 chapter 31: using xml and wddx about xml and coldfusion in the last few years, xml has rapidly become the universal language for representing documents and data on the web. These documents can extend beyond the traditional concept of a paper document or its equivalent. For example, xml is often ...

  • Page 671

    The xml document object 671 the xml document object coldfusion represents an xml document as an object, called an xml document object, that is much like a standard coldfusion structure. In fact, most coldfusion structure functions, such as structinsert , work with xml document objects. For a full li...

  • Page 672

    672 chapter 31: using xml and wddx dom node view the dom node view presents the xml document object using the same format as the document’s xml document object model (dom). In fact, an xml document object is a representation of a dom object. The dom is a world wide web consortium (w3c) recommendatio...

  • Page 673

    The xml document object 673 xml document structures an xml document object is a structure that contains a set of nested xml element structures. The following figure shows a section of the cfdump tag output for the document object for the xml in “a simple xml document” on page 671 . This figure shows...

  • Page 674

    674 chapter 31: using xml and wddx the following code displays this output. It assumes that you save the code in a file under your web root, such as c:\inetpub\wwwroot\testdocs\employeesimple.Xml variable="xmldoc"> the document object structure at the top level, the xml document object has the follo...

  • Page 675

    The xml document object 675 xml dom node structure the following table lists the contents of an xml dom node structure: note: the cfdump tag does not display xmlnode structures. If you try to dump an xmlnode structure, the cfdump tag displays “empty structure”. The following table lists the contents...

  • Page 676

    676 chapter 31: using xml and wddx coldfusion xml tag and functions the following table lists the coldfusion tag ( cfxml ) and functions that create and manipulate xml documents: tag or function description variable="objectname" [casesensitive="boolean"]> creates a new coldfusion xml document object...

  • Page 677

    Using an xml object 677 note: the tags and functions that create xml document objects let you specify whether coldfusion will treat the object in a case-sensitive manner. If you do not specify case-sensitivity, coldfusion ignores the case of xml document object component identifiers, such as element...

  • Page 678

    678 chapter 31: using xml and wddx • use associative array (bracket) notation to specify an element name that contains a period or colon; for example, myotherdoc.Xmlroot["type1.Case1"] . • you can use dom methods in place of structure entry names. For example, the following variables all refer to th...

  • Page 679

    Using an xml object 679 • if the component name does not match an existing element, the element names on the left and right sides of the expression must match. Coldfusion creates a new element with the name of the element on the left of the expression. If the element names do not match, it generates...

  • Page 680

    680 chapter 31: using xml and wddx the value when output using xmltext is: #mydoc.Myroot.Xmlchildren[1].Xmltext# the xml text representation of mydoc is: #tostring(mydoc)# creating and saving an xml document object the following sections show the ways you can create and save an xml document object. ...

  • Page 681

    Modifying a coldfusion xml object 681 { mydoc.Myroot.Xmlchildren[i] = xmlelemnew(mydoc,"childnode"); mydoc.Myroot.Xmlchildren[i].Xmltext = "this is child node " & i &"."; } creating an xml document object from existing xml the xmlparse function converts an xml document or document fragment represent...

  • Page 682

    682 chapter 31: using xml and wddx functions for xml object management the following table lists the coldfusion array and structure functions that you can use to manage xml document objects and their functions, and describes their common uses. In several cases you can use either an array function or...

  • Page 683

    Modifying a coldfusion xml object 683 note: array and structure functions not in the preceding or table or the table in the next section, do not work with xml document objects, xml elements, or xml node structures. Treating elements with the same name as an array in many cases an xml element has mul...

  • Page 684

    684 chapter 31: using xml and wddx adding use the following techniques to add new information to an element: deleting use the following techniques to delete information from an element: type using a function using an assignment statement attribute structinsert (xmlelempath.Xmlattributes, "key", "val...

  • Page 685

    Modifying a coldfusion xml object 685 changing use the following techniques to change the contents of an element: adding, deleting, and modifying xml elements the following sections describe the basic techniques for adding, deleting, and modifying xml elements. The example code uses the xml document...

  • Page 686

    686 chapter 31: using xml and wddx { if (xmlelement.Xmlchildren[i].Xmlname is nodename) nodesfound = nodesfound + 1; } return nodesfound; } the following lines use this function to display the number of nodes named “name” in the mydoc.Employee element: nodes found: #nodecount(mydoc.Employee, "name")...

  • Page 687

    Modifying a coldfusion xml object 687 if you have multiple child elements with the same name, and you want to insert a new element in a specific position, use the xmlchildpos function to determine the location in the xmlchildren array where you want to insert the new element. For example, the follow...

  • Page 688

    688 chapter 31: using xml and wddx when you copy an element, the new element must have the same name as the existing element. If you specify the new element by name on the left side of an assignment, the element name must be the same as the name on the right side. For example, the following expressi...

  • Page 689

    Modifying a coldfusion xml object 689 adding, changing, and deleting element attributes you modify an element’s attributes the same way you change the contents of any structure. For example, each of the following lines adds a status attribute the second mydoc.Employee.Name element: "inactive")> to c...

  • Page 690

    690 chapter 31: using xml and wddx to move an element, you must assign it to its new location, then delete it from its old location. For example, the following lines move the phonenumber element from mydoc.Employee.Name[1] to mydoc.Employee.Name[2]: using xml and coldfusion queries you can convert x...

  • Page 691

    Transforming documents with xslt 691 converting a query object to xml the following example shows how to convert a query object to xml. It uses cfquery to get a list of employees from the companyinfo database and saves the information as an xml document. Select firstname, lastname from employee #fir...

  • Page 692

    692 chapter 31: using xml and wddx extracting data with xpath xpath is a language for addressing parts of an xml document. Like xsl, xpath is a w3c specification. One of the major uses of xpath is in xsl transformations. However, xpath has more general uses. In particular, it can extract data from x...

  • Page 693

    Example: using xml in a coldfusion application 693 the xml document the order.Xml document has the following structure: • the root element is named order and has one attribute, id. • there is one customer element with firstname, lastname, and accountnum attributes. The customer element does not have...

  • Page 694

    694 chapter 31: using xml and wddx the coldfusion page the coldfusion page looks like the following: variable="myxml"> name=#mydoc.Order.Customer.Xmlattributes.Firstname# #mydoc.Order.Customer.Xmlattributes.Lastname# account=#accountnum# number of items ordered= #numitems# #mydoc.Order.Items.Item[i]...

  • Page 695

    Example: using xml in a coldfusion application 695 as totalprice from orderquery full price= #pricequery.Totalprice# discount price= #discountprice# #discountprice# #drate# #name# #qty# #qty*unitprice#.

  • Page 696

    696 chapter 31: using xml and wddx reviewing the code the following table describes the cfml code and its function. For the sake of brevity, it does not include code that displays the processing results. Code description file="c:eo\wwwroot\examples\order.Xml" variable="myxml"> customer.Xmlattribut...

  • Page 697

    Moving complex data across the web with wddx 697 moving complex data across the web with wddx wddx is an xml vocabulary for describing a complex data structure, such as an array, associative array (such as a coldfusion structure), or a recordset, in a generic fashion. It lets you use http to move th...

  • Page 698

    698 chapter 31: using xml and wddx wddx has two features that make it useful for transferring data in a web environment: • it is lightweight. The javascript used to serialize and deserialize data, including a debugging function to dump wddx data, occupies less than 22k. • unlike traditional client-s...

  • Page 699

    Moving complex data across the web with wddx 699 applications that take advantage of wddx can continue to do so if they start to use web services. These applications could also be converted to use web services standards exclusively; only the service and data interchange formats—not the application m...

  • Page 700

    700 chapter 31: using xml and wddx wddx data type support the following sections describe the data types that wddx supports. This information is a distillation of the description in the wddx dtd. For more detailed information, see the dtd at www.Openwddx.Org. Basic data types wddx can represent the ...

  • Page 701

    Moving complex data across the web with wddx 701 data type comparisons the following table compares the basic wddx data types with the data types to which they correspond in the languages and technologies commonly used on the web: time zone processing producers and consumers of wddx packets can be i...

  • Page 702

    702 chapter 31: using xml and wddx using wddx the following sections describe how you can use wddx in coldfusion applications. The first two sections describe the tools that coldfusion provides for creating and converting wddx. The remaining sections show how you use these tools for common applicati...

  • Page 703

    Using wddx 703 converting cfml data to a javascript object the following example demonstrates the transfer of a cfquery recordset from a coldfusion page executing on the server to a javascript object that is processed by the browser. The application consists of four principal sections: • running a d...

  • Page 704

    704 chapter 31: using xml and wddx 6 click serialize to serialize the resulting data. The resulting wddx packet appears in the wddx packet display box. This step is intended only for test purposes. Real applications handle the serialization automatically. 7 click submit to submit the data. The wddx ...

  • Page 705

    Using wddx 705 name="personform"> personal information first name: last name: onclick="serializedata(personinfo, document.Personform.Wddxpacket)"> names added so far: wddx packet display: server-side processing output="personinfo"> the submitted personal information is: person #currentrow#: #firstna...

  • Page 706

    706 chapter 31: using xml and wddx storing complex data in a string the following simple example uses wddx to store complex data, a data structure that contains arrays as a string in a client variable. It uses the cfdump tag to display the contents of the structure before serialization and after des...

  • Page 707: Chapter 32

    707 chapter 32 using web services web services let you publish and consume remote application functionality over the internet. When you consume web services, you access remote functionality to perform an application task. When you publish a web service, you let remote users access your application f...

  • Page 708

    708 chapter 32: using web services web services since its inception, the internet has allowed people to access content stored on remote computers. This content can be static, such as a document represented by an html file, or dynamic, such as content returned from a coldfusion page or cgi script. We...

  • Page 709

    Web services 709 translationmode="en_es" sourcedata="hello world" returnvariable='foo'> #foo# for more information on consuming web services, see “consuming web services” on page 713 . Basic web service concepts you must be familiar with the underlying architecture of a web service provider in order...

  • Page 710

    710 chapter 32: using web services describing web services with wsdl a wsdl document is an xml file that describes a web service’s purpose, where it is located, and how to access it. The wsdl document describes the operations that you can invoke and their associated data types. Coldfusion mx can gen...

  • Page 711

    Working with wsdl files 711 viewing a wsdl file using dreamweaver mx dreamweaver mx contains a utility to view web services, including operation names, parameter names, and parameter data types. The following figure shows a wsdl file for the babelfish web service: this figure shows that the web serv...

  • Page 712

    712 chapter 32: using web services porttype name="babelfishporttype"> operation name="babelfish"> /operation> /porttype> binding name="babelfishbinding" type="tns:babelfishporttype"> http" /> operation name="babelfish"> input> encodingstyle="http://schemas.Xmlsoap.Org/soap/encoding/" /> /input> outp...

  • Page 713

    Consuming web services 713 consuming web services coldfusion mx provides two methods for consuming web services. The method that you choose depends on your coldfusion programming style and application. The following table describes these methods: one important consideration is that all consumption m...

  • Page 714

    714 chapter 32: using web services the operation name used in the examples in this section is babelfish. This operation takes a single input parameter defined as a message of type babelfishrequest. You can see that the message babelfishrequest contains two string parameters: translationmode and sour...

  • Page 715

    Consuming web services 715 where: • webservice specifies the url to the wsdl file for the web service. • method specifies the operation of the web service to invoke. • inputparamn specifies an input parameter passed to the operation. • returnvariable specifies the name of the variable that contains ...

  • Page 716

    716 chapter 32: using web services webservice = "http://www.Xmethods.Net/sd/2001/babelfishservice.Wsdl" method = "babelfish" argumentcollection = "#stargs#" returnvariable = "varname" > #varname# in this example, you create the structure in a cfscript block, but you can use any coldfusion method to ...

  • Page 717

    Consuming web services 717 consuming web services that are not generated by coldfusion mx to consume a web service that is implemented in a technology other than coldfusion mx, the web service must have one of the following sets of options: • rpc as the soap binding style and encoding as the encodin...

  • Page 718

    718 chapter 32: using web services handling inout and out parameters some web services define inout and out parameters. You use out parameters to pass a placeholder for a return value to a web service. The web service then returns its result by writing it to the out parameter. Inout parameters let y...

  • Page 719

    Consuming web services 719 data conversions between coldfusion and wsdl data types a wsdl file defines the input and return parameters of an operation, including data types. For example, the babelfish web service contains the following definition of input and return parameters: message name="babelfi...

  • Page 720

    720 chapter 32: using web services the following example shows a coldfusion component that takes a query as input and echoes the query back to the caller: if you add this web service in dreamweaver mx, you see a description of it in the components tab of the application panel. Note: this figure assu...

  • Page 721

    Publishing web services 721 publishing web services to publish web services for consumption by remote applications, you create the web service using coldfusion components. For more information on components, see chapter 11, “building and using coldfusion components,” on page 219 . Creating component...

  • Page 722

    722 chapter 32: using web services as part of publishing the component for access as a web service, coldfusion generates the wsdl file that defines the component where the wsdl file includes definitions for how coldfusion data types map to wsdl data types. The following table shows this mapping: in ...

  • Page 723

    Publishing web services 723 if you register the component in dreamweaver mx, it appears in the components tab of the application panel. Requesting the wsdl file returns the following: xmlns:wsdl="http://schemas.Xmlsoap.Org/wsdl/" xmlns:xsd="http://www.W3.Org/2001/xmlschema" xmlns:wsdlsoap="http://sc...

  • Page 724

    724 chapter 32: using web services 2 save this file as echo.Cfc in your web root directory. 3 create a coldfusion page with the following content: method ="echostring" input = "hello" returnvariable="foo"> #foo# 4 save this file as echoclient.Cfm in your web root directory. 5 request echoclient.Cfm ...

  • Page 725

    Publishing web services 725 note: if the component files are not in a directory under your web root, you must create a coldfusion mapping to the directory containing them. If you register the component in dreamweaver mx, it appears in the components tab of the application panel, as the following fig...

  • Page 726

    726 chapter 32: using web services securing your web services you can restrict access to your published web services to control the users allowed to invoke them. You can use your web server to control access to the directories containing your web services, or you can use coldfusion security in the s...

  • Page 727

    Publishing web services 727 using coldfusion to control access instead of letting the web server control access to your web services, you can handle the username/password string in your application.Cfm file as part of your own security mechanism. In this case, you use the cflogin tag to retrieve the...

  • Page 728

    728 chapter 32: using web services using programmatic security you can implement your own security within the a function to protect resources. For example you can use the coldfusion function isuserinrole to determine if a user is in particular role, as the following example shows: … do stuff allowed...

  • Page 729

    Handling complex data types 729 this table shows that complex data types map to coldfusion structures. Coldfusion structures offer a flexible way to represent data. You can create structures that contain single-dimension arrays, multi-dimensional arrays, and other structures. The coldfusion mapping ...

  • Page 730

    730 chapter 32: using web services to call the updateemployeeinfo operation, you create a coldfusion structure, initialize six fields of the structure that correspond to the six elements of employee, then call the operation, as the following code shows: stuser = structnew(); stuser.Active = true; st...

  • Page 731

    Handling complex data types 731 name of employee is: #myreturnvar.Fname# #myreturnvar.Lname# active status: #myreturnvar.Active# age: #myreturnvar.Age# hire date: #myreturnvar.Hiredate# favorite number: #myreturnvar.Number# you access elements of the variable myreturnvar using the dot notation in th...

  • Page 732

    732 chapter 32: using web services publishing structures a coldfusion structure can hold an unlimited number of key-value pairs where the values can be of any coldfusion data type. While it is a very useful and powerful way to represent data, it cannot be directly mapped to any xml data types define...

  • Page 733

    Handling complex data types 733 the following table describes the elements of querybean: the wsdl file for a querybean defines these elements as follows: > element name description columnlist string array that contains column names data 2-dimensional array that contains query data > element name des...

  • Page 734

    734 chapter 32: using web services.

  • Page 735: Chapter 33

    735 chapter 33 integrating j2ee and java elements in cfml applications this chapter describes how to integrate j2ee elements, including the following, into your coldfusion application: • jsp pages and servlets • jsp tags • java objects, including enterprise javabeans (ejbs) it does not explain j2ee ...

  • Page 736

    736 chapter 33: integrating j2ee and java elements in cfml applications about coldfusion, java, and j2ee coldfusion mx is built on a j2ee-compliant java technology platform. This lets coldfusion applications take advantage of, and integrate with, j2ee elements. Coldfusion pages can do any of the fol...

  • Page 737

    About coldfusion, java, and j2ee 737 • jsp comments instead, you use cfml comments. (coldfusion ignores jsp comments and passes them to the browser.) • standard jsp tags such as jsp:plugin, unless your j2ee server provides access to these tags in a jar file. Instead, you use coldfusion tags and the ...

  • Page 738

    738 chapter 33: integrating j2ee and java elements in cfml applications to disable automatic class loading of your classes, put the classes in the jvm classpath. Classes located on the jvm classpath are loaded once per server lifetime. To reload these classes, stop and restart coldfusion mx. Note: b...

  • Page 739

    Using jsp tags and tag libraries 739 using jsp tags and tag libraries you can use jsp tags from any jsp tag library. For example, you can use any of the custom tags in the open-source apache jakarta project taglibs project tag libraries, located at http:// jakarta.Apache.Org/taglibs/index.Html. This...

  • Page 740

    740 chapter 33: integrating j2ee and java elements in cfml applications example: using the random tag library the following example uses the random tag library from the apache jakarta taglibs project and calls the library’s number tag, which initializes a random number generator that uses a secure a...

  • Page 741

    Interoperating with jsp pages and servlets 741 for example, you might want to integrate an existing jsp customer response component into a new coldfusion order processing application. The order processing application provides the order number, total cost, and expected shipping date, and the customer...

  • Page 742

    742 chapter 33: integrating j2ee and java elements in cfml applications accessing coldfusion application and session variables in jsp pages coldfusion mx runs as a j2ee application on the j2ee application server. The j2ee application servletcontext is a data structure that stores objects as attribut...

  • Page 743

    Interoperating with jsp pages and servlets 743 reviewing the code the following table describes the cfml code and its function: the hello.Jsp page is called by the coldfusion page. It displays the name parameter in a header and the three variables in the remainder of the body. Request.Myvariable: se...

  • Page 744

    744 chapter 33: integrating j2ee and java elements in cfml applications calling a coldfusion page from a jsp page the following jsp page sets request, session, and application variables and calls a coldfusion page, passing it a name parameter: reviewing the code the following table describes the jsp...

  • Page 745

    Interoperating with jsp pages and servlets 745 the following hello.Cfm page is called by the jsp page. It displays the name parameter in a heading and the three variables in the remainder of the body. Request.Myvariable: #request.Myvariable# session.Myvariable: #session.Myvariable# application.Myvar...

  • Page 746

    746 chapter 33: integrating j2ee and java elements in cfml applications using java objects you use the cfobject tag to create an instance of a java object. You use other coldfusion tags, such as cfset and cfoutput , or cfscript to invoke properties (attributes), and methods (operations) on the objec...

  • Page 747

    Using java objects 747 using properties use the following coding syntax to access properties if the object does either of the following actions: • exposes the properties as public properties. • does not make the properties public, but is a javabean that provides public getter and setter methods of t...

  • Page 748

    748 chapter 33: integrating j2ee and java elements in cfml applications note: you can use the direct reference method to get or set values in some classes that have getproperty and setproperty methods but do not conform fully to the javabean pattern. However, you cannot use this technique for all cl...

  • Page 749

    Using java objects 749 public employee(string first, string last, float salary, int grade) { firstname = first; lastname = last; salary = salary; jobgrade = grade; } public void setsalary(float dollars) { salary = dollars; } public float getsalary() { return salary; } public void setjobgrade(int gra...

  • Page 750

    750 chapter 33: integrating j2ee and java elements in cfml applications reviewing the code the following table describes the cfml code and its function: java considerations keep the following points in mind when you write a coldfusion page that uses a java class object: • the java class name is case...

  • Page 751

    Using java objects 751 in this example, the constructor takes four arguments: the first two are strings, the third is a float, and the fourth is an integer. Java and coldfusion data type conversions coldfusion does not use explicit types for variables, while java is strongly typed. However, coldfusi...

  • Page 752

    752 chapter 33: integrating j2ee and java elements in cfml applications the following table lists how coldfusion converts data returned by java methods to coldfusion data types: resolving ambiguous data types with the javacast function you can overload java methods so a class can have several identi...

  • Page 753

    Using java objects 753 the coldfusion javacast function helps you resolve such issues by specifying the java type of a variable, as in the following line: the javacast function takes two parameters: a string representing the java data type, and the variable whose type you are setting. You can specif...

  • Page 754

    754 chapter 33: integrating j2ee and java elements in cfml applications example: cfml java exception handling code the following cfml code calls the testexception class doexception method. The cfcatch block handles the resulting exception. The exception message is: #cfcatch.Message# examples: using ...

  • Page 755

    Using java objects 755 ■ name of the ejb, as registered with the naming service 3 install the ejb home and component interface compiled classes on your coldfusion web server, either as class files in the web_root/web-inf/classes directory or packaged in a jar file the web_root/web-inf/lib directory....

  • Page 756

    756 chapter 33: integrating j2ee and java elements in cfml applications action=create name=prop type="java" class="java.Util.Properties"> "jrun.Naming.Jruncontextfactory")> action=create name=initcontext type="java" class="javax.Naming.Initialcontext"> #mymessage# action=create name=prop type="java"...

  • Page 757

    Using java objects 757 the example class the following java code defines the example class. The java class example has one public integer member, mpublicint . Its constructor initializes mpublicint to 0 or an integer argument. The class has the following public methods: public class example { public...

  • Page 758

    758 chapter 33: integrating j2ee and java elements in cfml applications static public int sumarray(int[] arr) { int sum=0; for (int i=0; i sum += arr[i]; } return sum; } static public example sumobjarray(example[] arr) { example sum= new example(); for (int i=0; i sum.Mpublicint += arr[i].Mpublicint...

  • Page 759

    Using java objects 759 after reverse element 1: #ra[1]# after reverse element 2: #ra[2]# after reverse element 3: #ra[3]# stringval: #stringval# intval: #intval# floatval: #floatval# intval1 :#intval# array1: #reversedarray[1]# array2: #reversedarray[2]# intval1: #intval#.

  • Page 760

    760 chapter 33: integrating j2ee and java elements in cfml applications.

  • Page 761: Chapter 34

    761 chapter 34 integrating com and corba objects in cfml applications this chapter describes how to use the cfobject tag to invoke com (component object model) or dcom (distributed component object model) and corba (common object request broker) objects. Contents about com and corba. . . . . . . . ....

  • Page 762

    762 chapter 34: integrating com and corba objects in cfml applications about com and corba this section provides some basic information on com and corba objects supported in coldfusion mx and provides resources for further inquiry. About objects com and corba are two of the object technologies suppo...

  • Page 763

    Creating and using objects 763 each corba object has an interface that is defined in the corba interface definition language (idl). The corba idl describes the operations that can be performed on the object, and the parameters of those operations. Clients do not have to know anything about how the i...

  • Page 764

    764 chapter 34: integrating com and corba objects in cfml applications calling methods object methods usually take zero or more arguments. You send in arguments, whose values are not returned to the caller by value. You send out and in,out arguments, whose values are returned to the caller, by refer...

  • Page 765

    Getting started with com and dcom 765 com requirements to use com components in your coldfusion application, you need at least the following items: • the com objects (typically dll or exe files) that you want to use in your coldfusion application pages. These components should allow late binding; th...

  • Page 766

    766 chapter 34: integrating com and corba objects in cfml applications using the ole/com object viewer the ole/com object viewer installation installs the executable, by default, as \mstools\bin\oleview.Exe. You use the object viewer to retrieve a com object’s progid, as well as its methods and prop...

  • Page 767

    Creating and using com objects 767 3 right-click the object to view it, including the typeinfo. If you view the typeinfo, you see the object's methods and properties, as shown in the following figure. Some objects do not have access to the typeinfo area, which is determined when an object is built a...

  • Page 768

    768 chapter 34: integrating com and corba objects in cfml applications the cdo for nts newmail component includes a number of methods and properties to perform a wide range of mail-handling tasks. (in the ole/com object viewer, methods and properties might be grouped together, so you could find it d...

  • Page 769

    Creating and using com objects 769 note: use the cftry and cfcatch tags to handle exceptions thrown by com objects. For more information on exception handling, see chapter 14, “handling runtime exceptions with coldfusion tags,” on page 299 . Releasing com objects by default, com object resources are...

  • Page 770

    770 chapter 34: integrating com and corba objects in cfml applications ensuring correct threading improper threading can cause serious problems when using a com object in coldfusion. Make sure that the object is thread-safe. An object is thread-safe if it can be called from many programming threads ...

  • Page 771

    Creating and using com objects 771 understanding common com-related error messages the following table described some error messages you might encounter when using com objects: accessing complex com objects using java proxies coldfusion mx supports java proxies to access com objects. If you do not c...

  • Page 772

    772 chapter 34: integrating com and corba objects in cfml applications to create java stub files for com objects: 1 configure your system as follows: a ensure that a jdk (java development kit) is correctly installed, including proper configuration of the classpath and the command prompt path variabl...

  • Page 773

    Creating and using com objects 773 5 ensure that the coldfusion server is not running. To stop the coldfusion server, open the services control panel, select coldfusion mx application server, and click stop. (in windows 98 or windows me, select stop coldfusion mx from the coldfusion mx programs item...

  • Page 774

    774 chapter 34: integrating com and corba objects in cfml applications using the application scope to improve com performance the java call to create a new com object instance can take substantial time. As a result, creating com objects in coldfusion mx can be substantially slower than in coldfusion...

  • Page 775

    Creating and using com objects 775 class="scripting.Filesystemobject" name="application.Fso" server="\\localhost"> getting fixed drive available space class="scripting.Filesystemobject" name="application.Fso" server="\\localhost"> execution time: #int(gettickcount()-start)# milliseconds cfoutput> ex...

  • Page 776

    776 chapter 34: integrating com and corba objects in cfml applications action="connect" class="word.Application" name="application.Mywordobj" context="local"> action="create" class="word.Application" name="application.Mywordobj" context="local"> conversion of temp.Htm complete execution time: #int(g...

  • Page 777

    Creating and using corba objects 777 getting started with corba the coldfusion cfobject tag and createobject function support corba through the dynamic invocation interface (dii). As with com, the object's type information must be available to coldfusion. Therefore, an iiop-compliant interface repos...

  • Page 778

    778 chapter 34: integrating com and corba objects in cfml applications for example, use the following cfml to invoke a corba object specified by the tester.Ior file if you configured your orb name as visibroker: class = "d:\temp\tester.Ior" name = "handle" locale = "visibroker"> when you use the cre...

  • Page 779

    Creating and using corba objects 779 the following sections describe how to call corba methods correctly in coldfusion. Method name case considerations method names in idl are case-sensitive. However, coldfusion is case-insensitive. Therefore, do no use methods that differ only in case in idl. For e...

  • Page 780

    780 chapter 34: integrating com and corba objects in cfml applications using methods with return values use corba methods that return values as you would any coldfusion function; for example: using idl types with coldfusion variables the following sections describe how coldfusion supports corba data...

  • Page 781

    Creating and using corba objects 781 data type conversion the following table lists idl data types and the corresponding coldfusion data types: double yes yes yes unsigned short yes yes yes unsigned long yes yes yes longlong no no no unsigned longlong no no no void yes na yes idl type coldfusion typ...

  • Page 782

    782 chapter 34: integrating com and corba objects in cfml applications boolean data considerations coldfusion treats any of the following as boolean values: you can use any of these values with corba methods that take boolean parameters, as the following code shows: struct data type considerations f...

  • Page 783

    Creating and using corba objects 783 in this example, the corba object gets called with the second ( not first) entry in the enumerator, a. Double-byte character considerations if you are using an orb that supports corba later than version 2.0, you do not have to do anything to support double-byte c...

  • Page 784

    784 chapter 34: integrating com and corba objects in cfml applications corba example the following code shows an example of using a loananalyzer corba object. This simplified object determines whether an applicant is approved for a loan based on the information that is supplied. The loananalyzer cor...

  • Page 785

    Corba example 785 4 displays the value of the ret variable, yes or no. Idl struct person { long pid; string name; string middle; string last_name; } struct account { person person; short age; double income; } double loanamountl enum cardtype {amex, visa, mc, discover, diners}; typedef sequence credi...

  • Page 786

    786 chapter 34: integrating com and corba objects in cfml applications.

  • Page 787: Part Vii

    Part vii using external resources this part describes how you can use coldfusion to access and use the following external services: mail servers, remote http and ftp servers, and files and directories. The following chapters are included: chapter 35: sending and receiving e-mail . . . . . . . . . . ...

  • Page 789: Chapter 35

    789 chapter 35 sending and receiving e-mail you can add interactive e-mail features to your coldfusion applications using the cfmail and cfpop tags. This complete two-way interface to mail servers makes the coldfusion e-mail capability a vital link to your users. Contents using coldfusion with mail ...

  • Page 790

    790 chapter 35: sending and receiving e-mail using coldfusion with mail servers adding e-mail to your coldfusion applications lets you respond automatically to user requests. You can use e-mail in your coldfusion applications in many different ways, including the following: • trigger e-mail messages...

  • Page 791

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

  • Page 792

    792 chapter 35: sending and receiving e-mail sample uses of cfmail an application page containing the cfmail tag dynamically generates e-mail messages based on the tag’s settings. Some of the tasks that you can accomplish with cfmail include the following: • sending a mail message in which the data ...

  • Page 793

    Sample uses of cfmail 793 reviewing the code the following table describes the code: sending e-mail to multiple recipients in addition to simply using a comma-delimited list in the to attribute of the cfmail tag, you can send e-mail to multiple recipients by using the query attribute of the cfmail t...

  • Page 794

    794 chapter 35: sending and receiving e-mail customizing e-mail for multiple recipients in the following example, a query (getcustomers) retrieves the contact information for a list of customers. The query then sends an e-mail to each customer to verify that the contact information is still valid: s...

  • Page 795

    Using cfmailparam 795 reviewing the code the following table describes the code and its function: using cfmailparam you use the cfmailparam tag to attach files or add a custom header to an e-mail message. You nest the cfmailparam tag within the cfmail tag. Attaching files to a message you use one cf...

  • Page 796

    796 chapter 35: sending and receiving e-mail adding a custom header to a message when the recipient of an e-mail message replies to the message, the reply is sent to the address specified in the from field of the original message. You can use cfmailparam to override the value in the from field and p...

  • Page 797

    Receiving e-mail messages 797 error logging and undelivered messages coldfusion logs all errors that occur during smtp message processing to the file mail.Log in the coldfusion log directory. The log entries contain the date and time of the error as well as diagnostic information about why the error...

  • Page 798

    798 chapter 35: sending and receiving e-mail 4 decide whether you must delete messages from the pop server after you retrieve them. 5 incorporate the cfpop tag in your application and create a user interface for accessing a mailbox. 6 build an application page to handle the output. Retrieved message...

  • Page 799

    Handling pop mail 799 to retrieve only the message header: 1 create a coldfusion page with the following content: username=#myusername# password=#mypassword# action="getheaderonly" name="sample"> messagenumber: #htmleditformat(sample.Messagenumber)# to: #htmleditformat(sample.To)# from: #htmleditfor...

  • Page 800

    800 chapter 35: sending and receiving e-mail 3 save the file as header_only.Cfm in the myapps directory under your web_root and view it in your web browser: this code retrieves the message headers and stores them in a cfpop record set called sample. For more information about working with record set...

  • Page 801

    Handling pop mail 801 retrieving a message when you use the cfpop tag with action="getall" , coldfusion returns the same columns as with getheaderonly , plus two additional columns, body and header . To retrieve an entire message: 1 create a coldfusion page with the following content: username=#myus...

  • Page 802

    802 chapter 35: sending and receiving e-mail 3 save the file as header_body.Cfm in the myapps directory under your web_root and view it in your web browser: this example does not use a cfml function to encode the body contents. As a result, the browser displays the formatted message as you would nor...

  • Page 803

    Handling pop mail 803 to retrieve all parts of a message, including attachments: 1 create a coldfusion page with the following content: body, and all attachments: username=#myusername# password=#mypassword# action="getall" attachmentpath="c:\temp\attachments" name="sample"> messagenumber: #htmleditf...

  • Page 804

    804 chapter 35: sending and receiving e-mail 3 save the file as header_body_att.Cfm in the myapps directory under your web_root and view it in your web browser: note: to avoid duplicate filenames when saving attachments, set the generateuniquefilenames attribute of cfpop to yes. Deleting messages by...

  • Page 805

    Handling pop mail 805 messagenumber="1,2,3"> 2 edit the following lines so that they refer to valid values for your pop mail server, username, and password: username=#username# password=#password# 3 save the file as message_delete.Cfm in the myapps directory under your web_root and view the file in ...

  • Page 806

    806 chapter 35: sending and receiving e-mail.

  • Page 807: Chapter 36

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

  • Page 808

    808 chapter 36: interacting with remote servers about interacting with remote servers transfer protocols are mechanisms for moving files and information from a source to one or more destinations. Two of the more popular protocols are the hypertext transfer protocol (http) and the file transfer proto...

  • Page 809

    Using cfhttp to interact with the web 809 2 (optional) replace the value of the url attribute with another url. 3 save the file as get_webpage.Cfm in the myapps directory under your web_root and view it in the web browser. The browser loads the web page specified in the url attribute. Reviewing the ...

  • Page 810

    810 chapter 36: interacting with remote servers reviewing the code the following table describes the code and its function: to get a binary file and save it: 1 create a coldfusion page with the following content: method="get" url="http://www.Macromedia.Com/macromedia/accessibility/images/ spotlight....

  • Page 811

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

  • Page 812

    812 chapter 36: interacting with remote servers columns="id,number,odate,sdate,name,address" textqualifier=""> order id: #id# order number: #number# order date: #sdate# 4 save the file as query_textfile.Cfm in the myapps directory under your web_root and view it in the web browser. Using the cfhttp ...

  • Page 813

    Using the cfhttp post method 813 2 replace the path to the gif file to a path on your server (just before the closing cfhttp tag). 3 save the file as post_test.Cfm in the myapps directory under your web_root. Note: you must write a page to view the variables. This is the next procedure. Reviewing th...

  • Page 814

    814 chapter 36: interacting with remote servers 2 replace c:\temp\ with an appropriate directory path on your hard drive. 3 save the file as post_test_server.Cfm in the myapps directory under your web_root. 4 view post_test.Cfm in your browser and look for the file in c:\temp\ (or your replacement p...

  • Page 815

    Performing file operations with cfftp 815 performing file operations with cfftp the cfftp tag lets you perform tasks on remote servers using file transfer protocol (ftp). You can use cfftp to cache connections for batch file transfers when uploading or downloading files. Note: to use cfftp, the enab...

  • Page 816

    816 chapter 36: interacting with remote servers text="#dateformat(lastmodified)#"> text="#isdirectory#"> 2 change myserver to the name of a server for which you have ftp permission. 3 change myusername and mypassword to a valid username and password. To establish an anonymous connection, enter “anon...

  • Page 817

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

  • Page 818

    818 chapter 36: interacting with remote servers connection actions and attributes the following table shows the available cfftp actions and the attributes they require when you use a named (that is, cached) connection. If you do not specify an existing connection name, you must specify the username ...

  • Page 819: Chapter 37

    819 chapter 37 managing files on the server the cffile , cfdirectory , and cfcontent tags handle browser and server file management tasks, such as uploading files from a client to the web server, viewing directory information, and changing the content type that is sent to the web browser. To perform...

  • Page 820

    820 chapter 37: managing files on the server about file management coldfusion lets you access and manage the files and directories on your coldfusion server. The cffile tag has several attributes for moving, copying, deleting, and renaming files. You use the cfdirectory tag to list, create, delete, ...

  • Page 821

    Using cffile 821 note: the form will not work until you write an action page for it (see the next procedure). Reviewing the code the following table describes the code and its function: the user can enter a file path or browse the system and select a file to send. 1 create a coldfusion page with the...

  • Page 822

    822 chapter 37: managing files on the server reviewing the code the following table describes the code and its function: note: this example performs no error checking and does not incorporate any security measures. Before deploying an application that performs file uploads, be sure to incorporate bo...

  • Page 823

    Using cffile 823 note: modern versions of internet explorer and netscape support mime type associations. Other browsers and older versions might ignore these associations. Coldfusion saves any uploaded file if you omit the accept attribute or specify "*/*". You can restrict the file types, as demons...

  • Page 824

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

  • Page 825

    Using cffile 825 moving, renaming, copying, and deleting server files with cffile , you can create application pages to manage files on your web server. You can use the tag to move files from one directory to another, rename files, copy a file, or delete a file. The examples in the following table s...

  • Page 826

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

  • Page 827

    Using cffile 827 enter your name: enter the name of the file: size="25">.Txt enter your message: 2 save the file as writetextfileform.Cfm in the myapps directory under your web_root . Note: the form will not work until you write an action page for it (see the next procedure). To write a text file: 1...

  • Page 828

    828 chapter 37: managing files on the server 4 view the file in the browser, enter values, and submit the form. The appended information displays at the end of the text file. Using cfdirectory use the cfdirectory tag to return file information from a specified directory and to create, delete, and re...

  • Page 829

    Using cfdirectory 829 2 modify the path c:\inetpub\wwwroot\mine so that it points to a directory on your server. 3 save the file as directoryinfo.Cfm in the myapps directory under your web_root and view it in the browser:.

  • Page 830

    830 chapter 37: managing files on the server using cfcontent the cfcontent tag downloads files from the server to the client. You can use this tag to set the mime type of the content returned by a coldfusion page and, optionally, define the filename of a file to be downloaded by the current page. By...

  • Page 831

    Using cfcontent 831 type = "text/html" file = "c:\cfusionmx\wwwroot\myapps\cfcontent_message.Htm" deletefile = "no"> type = "text/html" file = "c:\cfusionmx\wwwroot\myapps\cfcontent_message.Htm" deletefile = "no"> 4 if necessary, edit the file = line to point to your myapps directory. 5 save the fil...

  • Page 832

    832 chapter 37: managing files on the server to create an excel spreadsheet with cfcontent: 1 create a coldfusion page with the following content: select * from employees #employee_id##tabchar##lastname# #tabchar##firstname##tabchar##salary##newline# 2 save the file as employees_to_excel.Cfm in the ...

  • Page 833: Index

    833 index a access security, component 248 accessing client variables 324, 330 generated content 185 action pages 564 actionscript, on coldfusion server 32 active server pages 697 adding data elements to structures 117 elements to an array 108 ancestor tags data access 189 definition 186 and operato...

  • Page 834

    834 index applicationtoken 353 area chart, example 634 arguments optional 199, 202 passing 202 user-defined function 202 using function names 208 arguments. See parameters arguments scope as array 196 as structure 197 in components 243 user-defined functions and 194 variables 45, 74 arithmetic opera...

  • Page 835

    Index 835 requesting component pages with 233 transferring data to a server 703 building components 235 drop-down list boxes 593 queries 430 search interfaces 569 slider bar controls 595 text entry boxes 594 tree controls 586 built-in variables client 324 custom tags 182 server 332 session 328 byte ...

  • Page 836

    836 index using 815 cffunction tag attributes 200 creating user-defined functions 193 security and 352 web services, publishing 721 cfgrid tag browser considerations 585 controlling cell contents 599 editing data in 601 handling failed validation 614 returning user edits 600 using 595 validating wit...

  • Page 837

    Index 837 functions 31, 42 reserved words 51 special characters 50 syntax errors 406 tags 30, 40 variables 44 cfml functions arrayappend 108 arraydeleteat 109 arrayinsertat 108 arraynew 106 arrayprepend 108 arrayset 110 arraysort 118 atructkeyarray 118 createobject 713 createtimespan 284, 328, 455 d...

  • Page 838

    838 index cfscript comments 130 conditional processing 132 creating user-defined functions 193 description 31 differences from javascript 131 example 128, 140 exception handling 139 expressions 129 function statement 198 introduction 46 language 129 looping 134 reserved words 131 return statement 19...

  • Page 839

    Index 839 character encodings about 374 conversion issues 375 defined 373 determining page 378 files 385 forms and 383, 384 processing data from various sources 385, 386 searching and indexing 387 unicode 375 character sets, defined 373 character sets. See also character encodings charting about 621...

  • Page 840

    840 index coldfusion mx about 30 action pages, extension for 564 application services 32 cfml 30 corba type support 780 dynamic evaluation 94 error handling 290 error types 287 features 34 flash connectivity 32 functions 31 integrating e-mail with 790 java objects and 737 scripting environment 30 se...

  • Page 841

    Index 841 introspecting 233 invocation techniques 225 invoking directly 229 invoking from flash 232 invoking methods dynamically 229 invoking methods transiently 226 invoking with forms 231 invoking with urls 230 metadata 233 method parameters 238 naming 242 packages 247 programmatic security 249 re...

  • Page 842

    842 index children 186 data access example 189 data accessibility 187 data exchange 188 descendants 186 downloading 177 encoding 181 encrypting 181 example 179 execution modes 183 filename conflicts 177, 181 instance data 182 location of 175 managing 181 naming 175 nesting 186 parent 186 passing att...

  • Page 843

    Index 843 record delete 448 record sets 418 records 412 retrieving data from 428 rollbacks 414 rows 412 sql 415 stored procedures 281 stored procedures, debugging 397 tables 412 transactions 414 update form 443 updating 421, 438, 442 date-time format 59 date-time values, conversions 70 date-time var...

  • Page 844

    844 index directory structure, application 270, 271 displaying com objects with cfdump 765 query results 431 query results, in tables 567 displaying, component output 239 distinguished name 480 distributed component object model. See dcom distributing cfx tags 263 do while loop, cfscript 136 documen...

  • Page 845

    Index 845 errors categories 287 causes 286 creating application pages 295 custom pages 294 input validation 297 logging 297 recovery 286 web services and 717 euc-kr 374 euro, supporting 383 evaluating cfml functions 95 file upload results 824 strings in functions 210 examples ancestor data access 18...

  • Page 846

    846 index file operations cfftp actions 818 using cffile 820 using cfftp 815 file scope 182 file types, supported for searching 507 files appending 827 character encodings 385 controlling type uploaded 822 copying 825 deleting 825 downloading 830 locking access to 337, 342 moving 825 name conflicts ...

  • Page 847

    Index 847 function-only variables 203 functions built in 42 calling 200 example custom 204 for arrays 113 for components 222 getmetadata 235 introduction 42 javascript, for validation 613 structures 125 syntax 88 user-defined 43 see also coldfusion functions, user-defined functions g generated conte...

  • Page 848

    848 index inserting data description 438 with cfinsert 440 with cfquery 441 instance data, custom tag 182 instance data, of components 236 instance, invoking methods of a component 226 instantiating, components 225 integer variables 56 international languages, search support 509 internationalization...

  • Page 849

    Index 849 javacast cfml function 752 javascript differences from cfscript 131 in charts 639 validating with 613 joins, queries of queries 462 jsp pages accessing 740 calling from coldfusion 744 example 742 sharing data with 741 sharing scopes with 741 jsp tags coldfusion and 736 example 739, 740 in ...

  • Page 850

    850 index read-only 336 scopes and names 336 types 336 log files example 297 using 297 logging errors 297 login applicationtoken 353 flash remoting 354 getting user id and password 353 internet domains 353 logging out users 354 scope of 353 logout, performing 354 looping through structures 121 m mac...

  • Page 851

    Index 851 onrequestend.Cfm 271 opening, sql builder 424 operands 43 operators 43 alternative notation 86 arithmetic 84 boolean 85 comparison 85 concept 544 decision, or comparison 85 evidence 548 explicit queries 539 precedence 87 proximity 549 relational 545 score 550 search 543 sql 416 string oper...

  • Page 852

    852 index proximity operators 549 punctuation, searching 541 python, wddx and 697 q queries about 621 as function parameters 208 as objects 452 as variables 62 building 415, 430 charting 621 converting to xml 691 creating from text files 811 graphing 621 grouping output 587 guidelines for outputting...

  • Page 853

    Index 853 registering cfx tags 263 com objects 765 corba objects 778 java applets 606 regular expressions backreferences 152, 612 basic syntax 145 case sensitivity 147 character classes 151 character sets 145 common uses 159 escape sequences 150 examples 158, 159, 613 for form validation 610 for sea...

  • Page 854

    854 index saving binary files 810 components 241 web pages 809 sbcs 374 schema, ldap directory 498 scopes about 72 application 74, 270, 316, 330 arguments 74 as structures 77 attributes 73 caller 73 cfx tags 77 cgi 73 client 73, 270, 316, 318, 321 cookie 73 debug output 398 evaluating 77 file 182 fl...

  • Page 855

    Index 855 tags 352 types of 346 user security 348 web servers and 350, 726 web services 726, 727 without cookies 352 see also login see also sandbox security security exceptions 289 select sql statement 416, 418 selection lists, multiple 578 sending e-mail 790, 791, 793 form-based e-mail 792 mail as...

  • Page 856

    856 index sorting 419 statement clauses 416 statements 416 sum function 634 syntax 416 text literals in 429 update statement 421, 442 use in cfquery 429 where clause 419, 564 writing 415 standard variables. See built-in variables statement clauses, sql 416 statements cfscript 129 sql 416 status outp...

  • Page 857

    Index 857 time zone processing, wddx 701 time, globalization functions 381 time-out attribute, cflock 337 tostring cfml function 677 tracing 401 cftrace tag 401 considerations for 403 enabling 390 format 402 messages 402 options 401 output 398, 401 transactions 414 transferring data, from browser to...

  • Page 858

    858 index variable scopes about 44 application 45 arguments 45 attributes 44 caller 44 cgi 45 client 45 cookie 45 flash 45 form 44 function local scope 45 request 44 server 45 sessions 45 this 45 thistag 44 url 44 variables 44 variables application 331 application scope 270, 316, 330 array 61 base64...

  • Page 859

    Index 859 purpose of 697 storing data in strings 706 time zone processing 701 transferring data 703 web accessing with cfhttp 697, 808 application framework 318 web application servers request handling 29 tasks 29 web servers and 29 web pages dynamic 428 saving 809 static 428 web server-based authen...

  • Page 860

    860 index wsdl files components 712 creating 710 defined described 710 reading 711 viewing in dreamweaver mx 711 web services, publishing 722 x xml about 676 basic document view 671 coldfusion and 670 converting to query 690 dom node view 672 elements 685 example 692 functions 676 queries and 690 us...