Adobe COLDFUSION 9 Manual Download Page 91

86

DEVELOPING

 

COLDFUSION 9 APPLICATIONS

The CFML Programming Language

Las

t

 upda

te

d 8/5/2010

 

 

 

 

 

<cfset i="CP">  

 

<cfset "#i#"=["Charlie","Parker"]>

Creating complex multidimensional arrays

ColdFusion supports dynamic multidimensional arrays. When you declare an array with the 

ArrayNew

 function, you 

specify the number of dimensions. You can create an asymmetrical array or increase the number of dimensions by 
nesting arrays as array elements.

It is important to know that when you assign one array (array1) to an element of another array (array2), array1 is 
copied into array2. The original copy of array1 still exists, independent of array2. You can then change the contents of 
the two arrays independently.

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.

 

 

 

 

 

<cfset myarray=ArrayNew(1)>  

 

<cfset myotherarray=ArrayNew(2)>  

 

<cfset biggerarray=ArrayNew(3)>  

 

  

 

<cfset biggerarray[1][1][1]=myarray>  

 

<cfset biggerarray[1][1][1][10]=3>  

 

<cfset biggerarray[2][1][1]=myotherarray>  

 

<cfset biggerarray[2][1][1][4][2]="five deep">  

 

  

 

<cfset biggestarray=ArrayNew(3)>  

 

<cfset biggestarray[3][1][1]=biggerarray>  

 

<cfset biggestarray[3][1][1][2][3][1]="This is complex">  

 

<cfset myarray[3]="Can you see me">  

 

  

 

<cfdump var=#biggestarray#><br>   

 

<cfdump var=#myarray#>

Note: 

The 

cfdump

 tag displays the entire contents of an array. It is an excellent tool for debugging arrays and array-

handling code.

Reviewing the code

The following table describes the code:

Code

Description

 

<cfset myarray=ArrayNew(1)>  

 

<cfset myotherarray=ArrayNew(2)>  

 

<cfset biggerarray=ArrayNew(3)>

Create three empty arrays, a 1D array, a 2D array, and a 3D array.

<cfset biggerarray[1][1][1]=myarray>  
 

<cfset biggerarray[1][1][1][10]=3>

Make element [1][1][1] of the 3D 

biggerarray

 array be a copy 

of the 1D array. Assign 3 to the [1][1][1][10] element of the 
resulting array. 

The biggerarray array is now asymmetric. For example, it does 
not have a [1][1][2][1] element.

<cfset biggerarray[2][1][1]=myotherarray>  
 

<cfset biggerarray[2][1][1][4][2]="five deep">

Make element [2][1][1] of the 3D array be the 2D array, and 
assign the [2][1][1][4][2] element the value 

"five deep"

The biggerarray array is now even more asymmetric.

Summary of Contents for COLDFUSION 9

Page 1: ...Developing Applications ADOBE COLDFUSION 9...

Page 2: ...ion of the guide contains a notice that use of the guide is governed by these terms The best way to provide notice is to include the following link To view a copy of this license visit http creativeco...

Page 3: ...Using Regular Expressions in Functions 131 Chapter 5 Building Blocks of ColdFusion Applications Creating ColdFusion Elements 146 Writing and Calling User Defined Functions 153 Building and Using Cold...

Page 4: ...oxy ActionScript Classes for ColdFusion Services 653 Using the LiveCycle Data Services ES Assembler 671 Using Server Side ActionScript 688 Chapter 10 Requesting and Presenting Information Introduction...

Page 5: ...g ColdFusion Web Services 1122 Integrating J2EE and Java Elements in CFML Applications 1125 Using Microsoft NET Assemblies 1149 Integrating COM and CORBA Objects in CFML Applications 1170 Chapter 15 U...

Page 6: ...or cfile action upload FileUpload and cffile action uploadall FileUploadAll The following script functions have been implemented as CFCs dbinfo imap pop ldap feed Caching New function cacheGetSession...

Page 7: ...ession information implicitly to the target page if session management is turned on either in Application cfc or Application cfm Added the following JavaScript Functions ColdFusion Autosuggest getAuto...

Page 8: ...the key verticalalignment AIR integration The following enhancements Support for auto generating primary keys Support for encrypted database introduced in AIR 1 5 Cache file used by ActionScript ORM...

Page 9: ...in the Actions column of the Log Files page ColdFusion Administrator Debugging Logging Support for automatic logging of scheduled tasks Server monitoring Enhancements in this release help you use Serv...

Page 10: ...oading Cleaner and more manageable application code Database vendor independence For more information see ColdFusion ORM Flex and AIR integration Adobe AIR applications Offline capabilities Offline ap...

Page 11: ...l for application independent tasks such as instantiating the applications configuring logging or setting up the scheduler For more details see the section onServerStart in ColdFusion CFML Reference O...

Page 12: ...nd update MS Excel spreadsheets using the cfspreadsheet tag Generate PDFs from MS Word and MS PowerPoint automatically using the cfdocument tag Generate PowerPoint presentations dynamically from HTML...

Page 13: ...rray and datetime types in CFC Other performance enhancements Improved CFC performance Faster Java method invocation Database enhancements DataDirect This release supports DataDirect driver version 4...

Page 14: ...usion server administrators to monitor and manage multiple servers and apply the settings from one ColdFusion server to other ColdFusion servers Server Manager provides improved system management and...

Page 15: ...n see Assembling PDF Documents IMAP support You can query an IMAP server to retrieve and manage mails within multiple folders using the cfimap tag This feature lets you Retrieve messages and store inf...

Page 16: ...Fusion documentation is available online in HTML and Adobe Acrobat Portable Document Format PDF files Go to the ColdFusion Help and Support page at www adobe com go learn_cfu_support_en to view the on...

Page 17: ...ET the Internet has become a multifaceted tool for integrating business activities Now enterprises can use the Internet to integrate distributed activities such as customer service order entry order f...

Page 18: ...uctions and generate output that a web browser can interpret they let web developers build highly interactive and data rich websites which can do tasks such as the following Query other database appli...

Page 19: ...st You can use the ColdFusion GetLocalHostIP function to get the IP address of localhost The URL for a remote site includes the server name or IP address of the server where ColdFusion is installed fo...

Page 20: ...on data management and system functions CFML also includes a built in scripting language CFScript that lets you write code in a manner that is familiar to programmers and JavaScript writers CFML exten...

Page 21: ...tion J2EE specification J2EE provides a common set of infrastructure services for accessing databases protocols and operating system functionality across multiple operating systems About ColdFusion an...

Page 22: ...characters instead of two for example This is a ColdFusion Comment Browsers do not receive it The ColdFusion server removes all ColdFusion comments from the page before returning it to the web server...

Page 23: ...g example cfset YourName Bob Note The cfset tag differs from other tags in that it does not have a body or arguments Instead the tag encloses an assignment statement that assigns a value to a variable...

Page 24: ...e tag and when calling custom tags directly is different from the attributeCollection attribute for all other tags In the cfmodule tag and in custom tags you can mix the attributeCollection attribute...

Page 25: ...e 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 CF...

Page 26: ...name value pairs For example cfscript param name paramname default value min minvalue max maxvalue pattern pattern cfscript cfrethrow rethrow cfthrow throw message For detailed information on the sta...

Page 27: ...tag body You can nest transaction operations For more information on nested transactions see cftransaction in CFML Reference The following example uses nested transaction operations cfscript qry new...

Page 28: ...If you omit this attribute the current thread waits until all specified threads finish running Note You can also use these functions with transactions that you create by using cftransaction tags Serv...

Page 29: ...myQuery execute sql select from art By using attribute setters as in the following example myMail setSubject Hi Note You cannot use a getAttributeName function to get the value of the attribute speci...

Page 30: ...the way service tags return data has changed Now a component is returned with applicable properties set and you need to invoke getters on the properties to access the data Note The PDF object has two...

Page 31: ...s WriteOutput Directory does not exist list directory contents note the usage of getResult and getPrefix r f listDir directory some_dir name dirContents dirContents r getResult r getPrefix succeeded W...

Page 32: ...n query init r here is no longer the query recordset but a component r qryObj execute sql select from art datasource cfdocexamples result myresult name myquery new way to access the data resultset r g...

Page 33: ...newownerpw cfscript Storedproc example The following code shows sample usage of the storedproc service object cfscript sp new storedproc add cfprocparam tags sp addParam TYPE IN CFSQLTYPE CF_SQL_VARCH...

Page 34: ...tegorized lists of ColdFusion functions see ColdFusion Functions in the CFML Reference You use built in functions throughout ColdFusion pages Built in functions are frequently used in a cfset or cfout...

Page 35: ...ute works similarly Explicit set or get methods override the implicit set and get methods Therefore if a CFC has a MyProp property with an explicit setMyProp method and you call the setMyProp function...

Page 36: ...it This way you can write the code once and use it multiple times UDFs ensure consistency of coding and enable you to structure your CFML more efficiently Typical user defined functions include mathem...

Page 37: ...riable represents such as number string or date See Data types on page 32 for a list of data types which also apply to constant values For detailed information on ColdFusion variables including data t...

Page 38: ...e of alphanumeric characters enclosed in single or double quotation marks such as This is a test integers A sequence of numbers written without quotation marks such as 356 real numbers such as 3 14159...

Page 39: ...aultcase 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 body...

Page 40: ...tput LoopCount cfoutput br cfloop 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 thr...

Page 41: ...ut cfloop 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...

Page 42: ...or name for ColdFusion variables UDFs and custom tags Avoid using any name that can be confused with a ColdFusion element In some cases if you use a word that ColdFusion uses for example a built in s...

Page 43: ...CFScript including setting variables loop structures script code blocks and function calls Also the code uses a cfoutput tag to display its results Although you can use CFScript for output the cfoutp...

Page 44: ...mes must conform to Java naming rules and the following guidelines A variable name must begin with a letter underscore or Unicode currency symbol The initial character can by followed by any number of...

Page 45: ...ies and XML document objects You cannot use a complex variable such as an array directly in a ColdFusion expression but you can use simple data type elements of a complex variable in an expression For...

Page 46: ...string Also you can use the JavaCast function in a call to a Java object to convert a ColdFusion empty string to a Java null Numbers ColdFusion supports integers and real numbers You can intermix int...

Page 47: ...You specify strings by enclosing them in either single or double quotation marks For example the following two strings are equivalent This is a string This is a string You can write an empty string in...

Page 48: ...r example if MyList is 1 2 3 4 5 and the delimiter is the comma the list has five elements and list functions treat it the same as 1 2 3 4 5 Boolean values A Boolean value represents whether something...

Page 49: ...Locale specific dates and times ColdFusion provides several functions that let you input and output dates and times and numbers and currency values in formats that are specific to the current locale A...

Page 50: ...llowing functions that convert among string data binary data and string encoded binary data Complex data types Arrays structures and queries are ColdFusion built in complex data types Structures and q...

Page 51: ...t newArray myArray For more information on using arrays see Using Arrays and Structures on page 82 Structures ColdFusion structures consist of key value pairs where the keys are text strings and the v...

Page 52: ...query object s variable name The QueryNew function also creates query objects When you assign a query to a new variable ColdFusion does not copy the query object Instead both names point to the same r...

Page 53: ...ing the local myquery variable cfset Server SScopeQuery myquery To clear the server scope query variable reassign the query object as follows cfset Server SScopeQuery 0 This line deletes the reference...

Page 54: ...tput br cfset myVar myQuery Firstname cfoutput myVar cfoutput br Using periods in variable references ColdFusion uses the period to separate elements of a complex variable such as a structure query XM...

Page 55: ...es myVar a b br cfoutput Setting a variable ColdFusion cannot be as flexible when it sets a variable value as when it gets a variable because it must determine the type of variable to create or set Th...

Page 56: ...cfoutput 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 follo...

Page 57: ...to the listed data type ColdFusion cannot convert complex types such as arrays queries and COM objects to other types However it can convert simple data elements of complex types to other simple data...

Page 58: ...Converting numeric values When ColdFusion evaluates an expression that includes both integers and real numbers the result is a real number To convert a real number to an integer use a ColdFusion funct...

Page 59: ...S comparison operator when testing whether a variable is True or False This issue is a case of the more general problem of ambiguous type expression evaluation described in the following section Ambig...

Page 60: ...r ts is not a valid date because the ColdFusion Now function returns an ODBC timestamp cfquery name MyQofQQ dbtype query SELECT FROM DateQuery WHERE MyDate now cfquery Using JavaCast with overloaded J...

Page 61: ...more information see Specifying the scope of a function on page 173 Scope types The following table describes ColdFusion scopes Scope Description Application Contains variables that are associated wit...

Page 62: ...ope is useful for nested child parent tags This scope can often be used in place of the Application scope to avoid the need for locking variables Several chapters discuss using the Request scope Serve...

Page 63: ...ponent and its functions and not to the page that instantiates the component or calls its functions Scope prefix type Prefix required to reference Where available Created by Application Yes For multip...

Page 64: ...variable Server Yes To any page on the ColdFusion server Surround all code that uses server variables in cflock blocks Specifying the prefix Server when you create the variable Session Yes For one cl...

Page 65: ...you write in a programming language such as C or Java The ColdFusion page that calls a CFX tag must use tag attributes to pass data to the CFX tag The CFX tag must use the Java Request and Response in...

Page 66: ...variable value that does not exist Therefore before you use any variable whose value is assigned dynamically you must ensure that a variable value exists For example if your application has a form it...

Page 67: ...ontain an empty string if the user did not enter data Using the cfparam tag You can ensure that a variable exists by using the cfparam tag which tests for the variable s existence and optionally suppl...

Page 68: ...format There are many ways to ensure the validity of data including the following methods Use the cfparam tag with the type attribute to validate a variable Use the IsValid function to validate a var...

Page 69: ...owever the Java Request Interface getIntAttribute method lets you get a passed integer value Using Expressions and Number Signs In CFML you create expressions by using number signs to indicate express...

Page 70: ...the value of i becomes 8 These operators cannot be used with expressions that involve functions as in f a Also you can use an expression such as x but x and x cause errors because their meanings are a...

Page 71: ...both are False The EQV operator is the opposite of the XOR operator For example True EQV True is True but True EQV False is False IMP Implication The statement A IMP B is the equivalent of the logical...

Page 72: ...he case As a result the following expression is True a IS A When a ColdFusion decision operator compares strings it evaluates the strings from left to right comparing the characters in each position a...

Page 73: ...parenthesize expressions For example 6 3 2 is equal to 0 6 3 2 is equal to 6 You can nest parenthesized expressions When in doubt about the order in which operators in an expression are evaluated use...

Page 74: ...ith Drink Expression evaluation and functions It is important to remember that ColdFusion evaluates function attributes as expressions before it executes the function As a result you can use any ColdF...

Page 75: ...h as Left trim myString position Do not place complex expressions such as 1 2 in number signs Although this is allowed in a cfoutput block such as cfoutput One plus one is 1 1 cfoutput doing so mixes...

Page 76: ...Two expressions inside number signs can be adjacent to one another as in the following example cfoutput Mo and nk is Left Moon 2 Mid Monkey 3 2 cfoutput This code displays the following text Mo and n...

Page 77: ...the same results and can further improve readability cfset FullName FirstName LastName cfset Sentence The length of the full name is Len FullName A common mistake is to place number signs around the a...

Page 78: ...y functions and performing any required operations This process enables ColdFusion to interpret dynamic expressions with variable parts However it incurs a substantial processing overhead Dynamic expr...

Page 79: ...limitation When you use a dynamic variable name in quotation marks 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...

Page 80: ...e DE function is particularly useful with the IIF function to prevent the function from evaluating a string to be output For an example of using the DE function with the IIF function see Using the IIF...

Page 81: ...r cfset myVar 27 9 Sets the two variables to the following strings myVar 27 9 cfoutput myVar2 br myVar br Displays the values assigned to the variables myVar and 27 9 respectively Evaluate myVar2 br P...

Page 82: ...ng cart In this example ColdFusion does the following 1 Replaces the variable i with its value for example 1 2 concatenates the variable value with Form product_ and passes the result for Form product...

Page 83: ...use of the JavaScript and Java operator and can result in more compact code As a result the IIF function can be convenient even if you are not using dynamic expressions The IIF function requires the...

Page 84: ...you are using a form the action page only receives Form variables with the names and values of the form fields The following example shows the shopping cart contents and lets you edit your order and s...

Page 85: ...uct_ Cart i ID cfset skuName sku_ Cart i ID cfset qtyname qty_ Cart i ID td cfinput type checkbox name itemID value Cart i ID checked td td cfinput type text name productName value Cart i Name passThr...

Page 86: ...row has the data for one cart item cfloop index i from 1 to cartItems tr cfset productName product_ Cart i ID cfset skuName sku_ Cart i ID cfset qtyname qty_ Cart i ID td cfinput type checkbox name it...

Page 87: ...t is called by submitting a form This is not needed if the form and action pages are separate but is required if the form and action page were one ColdFusion page cfparam name Form itemID default Set...

Page 88: ...ariable name and a numeric index The index number references a single entry or cell in the array Thus the following statement sets the value of the fifth entry in the one dimensional array MyArray to...

Page 89: ...by specifying two coordinates myarray 1 1 You can use ColdFusion variables and expressions inside the brackets to reference an index as the following example shows cfset myArray ArrayNew 1 cfset myArr...

Page 90: ...leman Charlie Dexter This single statement is equivalent to the four statements used to create the firstname array in Creating arrays using functions on page 85 When you create an array implicitly the...

Page 91: ...ayNew 3 cfset biggerarray 1 1 1 myarray cfset biggerarray 1 1 1 10 3 cfset biggerarray 2 1 1 myotherarray cfset biggerarray 2 1 1 4 2 five deep cfset biggestarray ArrayNew 3 cfset biggestarray 3 1 1 b...

Page 92: ...es it with the new value To prevent existing data from being overwritten use the ArrayInsertAt function as described in the next section If elements with lower number indexes do not exist they remain...

Page 93: ...rray For more information about these array functions see the CFML Reference Deleting elements from an array Use the ArrayDeleteAt function to delete data from the array at a particular index instead...

Page 94: ...ts own copy of the complex data only references to it To demonstrate this behavior run the following code Create an array that contains a structure br cfset myStruct StructNew cfset myStruct key1 Stru...

Page 95: ...et myarray 1 100 Populating an array with the cfloop tag The cfloop tag provides a common and efficient method for populating an array The following example uses a cfloop tag and the MonthAsString fun...

Page 96: ...my3darray cfloop index Dim2 from 1 to ArrayLen my3darray Dim1 cfloop index Dim3 from 1 to ArrayLen my3darray Dim1 Dim2 cfoutput b Dim1 Dim2 Dim3 b my3darray Dim1 Dim2 Dim3 br cfoutput cfloop cfloop c...

Page 97: ...ray functions The following functions are available for creating editing and handling arrays Function Description ArrayAppend Appends an array element to the end of a specified array ArrayAvg Returns...

Page 98: ...as a structure called employee rather than as a collection of individual variables A structure key must be a string The values associated with the key can be any valid ColdFusion value or object It ca...

Page 99: ...hen you know the property names keys in advance and they are strings with no special characters numbers or spaces You cannot use the dot notation when the property or key is dynamic Associative arrays...

Page 100: ...Struct key2Var var2 br br Value of the struct2key2 entry in the key3 structure br myStruct key3 struct2key2 br myStruct key3 struct2key2 br myStruct key3Var struct2key2 br myStruct key3 struct2key2 br...

Page 101: ...key1 br mystruct key1 br mystruct key1Var br br Output the value of the key1 string entry using the following notation object property notation associative array notation with a constant associative...

Page 102: ...1 structKey1 innerStruct1 You cannot use a dynamic variable when you create a structure implicitly For example the following expression generates an error cfset i coInfo cfset i name Adobe Systems Inc...

Page 103: ...use the StructCount function as in the following example StructCount employee To discover whether a specific Structure contains data use the StructIsEmpty function as follows StructIsEmpty structure_...

Page 104: ...ng duplicating and assigning structure variables Technique Use Duplicate function Makes a complete copy of the structure All data is copied from the original structure to the new structure including t...

Page 105: ...ew reference to a structure br cfset structRef myNewStructure cfdump var structRef br br Change a string array element and structure value in the StructCopy copy br br cfset CopiedStruct key1 1A cfset...

Page 106: ...nction what to do if the specified key does not exist By default the function always returns True However if you specify True for the indicateNotExisting argument the function returns True if the key...

Page 107: ...following example uses structures to collect information from a form and to submit that information to a custom tag named cf_addemployee For information on creating and using custom tags see Creating...

Page 108: ...employee phone br Department is StructFind employee department br cfoutput Call the custom tag that adds employees cf_addemployee empinfo employee cfif The form for adding the new employee information...

Page 109: ...ng the structure First name is StructFind employee firstname br Last name is StructFind employee lastname br EMail is StructFind employee email br Phone is StructFind employee phone br Department is S...

Page 110: ...if a referenced key or structure does not exist For more information on these functions see the CFML Reference Code Description cfif StructIsEmpty attributes empinfo cfoutput Error No employee data w...

Page 111: ...n the specified structure This function is redundant with accessing structure elements using associative array notation StructFindKey Searches through a structure for the specified key name and return...

Page 112: ...andard ColdFusion functions UDFs are to ColdFusion built in functions what custom tags are to ColdFusion built in tags Typical uses of UDFs include data manipulation and mathematical calculation routi...

Page 113: ...uage enhancements in ColdFusion 9 include new language constructs extended tag support new keywords script functions implemented as CFCs and support for new operations New tag equivalents in CFScript...

Page 114: ...ding What is supported in CFScript Tag equivalents in CFScript cfthrow throw cftrace trace cftransaction transaction Function Equivalent ColdFusion Tag ftp cfftp http cfhttp mail cfmail pdf cfpdf quer...

Page 115: ...quivalent of cfimport path You cannot use cfimport taglib in cfscript cfinclude include cfinterface interface cflocation location cflock lock cflog writelog cfloop Indexed cfloop for loops Conditional...

Page 116: ...s NOT AND IS and so on the following words are reserved in CFScript Do not use these words as variables or identifiers in your scripting code Script functions For a list of script functions see Script...

Page 117: ...Signs on page 64 Statements CFScript supports the following statements The following rules apply to statements You must put a semicolon at the end of a statement Line breaks are ignored A single stat...

Page 118: ...have to start at the beginning of a line They can follow active code on a line For example the following line is valid MyVariable 12 Set MyVariable to the default value The end of a multiline comment...

Page 119: ...unctions CFScript assignment statements are the equivalent of the cfset tag These statements have the following form lval expression eval is any ColdFusion variable reference for example x positive y...

Page 120: ...ement s Use the following rules and recommendations for switch statements You cannot mix Boolean and numeric constant values in a switch statement Each constant value must be a constant that is not a...

Page 121: ...the found variable to True 3 Otherwise it sets the found variable to False switch name case John case Robert male True found True break case Mary male False found True break default found False end s...

Page 122: ...ed for processing in which an index variable is incremented each time through the loop but it is not limited to this use The following simple for loop sets each element in a 10 element array with its...

Page 123: ...ext statement The following example uses a while loop to populate a 10 element array with multiples of five a ArrayNew 1 loop 1 while loop LE 10 a loop loop 5 loop loop 1 As with other loops make sure...

Page 124: ...ariable can be any ColdFusion identifier it holds each structure key name as ColdFusion loops through the structure The structure must be the name of an existing ColdFusion structure The statement can...

Page 125: ...mbers with specific values such as the empty string Using break The break statement exits the current loop or case statement Processing continues at the next CFScript statement You end case statement...

Page 126: ...cript ColdFusion supports the syntax for defining CFCs including interfaces functions properties and parameters entirely in CFScript Currently however only certain ColdFusion tags are supported as CFS...

Page 127: ...e property operators at the top of the component definition immediately following the opening brace The syntax to define a function is similar to the component definition Comment text treated as a hin...

Page 128: ...03 argOne argTwo WriteOutput arguments argOne WriteOutput arguments argTwo return Arguments written Setting attributes The definition syntax provides two ways to set attributes At the end of a comment...

Page 129: ...ture and contents of the metadata see GetMetaData in the CFML Reference The following trivial code shows the use of component metadata Create an instance of a component theComponent createObject Compo...

Page 130: ...sion has an explicit function local scope Variables in this scope exist only during the execution of the function and are available only to the function To declare a function local scope variable eith...

Page 131: ...is not a reserved word so you can use it as a variable name You can use the cfimport tag or import script operator to import a CFC The import operation puts the contents of the specified component in...

Page 132: ...mport the directory that contains the CFC the cfcPath value is the CFC filename The constructor parameters can be positional or in name value format When you use the new operator ColdFusion does the f...

Page 133: ...e The finally block is optional Its code always runs and runs after the code in the try block and any catch block Exception handling example The following code shows exception handling in CFScript It...

Page 134: ...s acceptedApplicants 1 Cora Cardozo acceptedApplicants 2 Betty Bethone acceptedApplicants 3 Albert Albertson rejectedApplicants 1 Erma Erp rejectedApplicants 2 David Dalhousie rejectedApplicants 3 Fra...

Page 135: ...Creates a structure and assign each array to an element of the structure Creates a structure with rejection codes for rejected applicants The rejectedCode structure does not have entries for all reje...

Page 136: ...s 5 You must provide the exact string pattern to match If the exact pattern is not found Find returns an index of 0 Because you must specify the exact string pattern to match matches for dynamic data...

Page 137: ...tern and return the string index where it finds the pattern For example the following function returns the index of the first instance of the string BIG cfset IndexOfOccurrence REFind BIG Some BIG BIG...

Page 138: ...regular expression A Za z specifies to match any single uppercase or lowercase letter enclosed by spaces In the character set a hyphen indicates a range of characters The regular expression B IAU G m...

Page 139: ...6 cfset IndexOfOccurrence REFind a 2 4 hahahaaahaaaahaaaaahhh The value of IndexOfOccurrence is 6 The regular expression 0 9 3 specifies to match any integer number containing three or more digits 123...

Page 140: ...es you use a special character as a literal character For example if you want to search for the plus sign in a string you have to escape the plus sign by preceding it with a backslash The following ta...

Page 141: ...Parentheses group parts of a regular expression into subexpressions that you can treat as a single unit For example ha matches one or more instances of ha x If at the beginning of a regular expressio...

Page 142: ...line would return an index of zero to signify that it did not find the regular expression If at the beginning of a regular expression it specifies to use positive lookahead when searching for the regu...

Page 143: ...ing Big at the end of the search string and not the fragment big inside the word ambiguous reFindNoCase bBig b Don t be ambiguous about Big The value of IndexOfOccurrence is 26 When used inside a char...

Page 144: ...urrences of the replaces them with an asterisk enclosed in spaces and returns the following string There coffee in kitchen You interpret the regular expression A Za z 1 as follows Use the subexpressio...

Page 145: ...on pears as 2 The REReplace function returns the string pears and apples pears and apples pears and apples Note To use backreferences in either the search string or the replace string you must use par...

Page 146: ...n though the search string in the next example contains two matches of the regular expression the function only returns the index of the first cfset IndexOfOccurrence REFind BIG Some BIG BIG string Th...

Page 147: ...ake the second cfset newstart sLenPos pos 1 sLenPos len 1 1 subtract 1 because you need to start at the first space cfset sLenPos2 REFind BIG Some BIG BIG string newstart True cfoutput cfdump var sLen...

Page 148: ...d b b b one b b two b 1 True cfoutput cfdump var sLenPos cfoutput br Thus the starting position of the string is 1 and its length is 21 which corresponds to the largest of the two possible matches How...

Page 149: ...Za z A Za z0 9_ A ColdFusion variable with no more than one qualifier for example Form VarName but not Form Image VarName 1 9 0 9 An integer that does not begin with a zero and has an optional sign 0...

Page 150: ...except in case conversion sequences or escaped versions for example u or u Embedded modifiers such as i always operate on the entire expression even if they are inside a group and the combinations u...

Page 151: ...run time environment and JavaBeans For information on using Java objects see Integrating J2EE and Java Elements in CFML Applications on page 1125 Microsoft COM Component Object Model objects For info...

Page 152: ...oldFusion page close the block on the same page you cannot include the closing portion of the block in an included page ColdFusion searches for included files as follows The template attribute specifi...

Page 153: ...ML tags You can use UDFs in your application pages just as you use standard ColdFusion functions When you create a function for an algorithm or procedure that you use frequently you can then use the f...

Page 154: ...functions into a single unit they provide an object or class shell from which functions can be called ColdFusion components can make their data private so that it is available to all functions also c...

Page 155: ...sed When a page calls a custom tag it hands processing off to the custom tag page and waits until the custom tag page completes When the custom tag finishes it returns processing and possibly data to...

Page 156: ...return value Your code must be recursive Your functionality is complex To distribute your code in a convenient form to others If you can create either a UDF or a custom CFML tag for a purpose first c...

Page 157: ...the Java and C classes provided by ColdFusion for developing your CFX code For more information For more information on CFX tags see Building Custom CFXAPI Tags on page 224 Selecting among ColdFusion...

Page 158: ...ode Typical uses of UDFs include but are not limited to the following Data manipulation routines such as a function to reverse an array String and date time routines such as a function to determine wh...

Page 159: ...selecting where you define functions see the sections Using Application cfm and function include files on page 173 and Specifying the scope of a function on page 173 About creating functions using CF...

Page 160: ...uired by the function The number of arguments passed into the function must equal or exceed the number of arguments in the parentheses at the start of the function definition If the calling page omits...

Page 161: ...name exponent cfreturn 2 exponent cffunction For more information on how to use the cffunction tag to define a function see Defining functions by using the cffunction tag on page 156 Defining functio...

Page 162: ...ications on page 339 output Optional Determines how ColdFusion processes displayable output in the function body If you do not specify this option ColdFusion treats the body of the function as normal...

Page 163: ...the cffunction tag The function name must be unique It must be different from any existing variable or UDF except that you can use the ColdFusion advanced security function names You can have a user...

Page 164: ...can call the function without argument names on a form action page as follows cfoutput Interest TotalInterest Form Principal Form Percent Form Months cfoutput You can call the function with argument n...

Page 165: ...copy of a structure query or object in the caller pass the variable as an argument Because the function gets a reference to the structure in the caller the caller variable reflects all changes in the...

Page 166: ...tion doubleOneDArrayS OneDArrayStruct var i 0 for i 1 i LE arrayLen OneDArrayStruct Array i i 1 OneDArrayStruct Array i OneDArrayStruct Array i 2 return True Call the function Status doubleOneDArrayS...

Page 167: ...rguments scope looks like the following In this example the following functions return the value 2 because the scope contains two defined arguments ArrayLen Arguments StructCount Arguments However the...

Page 168: ...strong Two Unnamed arguments strong br cfset TestFunction 1 2 strong Three Unnamed arguments strong br cfset TestFunction 1 2 3 strong Arg1 strong br cfset TestFunction Arg1 8 strong Arg2 strong br cf...

Page 169: ...rg1 Arg2 var arg_count ArrayLen Arguments var sum 0 var i 0 for i 1 i LTE arg_count i i 1 sum sum Arguments i return sum With this function any of the following function calls are valid SumN Value1 Va...

Page 170: ...riable named Customer_name exists the function can read and change the variable by referring to it as Customer_name or using better coding practice Variables Customer_name Similarly you can create a l...

Page 171: ...catch blocks and the cfthrow and cfrethrow tags to handle and generate exceptions The technique you use depends on the circumstances of your function and application and on your preferred programming...

Page 172: ...171 uses one version of the status variable method It provides two forms of error information It returns 1 instead of an interest value if it encounters an error This value can serve as an error indic...

Page 173: ...For a description of the initial code see A user defined function example on page 171 Calling the function The code that calls the function now looks like the following Code that is changed from the e...

Page 174: ...m the error handling code and it can be more efficient than other methods at runtime because it does not require testing and branching Exceptions in UDFs have the following two dimensions Handling exc...

Page 175: ...runtime exceptions with ColdFusion tags on page 287 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 th...

Page 176: ...nally use the percent sign for the percentage rate and include the dollar sign and comma separators for the principal amount You could use the TotalInterest function in a cfoutput tag of a form s acti...

Page 177: ...lInterest principal annualPercent months Starts the TotalInterest function definition Requires three variables the principal amount the annual percentage rate and the loan duration in months Var years...

Page 178: ...equest MyFunc Variables MyFunc You can now use the function from any page in the Request scope by calling Request MyFunc Selecting a function scope The following table describes the advantages and dis...

Page 179: ...es You can assure that only the function uses the variable names In these circumstances you can improve efficiency and save processing time by defining your function s variables in the Request scope r...

Page 180: ...ach row in the query cfscript function FullName aFirstName aLastName return aFirstName aLastName cfscript cfquery name GetEmployees datasource cfdocexamples SELECT FirstName LastName FROM Employee cfq...

Page 181: ...produces the expected results the value of the argument if you pass the argument using its fully scoped name Variables myname However the function returns the value of the function local variable if y...

Page 182: ...of functions The page on which you define a CFC is also known as a component page Component pages use the same tags and functions that regular CFML pages do plus a small number of special tags in par...

Page 183: ...FCs have several advantages over UDFs and custom tags These advantages which CFCs automatically provide include all of the following The ability to group related methods into a single component and to...

Page 184: ...arameters The method then performs the function and if specified in the cfreturn tag returns data You can also define variables in a CFC Within a CFC these variables are known as properties Tags for c...

Page 185: ...ods You define component methods using cffunction tags The following example defines a CFC that contains two methods getall and getsalary cfcomponent cffunction name getall output false returntype que...

Page 186: ...et var deptQuery cfquery name deptQuery datasource cfdocexamples dbtype ODBC SELECT FROM tblDepartments cfquery cfreturn deptQuery cffunction cfcomponent Placing executable code in a separate file You...

Page 187: ...ce of the component and the name of the instance data as in objectname ivarname Components whose methods you invoke without first instantiating the component do not typically have instance data You in...

Page 188: ...parameters use multiple cfargument tags The tag names a parameter and lets you specify the following Whether the parameter is required The type of data that is required A default argument value Displa...

Page 189: ...The ColdFusion page processForm cfm calls the appropriate component method based on what the user entered in the form on the tempConversion cfm page Place it in the same directory as convertTemp cfc C...

Page 190: ...form temperature Invokes the ctof method of the convertTemp component without creating an instance of the convertTemp component Specifies newtemp as the result variable for the method Assigns the tem...

Page 191: ...ce cfdocexamples SELECT LASTNAME FIRSTNAME EMAIL FROM tblEmployees WHERE LASTNAME LIKE Arguments lastName cfquery Use cfdump for debugging purposes cfdump var empQuery cffunction cffunction name getCa...

Page 192: ...e the following getLocalTime2 component method returns the local time as a variable to the ColdFusion page or other client that invokes the method cfcomponent cffunction name getLocalTime cfreturn Tim...

Page 193: ...ng the GetMetaData or GetComponentMetaData function to get the metadata Each attribute name is a key in the metadata structure of the CFC element Metadata attributes are used for more than documentati...

Page 194: ...on components You can use a CFC in two ways 1 You can instantiate a CFC object which creates a CFC instance You then invoke the methods of the instance You can access the CFC methods and data as insta...

Page 195: ...lowing example uses the CreateObject function to instantiate the same component in CFScript tellTimeObj CreateObject component tellTime Tag Description cfinvoke Invokes a method of a CFC cfinvokeargum...

Page 196: ...eInfo utcStruct structNew utcStruct Hour DatePart h serverTime utcStruct Minute DatePart n serverTime utcStruct Hour utcStruct Hour utcTime utcHourOffSet utcStruct Minute utcStruct Minute utcTime utcM...

Page 197: ...od getLocalTime that displays the current time 2 Create a ColdFusion page with the following code and save it in the same directory as the tellTime component h3 Time Display Page h3 b Server s Local T...

Page 198: ...ldFusion function such as in cfset tags or surrounded by number signs in the body of a cfoutput tag Invoking component methods in CFScript The following example shows how to invoke component methods i...

Page 199: ...re data security Adobe strongly recommends that you not pass sensitive information over the web using URL strings Potentially sensitive information includes all personal user information including pas...

Page 200: ...TNAME EMAIL FROM tblEmployees WHERE LASTNAME LIKE arguments lastName cfquery cfoutput Results filtered by arguments lastName cfoutput br cfdump var empQuery cffunction cfcomponent 3 Open a web browser...

Page 201: ...but does not find a CFC under that directory ColdFusion returns a not found error and does not search for another directory If you invoke a CFC method remotely using a specific URL a form field Flash...

Page 202: ...a database cfinvoke component UserDataCFC method addUser argumentCollection Form Passing parameters by using the cfinvokeargument tag To pass parameters in the cfinvoke tag body use the cfinvokeargum...

Page 203: ...eyword on page 202 The This scope The This scope is available within the CFC and is shared by all CFC methods It is also available in the base component if the CFC is a child component on the page tha...

Page 204: ...ssing Variables as an argument to the CFC method It also illustrates that the Variables scope is private to the CFC The following code is for the callGreetMe cfm page cfset Variables MyName Wilson cfo...

Page 205: ...ession Application Server and Flash scopes with the calling page Variables in these scopes are also available to all pages that are included by a CFC These variables do not have any behavior that is s...

Page 206: ...erit from other components and ColdFusion initializes instance data in the parent CFC when you instantiate the CFC that extends it Component inheritance defines an is a relationship between components...

Page 207: ...th file You can use it for any core methods or properties that you want all CFCs in your ColdFusion application server instance to inherit Note When you install a newer version of ColdFusion the insta...

Page 208: ...ng 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 C...

Page 209: ...for the length of the user s session If you place the shopping cart CFC in the Session scope you can use component properties to store the cart contents For example the following line creates an insta...

Page 210: ...dFusion function IsUserInAnyRole to determine if a user is in particular role as the following example shows cffunction name foo cfif IsUserInRole admin do stuff allowed for admin cfelseif IsUserInRol...

Page 211: ...y lists the paths of all components When you click a component name in the lower left pane the right pane shows the ColdFusion introspection page as described in Requesting a component page from the b...

Page 212: ...e code particularly queries To illustrate the advantages of CFCs these examples invoke the appropriate method in the CFC that appears in the following example Although Adobe recommends using CFCs to c...

Page 213: ...tDepartments cfquery name GetDepartments datasource cfdocexamples SELECT DISTINCT Location FROM Departmt cfquery cffunction cfcomponent Creating and Using Custom CFML Tags You can extend CFML by creat...

Page 214: ...s the custom tag is referred to as the calling page 1 Create a ColdFusion page the custom tag page that shows the current date cfoutput DateFormat Now cfoutput 2 Save the file as date cfm 3 Create a C...

Page 215: ...he following code specifies to execute the custom tag defined by the mytag cfm page in the parent directory of the calling page cfmodule template mytag cfm For more information on using the cfmessageb...

Page 216: ...dministering ColdFusion Accessing existing custom tags Before creating a custom tag in CFML review the free and commercial custom tags available on the Adobe developer s exchange www adobe com go lear...

Page 217: ...ple use the following code in the getmd cfm page to set the variable Doctor on the calling page cfset Caller Doctor Doctor Attributes Name If the variable Doctor does not exist in the calling page thi...

Page 218: ...quotation marks 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 The val...

Page 219: ...r br cfoutput body html 2 Save the page as callingpage cfm 3 Create another page the custom tag with the following content The value of the variable Attributes Name comes from the calling page If the...

Page 220: ...ustom tag processing reserves the attributeCollection attribute for the structure holding a collection of custom tag attributes If attributeCollection does not reference such a collection ColdFusion g...

Page 221: ...stom tags in a multideveloper environment or distribute your tags publicly you can use the advanced security and template encoding capabilities of ColdFusion The ColdFusion security framework enables...

Page 222: ...o cfmessagebox then ColdFusion calls your custom tag as if it had both a start and an end tag Determining if an end tag is specified You can write a custom tag that requires users to include an end ta...

Page 223: ...hisTag ExecutionMode cfcase value start Start tag processing cfcase cfcase value end End tag processing cfcase cfswitch Considerations when using end tags How you code your custom tag to divide proces...

Page 224: ...tag execution Within a custom tag you typically perform error checking and parameter validation As part of those checks you can choose to abort the tag using cfabort if a required attribute is not sp...

Page 225: ...tags A key custom tag feature is for collaborating custom tags to exchange complex data without user intervention while encapsulating each tag s implementation so that others cannot see it When you u...

Page 226: ...tags including those tags in included pages and custom tag references to the start of the base page for the request Both cfinclude tags and custom tags appear on the tag context stack High level data...

Page 227: ...following functions provide access to ancestral data GetBaseTagList Returns a comma delimited list of uppercase ancestor tag names as a string The first list element is the current tag the next eleme...

Page 228: ...cestorlist getbasetaglist Output your own name You are the first entry in the context stack cfoutput p I m custom tag ListGetAt ancestorlist 1 p Output all the contents of the stack a line at a time c...

Page 229: ...already solves an application problem and you want to incorporate it into your ColdFusion application To meet these types of requirements you can use the ColdFusion Extension Application Programming...

Page 230: ...ent debugging and project management Configuring the classpath To configure your development environment to build Java CFX tags ensure that the supporting classes are visible to your Java compiler The...

Page 231: ...E response write Hello strName 2 Save the file as MyHelloColdFusion java in the WEB_INF classes directory 3 Compile the java source file into a class file using the Java compiler If you are using the...

Page 232: ...nistrator select Extensions CFX Tags 2 For the tag to delete click the Delete icon in the Controls column of the Registered CFX Tags list Processing requests Implementing a Java CFX tag requires inter...

Page 233: ...e Java CFX object is created for each invocation of the Java CFX tag As a result it is safe to store per request instance data within the members of your CustomTag object To store data and objects tha...

Page 234: ...mple to query an archive at the path C logfiles zip for its contents and output the results you use the following CFML code cfx_ZipBrowser archive C logfiles zip name LogFiles cfoutput query LogFiles...

Page 235: ...h your code and displaying variable values Debug the request in an interactive debugger offline from ColdFusion using the special com allaire cfx debugging classes Outputting debugging information Bef...

Page 236: ...d of your CFX tag within the context of the interactive debugger of a Java development environment The three debugging classes are the following DebugRequest An implementation of the Request interface...

Page 237: ...w OutputQuery DebugRequest request new DebugRequest attributes query DebugResponse response new DebugResponse tag processRequest request response response printResults catch Throwable e e printStackTr...

Page 238: ...resents a request made from an application page to a custom tag A pointer to an instance of a request object is passed to the main procedure of a custom tag The methods available from the request obje...

Page 239: ...mple cfx_MyNewTag 4 If the Server Library dll field is empty enter the filepath 5 Accept the default Procedure entry 6 Clear the Keep library loaded box while developing the tag For improved performan...

Page 240: ...ications are not J2EE applications However if you do not specify an application name in your Application cfc file or cfapplication tag the Application scope corresponds to the J2EE application servlet...

Page 241: ...ebox org Information on how to use or develop a specific application framework is not provided However there is information about the tools that ColdFusion provides for building your framework includi...

Page 242: ...sion processes the following two pages if they are available every time it processes any page in the application The Application cfm page is processed before each page in the application The OnRequest...

Page 243: ...cation only Specifying per application settings does not change the server wide settings To set per application settings first enable per application settings on the Settings page of the ColdFusion Ad...

Page 244: ...ing the application establish a root directory for the application You store application pages in subdirectories of the root directory How ColdFusion finds and process application definition pages Col...

Page 245: ...processed file if the settings such as the session time out differ among the files Note If your application runs on a UNIX platform which is case sensitive spell Application cfc Application cfm and On...

Page 246: ...vel constants Application event handlers are CFC methods that ColdFusion automatically executes when specific events occur during the lifetime of an application application start and end session start...

Page 247: ...Session cfset This sessionmanagement True cfset This sessiontimeout createtimespan 0 0 10 0 cfset This applicationtimeout createtimespan 5 0 0 0 For more information on these settings see cfapplicatio...

Page 248: ...f ColdFusion cannot complete processing a page within the time out period it generates an error This setting overrides the setting in the ColdFusion Administrator Use this setting to increase the page...

Page 249: ...e used by multiple pages and requests and must be consistently available to all code in your application Such resources include data sources application counters such as page hit variables or style in...

Page 250: ...et default variables and application level constants in Application cfc For example you can do the following Specify a data source and ensure that it is available Specify domain name Set styles such a...

Page 251: ...provides three methods for managing requests onRequestStart onRequest and onRequestEnd ColdFusion processes requests including these methods as follows 1 ColdFusion always processes onRequestStart at...

Page 252: ...f each request In ColdFusion versions through ColdFusion MX 6 1 you would use the OnRequestEnd cfm page for such code Typical uses include displaying dynamic footer pages For an example see onSessionE...

Page 253: ...cur when the session or application ends Handling server side validation errors in the onError method Server side validation errors are actually ColdFusion exceptions as a result if your application u...

Page 254: ...utput p Error Event EventName p p Error details br cfdump var except p cfoutput cfif cffunction cfcomponent To test this example place a CFML page with the following code in the same page as the Appli...

Page 255: ...NativeErrorCode cfreturn False cfcatch cftry cflog file This Name type Information text Application Started You do not have to lock code in the onApplicationStart method that sets Application scope va...

Page 256: ...Q cfinclude template noauthuserfooter cfm cfelse cfinclude template authuserfooter cfm cfif cffunction cffunction name onSessionStart cfscript Session started now Session shoppingCart StructNew Sessio...

Page 257: ...on specific code that executes only when the application starts Often such code in Application cfm is inside a block that tests for the existence of an Application scope switch variable Remove the var...

Page 258: ...r Client scope variables This setting overrides the method set in the ColdFusion Administrator Specify not to use cookies on the client browser For more information on configuring these options see Us...

Page 259: ...Products clientmanagement Yes clientstorage myCompany sessionmanagement Yes Set page processing attributes cfsetting showDebugOutput No Set custom global error handling pages for this application cfer...

Page 260: ...equest template requesterr cfm mailto admin company com cferror type validation template validationerr cfm Specifies custom error handlers for request and validation errors encounteredintheapplication...

Page 261: ...page request in a temporary file on the server This HTML need not be generated each time the page is requested When ColdFusion gets a request for a cached ColdFusion page it retrieves the pregenerate...

Page 262: ...ushed and a URL pattern that identifies the pages to flush If you do not specify a URL pattern all pages in the directory are flushed The URL pattern can include asterisk wildcards to specify parts of...

Page 263: ...or after an idle time of 30 minutes After the cache is invalidated cache is recreated the next time the page is accessed thereby displaying updated information if any Using Amazon S3 storage Note To...

Page 264: ...end of authentication information Note If you have specified the accessKeyID and awsSecretKey in both the URL and Application cfc then value specified in the URL takes precedence Example cffile action...

Page 265: ...age 261 DirectoryC reate cfdirectory action create directory s3 bucket1 List keys cfdirectory action list DirectoryL ist cfdirectory action list directory s3 bucket1 X y Since Amazon S3 does not have...

Page 266: ...multiple Grants where each grant has a grantee and a permission S3 allows three types of grantees group email canonical ID The following are the possible permissions read write read_acp write_acp full...

Page 267: ...t all_read group all permission read owner_full email xxx yyy com permission full_control aclObj owner_full all_read Access control functions storeSetACL Description Sets the ACL for object or bucket...

Page 268: ...dir test txt This is to test all users permission cfset StoreSetACL dir textl txt myarrray cfset test StoreGetACL dirkey test txt cfdump var test cfcatch cfdump var cfcatch cfcatch cftry storeAddACL...

Page 269: ...t StoreAddACL cfset StoreAddACL dir myarrray cfset test StoreGetACL dirkey cfdump var test cfcatch cfdump var cfcatch cfcatch cftry storeGetACL Description Gets the ACL object or bucket Returns Return...

Page 270: ...or bucket metadata Syntax StoreGetMetadata url Parameters History ColdFusion 9 Update 1 Added this function Example cfdump var StoreGetMetadata bucket_Name StoreSetMetadata Description Sets the metad...

Page 271: ...t Standard keys The following are the standard keys in the metadata For objects last_modified date owner etag content_length content_type content_encoding content_disposition content_language content_...

Page 272: ...n of dynamic code In memory files are supported across almost all tags and functions that take file or directory as input or output You use in memory files in the same manner as files on disk but with...

Page 273: ...f you have one it is ignored Example The following code writes a CFC as in memory file cffile action read file ExpandPath dynamic cfc variable Message cffile action write file ram cfc dynamic cfc outp...

Page 274: ...Info GetDirectoryFromPath GetFileFromPath ImageNew ImageRead ImageWrite ImageWriteBase64 IsImageFile IsPDFFile FileSetLastModified Example The following syntax explains the function FileSetLastModifie...

Page 275: ...copy source ram src test txt destination ram des final txt cffile action rename source ram src message txt destination ram des test txt cffile action move source ram des test txt destination c des mo...

Page 276: ...page appears 2 In the Add Security Sandbox box specify a disk directory and then click Add 3 In Files Directories specify the in memory file path For example ram a b for directory or ram a b dynamic...

Page 277: ...cfimport tag does not accept tag libraries on RAM For instance the following does not work cfimport prefix custom taglib ram a b mytags jar Renaming across file systems as shown in the following synta...

Page 278: ...rocedure that returns three result sets two of which the example uses The stored procedure returns the status code and one output parameter which the example displays cfstoredproc tag cfstoredproc pro...

Page 279: ...roc on the MY_SYBASE_TEST data source Populates the cfstoredprocstatusCode variable with the status code returned by stored procedure cfprocresult name RS1 cfprocresult name RS3 resultSet 3 Gets two r...

Page 280: ...ynamic Forms with cfform Tags on page 722 For information on debugging see Debugging and Troubleshooting Applications on page 378 About error handling in ColdFusion By default ColdFusion generates its...

Page 281: ...r that occurs when a user enters text where a number is required can be considered recoverable because the application can recognize the error and redisplay the data field with a message providing inf...

Page 282: ...an ODBC driver or CORBA server CFML errors or the results of cfthrow or cfabort tags Internal errors in ColdFusion Type Description Exception An error that prevents normal processing from continuing A...

Page 283: ...ude Errors where files specified by the cfinclude cfmessagebox and cferror tags are missing A cferror tag generates a missingInclude error only when an error of the type specified in the tag occurs Th...

Page 284: ...ou can use Java class names to catch exceptions in non CFML Java objects for example the following line catches all Java input output exceptions cfcatch type java io IOException How ColdFusion handles...

Page 285: ...s a page to handle this error type ColdFusion uses the specified error page Error messages and the standard error format If your application does not handle an error ColdFusion displays a diagnostic m...

Page 286: ...t In this code the Replace function removes the leading slash sign from the script name to make the display more friendly Section Description Error description A brief typically online description of...

Page 287: ...rs by surrounding the cfinclude or cfmodule tag in a cftry block The compiler exception on the accessed page gets caught as a runtime error on the base page However avoid this solution to the problem...

Page 288: ...the tag in the Application cfc initialization code or on the Application cfm page to make it apply to all pages in an application A Request error page cannot use CFML tags but it can display error var...

Page 289: ...tion Request or Validation Exception Use only for the Exception type The specific exception or exception category that causes the page to display This attribute can specify any of the types described...

Page 290: ...Please send e mail with the following information to error mailTo to report this error p table border 1 tr td b Error Information b br Date and time error DateTime br Page error template br Remote Ad...

Page 291: ...n you requested this page The error has been logged and we will work to correct the problem We apologize for the inconvenience p cflog type Error file myapp_errors text Exception error Exception type...

Page 292: ...as failed database operations missing include files or developer specified events Ordinarily when ColdFusion encounters an exception it stops processing and displays an error message or an error page...

Page 293: ...e resource availability is not guaranteed is a good candidate for using try catch blocks Try catch code structure In order for your code to directly handle an exception the tags in question must appea...

Page 294: ...entire stack of open tags until it finds a suitable cftry cfcatch combination or reaches the end of the stack Use cftry with cfcatch to handle exceptions based on their point of origin within an appli...

Page 295: ...nt as the exceptionVariable parameter cfcatch ErrorCode The cfthrow tag can supply a value for this code through the errorCode attribute For Type Database cfcatch ErrorCode has the same value as cfcat...

Page 296: ...with this exception Database drivers typically provide error codes to assist in the diagnosis of failing database operations The values assumed by cfcatch NativeErrorCode are driver dependent If no er...

Page 297: ...put Use cfcatch to test for missing included files Print Message and Detail error messages Block executes only if a MissingInclude exception is thrown cfcatch type MissingInclude h1 Missing Include Fi...

Page 298: ...error 2 Create a nonempty includeme cfm file and display the page If your database is configured properly you see an employee entry and do not get any error 3 In the cfquery tag change the line FROM...

Page 299: ...There is no need to put these lines in a cftry block cftry cfquery name test datasource cfdocexamples SELECT Dept_ID FirstName LastName FROM Employee WHERE Emp_ID EmpID cfquery Starts the cftry block...

Page 300: ...b Detail b cfcatch Detail ul cfoutput cfset errorCaught Database cfcatch Handles exceptions thrown when accessing a database Displays cfcatch variables including the ColdFusion basic error message the...

Page 301: ...he handler that most exactly matches handles the error In this case the MyApp BusinessRuleException InvalidAccount handler runs However if you used the following cfthrow tag cfthrow type MyApp Busines...

Page 302: ...tch block except those in the outermost cftry block with a cfrethrow tag Example using nested tags cfthrow and cfrethrow The following example shows many of the discussed techniques including nested c...

Page 303: ...he result cfquery Name getUser DataSource cfdocexamples SELECT FROM Employee WHERE LastName attributes EmpName cfquery cfset caller getEmpsResult getuser If the query failed with a database error chec...

Page 304: ...row cfcatch cftry Now in second level try block Throw all other types of Database exceptions to the next try block level cfelse cfrethrow cfif cfcatch Throw all other exceptions to the next try block...

Page 305: ...catches exceptions in this second database access If the database inquiry succeeds sets the calling page s getEmpsResult variable with the query results cfcatch type Database If the second database q...

Page 306: ...Client Application Session and Server scopes These scopes let you save data over time and share data between pages and even applications Use these scopes as persistent scopes In particular use the Cli...

Page 307: ...that you want to store for a significant period of time Data is stored as cookies database entries or Registry values Client variables can time out after an extended period Although do not have to use...

Page 308: ...re information see Locking code with cflock on page 318 Using variables in clustered systems Because memory variables are stored in memory they are not available to all servers in a cluster As a resul...

Page 309: ...data storage has its own time out period You can specify the database and Registry data time outs in the ColdFusion Administrator ColdFusion sets Cookie client variables to expire after approximately...

Page 310: ...efore do not use client variables if you allow users to disable cookies To retain client information without cookies require users to login with a unique ID You can then save user specific information...

Page 311: ...ion creates the CFToken value by prepending a 16 digit random hexadecimal number to a ColdFusion UUID The resulting CFToken identifier looks similar to the following 3ee6c307a7278c7b 5278BEA6 1030 C35...

Page 312: ...ide the default location by specifying a This clientStorage value in Application cfc or by setting the clientStorage attribute in the cfapplication tag You can specify the following values for the cli...

Page 313: ...tables 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 ta...

Page 314: ...about 4K with ORACLE the limit is about 2K 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 prefi...

Page 315: ...e function or the DeleteClientVariable function For example the following lines are equivalent cfset IsDeleteSuccessful DeleteClientVariable MyClientVariable cfset IsDeleteSuccessful StructDelete Clie...

Page 316: ...ter you create a Registry file you can copy it to a new machine and import it by clicking Import Registry File on the Registry editor Registry menu Note On UNIX systems the registry entries are kept i...

Page 317: ...ion client management J2EE session management provides the following advantages over ColdFusion session management J2EE session management uses a session specific session identifier jsessionid which i...

Page 318: ...n time out value Use the CreateTimeSpan function to specify the number of days hours minutes and seconds for the time out The following sample code enables session management for the GetLeadApp applic...

Page 319: ...Exclusive cfset Session ShoppingCartItems 0 cflock Use the structdelete tag to delete a session variable for example cflock timeout 20 scope Session type Exclusive cfset StructDelete Session ShoppingC...

Page 320: ...ests from the browser continue to use the same session ID until the browser exits It also does not log out the user even if you use Session scope storage for login information Always use the cflogout...

Page 321: ...ode cannot set a time out greater than this value The default value for this time out is two days You can set the time out period for application variables within a specific application by using the T...

Page 322: ...for data that must be accessed across clients and applications such as global server hit counts Server variables do not time out but they are lost when the server shuts down You can delete server vari...

Page 323: ...order of access to information If multiple pages or multiple invocations of a page attempt to write data simultaneously or read and write it at the same time the resulting data can be inconsistent as...

Page 324: ...Order 1 reads the total tickets sold as 160 3 Order 2 reaches the lock tag Because there is an active Application scope lock ColdFusion waits for the lock to free 4 Order 1 adds an order of 5 tickets...

Page 325: ...tten only once For example ensure that the variable is not rewritten if the user refreshes the browser or clicks a back button Also it can be difficult to ensure that you or future developers do not l...

Page 326: ...unning 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 exclusive lock com...

Page 327: ...side a cflock block For example if you want to assign the results of a query to a session variable first get the query results using a Variables scope variable in unlocked code Then assign the query r...

Page 328: ...ode with an exclusive lock in the Application cfc onRequestStart method or the Application cfm page 2 Use the Request scope variables on your ColdFusion pages for the duration of the request 3 Copy th...

Page 329: ...ialized cflock Check the local flag cfif not app_is_initialized Not initialized yet get exclusive lock to write scope cflock scope application type exclusive Check nonlocal flag since multiple request...

Page 330: ...f the total number of turtlenecks sold The following code implements the scheme shown in the Locking Application variables effectively section cfset app_is_initialized no cflock scope Application type...

Page 331: ...hem cflock scope Session timeout 10 type Exclusive cfparam name Session size default form size cfparam name Session color default form color cflock Lock the Application scope variable application numb...

Page 332: ...of synchronizing access to a file system The following example shows how to use a cflock block to synchronize access to a file system The cflock tag protects a cffile tag from attempting to append dat...

Page 333: ...received instead of having to wait for a response to each request before the next request can start One example of such usage is an RSS or Atom feed aggregator A page that sends many mail messages ru...

Page 334: ...fy a priority level of high normal the default or low to specify the relative amount of time that the processor should devote to the thread Page level code always runs at normal priority so you can gi...

Page 335: ...ed true Do additional processing here cfscript cfthread Join the page thread to thread B Don t join to thread A cfthread action join name threadB timeout 10000 Display the thread information cfoutput...

Page 336: ...value thread1 j br thread1 status thread1 Status br thread2 index value thread2 j br thread2 status thread2 Status br cfoutput Note You can also have the ColdFusion Sever Monitor automatically check f...

Page 337: ...lable only to the thread and exist only for the life of the thread Any variable that you define inside the cfthread tag body without specifying a scope name prefix is in the thread local scope and can...

Page 338: ...able only within the thread and only for the life of the thread ColdFusion makes a complete deep copy of all the attribute variables before passing them to the thread therefore the values of the varia...

Page 339: ...thread safe including the following items If multiple threads modify a Variables or Request scope variable use a Request scope lock to control access to the code that uses the variable to prevent dea...

Page 340: ...index variable query name list item pass the loop iterator to the thread as an attribute The following example shows the use of threads inside a loop It uses an indexed cfloop tag to start five threa...

Page 341: ...gs and tag actions that directly send output to the client instead of generating page text such as HTML output do not work inside the thread For example to use the cfdocument or cfreport tags in a thr...

Page 342: ...me t1 cftransaction In this case query q1 is not included in the transaction that contains query q2 To include both queries in the transaction you must place the complete transaction in a single threa...

Page 343: ...join name t1 t2 t3 timeout 6000 Use a loop to display the results from the feeds cfloop index i from 1 to 3 Use the cfthread scope and associative array notation to get the Thread scope cfset feedResu...

Page 344: ...pplication and its event handlers in Application cfc on page 241 Encryption and hashing functions The Encrypt Decrypt and Hash functions let you select a secure algorithm for encrypting and decrypting...

Page 345: ...ber of applications with different purposes and possibly different owners run securely on a single server When multiple applications share a host you set up a separate directory structure for each app...

Page 346: ...oles Employees Human Resources Benefits Managers Roles enable you to control access in your application resources without requiring the application to maintain knowledge about individual users For exa...

Page 347: ...lication authentication where the ColdFusion application authenticates the user and does not allow access to the application by users without valid login IDs Web server authentication All major web se...

Page 348: ...gh the web server s interfaces You can also use web server authentication with ColdFusion application authentication and thus use ColdFusion security for authorization If the web server uses basic HTM...

Page 349: ...on cfc initialization code or cfapplication tag When ColdFusion maintains login information in the Session scope it stores the authentication details in a Session cfauthorization variable and ColdFusi...

Page 350: ...loginuser tag requires three attributes name password and roles and does not have a body The roles attribute is a comma delimited list of role identifiers to which the logged in user belongs All space...

Page 351: ...nd j_password A request that uses HTTP Basic authentication and therefore includes an Authorization header with the user name and password A message from the Flash Remoting gatewayConnection object th...

Page 352: ...play its standard login dialog box instead To do so your cflogin tag body returns an HTTP status 401 to the browser if the user is not logged in or if the login fails that is if it does not have a val...

Page 353: ...ces createGatewayConnection gatewayConnection setCredentials userID password myService gatewayConnection getService securityTest thecfc this For more information on using Flash Remoting see Using the...

Page 354: ...pplication cfm page contains a cflogin tag ColdFusion executes the cflogin tag body if the user is not logged into ColdFusion The user is logged in if the cfloginuser tag has run successfully for this...

Page 355: ...policy store to ensure that the user is valid and get the user s roles 4 If the user name and password are valid the cflogin tag body code calls the cfloginuser tag with the user s ID password and ro...

Page 356: ...tted a login ID and password User submits form Use ID and password to request user s roles from login database Is the user valid Use cfloginuser to log in the user and identify roles In Application cf...

Page 357: ...the required code at the beginning of the method The resulting onRequestStart method has a cfinclude tag that specifies mm_wizard_application_include cfm it also has a simple form with a logout butto...

Page 358: ...st a database Providing user specific role information The Login Wizard sets all users in a single role In mm_wizard_authenticate cfc the performlogin method is hard coded to set the role to user The...

Page 359: ...es a password use the Hash function on the submitted string and compare it with the value in the database Web server based authentication user security example The following example shows how to imple...

Page 360: ...ation and starts the onRequestStart method that runs at the starts of each request The login information on this page only applies to this application cflogin cfif IsDefined cflogin cfif cflogin name...

Page 361: ...le user WriteOutput Everyone in the user role sees this message br br cfscript body html Reviewing the code The following table describes the securitytest cfm page CFML code and its function Applicati...

Page 362: ...amples database that is installed with ColdFusion You can replace this database with any database containing UserID Password and Roles fields The sample database contains the following data Because sp...

Page 363: ...le describes the CFML code in Application cfc and its function Code Description cfcomponent cfset This name Orders cfset This Sessionmanagement True cfset This loginstorage session cffunction name OnR...

Page 364: ...les If the query returns data in the Roles field logs in the user using the user s name and password and the Roles field from the database In this application every user must be in some role cfelse cf...

Page 365: ...control the information that is displayed The securitytest cfm page consists of the following Code Description H2 Please Log In H2 cfoutput form action CGI script_name CGI query_string method Post tab...

Page 366: ...code The following table describes the securitytest cfm page CFML code and its function Code Description cfoutput h2 Welcome GetAuthUser h2 cfoutput Displays a welcome message that includes the user s...

Page 367: ...89 Create the prefix and suffix parts of the user s DN cfset userPrefix cn cfset userSuffix ou Users o mycompany com Concatenate the user s DN and use it to authenticate cfset LDAP_username userPrefix...

Page 368: ...flogin name cfcatch detail script cfoutput cfabort cfif cfcatch cftry If the LDAP query returned a record the user is valid cfif auth recordcount cfloginuser name cflogin name password cflogin passwor...

Page 369: ...n cftry cfldap action QUERY name auth attributes cn referral yes start LDAP_root scope SUBTREE server LDAP_server port LDAP_port filter userfilter username LDAP_username password cflogin password In a...

Page 370: ...onalization Developing language neutral application functionality that can recognize process and respond to data regardless of its representation That is whatever the application can do in one languag...

Page 371: ...nji contains Chinese ideographs adapted to the Japanese language The Japanese language uses a much larger character set than English because Japanese supports more than 10 000 different characters In...

Page 372: ...each character takes up the minimum necessary number of bytes Currently Latin characters are most frequently used on the web and most character encodings used on the web represent those characters in...

Page 373: ...t include characters in that range As a result under the following circumstances characters in the range 80 9F such as the euro symbol are not displayed properly A file encoded in Windows 1252 include...

Page 374: ...ColdFusion tags and functions such as the functions that start with LS format data The last SetLocale function that ColdFusion processes before sending a response to the requestor typically the client...

Page 375: ...ssed by ColdFusion 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 ColdFus...

Page 376: ...format ColdFusion pages cfm pages default to using the Unicode UTF 8 format for the response even if you include the HTML meta tag in the page Therefore the following example doesnot modify the charac...

Page 377: ...cfprocessingdirective pageEncoding Identifies the character encoding of the contents of a page to be processed by ColdFusion For more information see Determining the character encoding of a ColdFusion...

Page 378: ...amount in the current locale LSIsDate Determines whether a string is a valid representation of a date time value in the current locale LSIsNumeric Determines whether a string is a valid representatio...

Page 379: ...LSDateFormat Now d m yy br LSDateFormat Now br hr noshade cfoutput cfloop body html Additional globalization tags and functions In addition to the tags and functions that are specifically for globali...

Page 380: ...specific currencies The 1 4 releases use euros for all currencies that are in the euro zone as of 2002 If you are using a JVM that does not support the euro use the LSEuroCurrencyFormat and LSParseEur...

Page 381: ...sers enter text on a page then submit that text to the server The form tags are designed to work only with single byte character data Since ColdFusion uses 2 bytes per character when it stores strings...

Page 382: ...aracter encoding of the data to read or write as the following example shows cffile action read charset EUC KR file c web message txt variable Message Databases ColdFusion applications access database...

Page 383: ...he cfobjecttype corba tag The CORBA 2 0 interface definition language IDL basic type String used the Latin 1 character encoding which used the full 8 bits 256 to represent characters As long as you ar...

Page 384: ...esses formoreinformation see Debugging IP addresses page on page 380 Select Debugging Output Format Determines how to display debugging output The classic cfm template the default displays information...

Page 385: ...format the information appears at the top of the debugging output and has no heading The general debugging information includes the following values The table lists the names used in the classic outpu...

Page 386: ...called three time in a request it appears only once in the output The following table describes the display fields The page icon indicates the requested page Any page with an average processing time t...

Page 387: ...ok 78 milliseconds and the average processing time was 39 milliseconds This time included the time to process mytag2 cfm this tag calls the mytag2 custom tag therefore the code directly on the page to...

Page 388: ...alerted to caught exceptions when you are debugging your application For example if a file is missing your application can catch the cffile exception and use a backup or default file instead If you en...

Page 389: ...debug pane is updated with the debugging information for the new page Controlling debugging information in CFML The following sections describe how you can use CFML tags and functions to display or h...

Page 390: ...dministrator but only if the Administrator enables debugging Using the IsDebugMode function to run code selectively The IsDebugMode function returns True if debugging is enabled You can use this funct...

Page 391: ...has completed You can display the cftrace tag output in either or both of the following ways As a section in the debugging output To display the trace information in the debugging output in the Admini...

Page 392: ...request to the point of the cftrace tag C CFusion wwwroot MYStuff mydocs tractest cfm Path in the web server of the page that contains the cftrace tag line 14 The line number of the cftrace tag UDF En...

Page 393: ...a cftrace call at the head of pages in your application or before critical tags or calls to critical functions Doing this could result in massive log files in a complex application so use this techniq...

Page 394: ...the category You can include simple ColdFusion variables but not arrays structures or objects in the category text by enclosing the variable name in number signs inline A Boolean value If you specify...

Page 395: ...lowing the cftimer tag Outline Displays timing information at the beginning of the timed code and draws a box around the timed code This requires browser support for the HTML FIELDSET attribute Commen...

Page 396: ...r pages but does not execute the compiled code It reports errors that the compiler encounters It provides information about the incompatibility and its severity and suggests a remedy where one is requ...

Page 397: ...umn 61 Unable to scan the character which follows at line 38 column 53 These errors typically indicate that you have unbalanced or characters One of the most common coding errors is to forget to close...

Page 398: ...nts of your form submission The method attribute in forms sent to the ColdFusion server must be Post for example form action test cfm method Post Problem The browser complains or does not send the ful...

Page 399: ...s 4 Specify the maximum number of simultaneous debug session if different from the default 5 Click Submit Changes 6 You may have to increase the time after which requests time out by doing the followi...

Page 400: ...r is D Shared websites MyCoolSite Eclipse translates the file path D MyCoolApp index cfm to a path that the ColdFusion server recognizes D Shared websites MyCoolSite index cfm To see more information...

Page 401: ...ecified stack frame which is analogous to going in reverse and restarting your program partway through Use Step Filters Step Debug Ensures that all step functions apply step filters Menu Displays the...

Page 402: ...ndow Show View Debug Output Buffer to see the output from your application and how your application appears in a browser 4 Select Window Preferences and specify the home page for your debugging sessio...

Page 403: ...it If you think that the line at which ColdFusion shows an unresolved breakpoint is valid delete the breakpoint and set it again Invalid If ColdFusion determines that the CFML that you edit in Eclips...

Page 404: ...generates by using the Log File Viewer 1 In Eclipse select Window Show View Other ColdFusion CF Log Viewer 2 To view details of a log file double click the name of the file 3 To include the log files...

Page 405: ...on 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 works primarily with relational databases such...

Page 406: ...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 The SQL keywords and syntax are rep...

Page 407: ...se permissions In many database environments a database administrator defines the access privileges for users accessing the database usually through user name and password When a person attempts to co...

Page 408: ...ldFusion includes the cftransaction tag that lets you implement database transactions for controlling rollback and commit For more information see the CFML Reference Database design guidelines From th...

Page 409: ...ement as Select all rows from the table employees where the DeptID is 3 SQL also lets you specify the table columns to return For example instead of returning all columns in the table you can return a...

Page 410: ...ent in a case sensitive database SELECT LastName FROM EMPLOYEES SELECT LASTNAME FROM employees In a case sensitive database employees and EMPLOYEES are two different tables For information on how your...

Page 411: ...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 condition ORDER BY order_condition ASC D...

Page 412: ...is example is useful if you are building a web page that shows the phone numbers for all employees SELECT FirstName LastName Phone FROM employees However this query does not to return the table rows i...

Page 413: ...e The basic syntax of an INSERT statement is as follows INSERT INTO table_name column_names VALUES value_list where column_names specifies a comma separated list of columns value_list specifies a comm...

Page 414: ...E If you omit the WHERE clause to execute the following statement UPDATE employees SET Email jsmith mycompany com you update the Email field for all rows in the table Deleting data from a database The...

Page 415: ...t and delete data at run time as your users interact with pages in their browsers For ColdFusion developers the term data source can refer to different types of structured content accessible locally o...

Page 416: ...Execute SQL code that you specify Store the retrieved data in the query object EmpList When creating queries to retrieve data keep in mind the following guidelines Use opening cfquery and ending cfque...

Page 417: ...a source that connects to the cfdocexamples mdb database This data source is installed by default For information on adding or configuring a data source see Configuring and Administering ColdFusion Qu...

Page 418: ...your cfoutput tag you can refer to the Firstname column in the Emplist query as Firstname However using the query name as a prefix Emplist Firstname is preferred and is in the following procedure The...

Page 419: ...list FirstName As with other attributes surround the query attribute value with double quotation marks As with any variables that you reference for output surround column names with number signs to te...

Page 420: ...xecutionTime br cfoutput cfdump var tmpResult SQLParameters 2 Save the file and view it in your web browser The number of employees now appears below the list of employees If necessary refresh your br...

Page 421: ...ddition to an expected integer for the Emp_ID column this query also passes malicious string code in the form of a SQL statement If this query successfully executes it deletes all rows from the Employ...

Page 422: ...uses the DBMS to use bind variables which can greatly enhance performance Updating Your Database Adobe ColdFusion lets you insert update and delete information in a database About updating your databa...

Page 423: ...message for the end user Creating an HTML insert form The following procedure creates a form using standard HTML tags 1 Create a ColdFusion page with the following content html head title Insert Data...

Page 424: ...e follow these rules for creating the form page Create HTML form fields for only the database columns into which you insert data By default cfinsert inserts all of the form s fields into the database...

Page 425: ...any form data it sends to numeric date or time database columns You can use the hidden field validation functions for these fields to display a custom error message For more information see Introduct...

Page 426: ...You have added Form FirstName Form Lastname to the employee database cfoutput body html 2 Save the page 3 View insert_form cfm in your web browser and enter values 4 Click Submit ColdFusion inserts yo...

Page 427: ...ication pages to update data in a database An update form An update action page You can create an update form with cfform tags or HTML form tags The update form calls an update action page which can c...

Page 428: ...name FirstName value FirstName td tr tr td Last Name td td input type text name LastName value LastName td tr tr td Department Number td td input type text name Dept_ID value Dept_ID td tr tr td Start...

Page 429: ...Makes available as variables the results of the GetRecordtoUpdate query in the form created in subsequent lines form action update_action cfm method Post form Creates a form whose variables are proce...

Page 430: ...atabase cfoutput body html 2 Save the page as update_action 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...

Page 431: ...t appears from the Access database cfquery name UpdateEmployee datasource cfdocexamples UPDATE Employee SET FirstName Form Firstname LastName Form LastName Dept_ID Form Dept_ID StartDate left Form Sta...

Page 432: ...lowing content html head title Delete Employee Record title head body cfquery name DeleteEmployee datasource cfdocexamples DELETE FROM Employee WHERE Emp_ID Form Emp_ID cfquery h1 The employee record...

Page 433: ...ordsets Query of Queries is based on manipulating the recordset which you can create using the cfquery tag and other ways When you execute a database query Adobe ColdFusion retrieves the data in a rec...

Page 434: ...2 cfset temp querysetcell qInstruments years_playing 24 2 cfset temp querysetcell qInstruments name Raoul 3 cfset temp querysetcell qInstruments instrument flute 3 cfset temp querysetcell qInstrument...

Page 435: ...can then display the names of the employees When users select an employee the application displays the details of the employees by selecting information from the cached query without accessing the da...

Page 436: ...m the cfdocexamples data source The detail query selects only the three columns to display for employees with the specified last name The following table describes the code and its function Code Descr...

Page 437: ...5 cfparam name StartRow default 1 master query retrieve all info from Employee table cfquery name GetSals datasource cfdocexamples SELECT FROM Employee ORDER BY LastName cfquery detail query select 3...

Page 438: ...number of records is less than or equal to the total number of rows provide a link to the same page with the StartRow value incremented by MaxRows 5 in this example tr td colspan 4 cfif startrow maxr...

Page 439: ...y of Queries with a Verity recordset 1 Create a ColdFusion page with the following content html head title QoQ and Verity title head body Master query retrieve all documents from the bbb collection th...

Page 440: ...uery dbtype query name GetBoth SELECT FROM GetGIF UNION SELECT FROM GetJPG ORDER BY Name cfquery Display output in a linked ordered list cfoutput p The strong dir strong directory contains GetBoth Rec...

Page 441: ...joins between two tables only Using unions The UNION operator lets you combine the results of two or more SELECT expressions into a single recordset The original tables must have the same number of c...

Page 442: ...s follows Select Type as SportType Name as SportName from Table1 UNION Select from Table2 Duplicate rows and multiple tables By default the UNION operator removes duplicate rows from the result table...

Page 443: ...er keywords with UNION When you perform a UNION the individual SELECT statements cannot have their own ORDER BY or COMPUTE clauses You can only have one ORDER BY or COMPUTE clause after the last SELEC...

Page 444: ...maximum Separate these values with the AND keyword Syntax between_cond expression NOT BETWEEN expression AND expression Example The following example uses a BETWEEN conditional to retrieve only those...

Page 445: ...rrier Scottish Terrier and so on SELECT dog_name dog_IQ breed FROM Dogs WHERE breed LIKE Terrier The following examples are select statements that use bracketed ranges SELECT lname FROM Suspects WHERE...

Page 446: ...e the GetMetaData function Specify the column data types in the QueryAddColumn function 1 Create a query by specifying the QueryNew function with no parameters Make a query cfset myQuery QueryNew 2 Ad...

Page 447: ...e of the following BINARY BIGINIT BIT DATE DECIMAL DOUBLE INTEGER TIME TIMESTAMP VARCHAR For example cfhttp url http quote yahoo com download quotes csv Symbols csco jnpr format sc1l1 ext csv method G...

Page 448: ...AVG SUM MIN MAX ALL DISTINCT numeric_exp 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...

Page 449: ...DESC Example 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 co...

Page 450: ...name having dbtype query SELECT lorange hirange 2 AS x COUNT FROM roysched GROUP BY x HAVING x 10000 cfquery Handling null values Query of Queries uses Boolean logic to handle conditional expressions...

Page 451: ...ists 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...

Page 452: ...00 000 ODBC format Dates times or timestamps in one of the following format Date string d value for example d 2004 07 06 Time string t value for example t 13 45 30 Timestamp string ts value for examp...

Page 453: ...T2 c Understanding Query of Queries processing Query of Queries can process the following Column comparisons Queries passed by reference Complex objects Comparing columns with different data types St...

Page 454: ...LDAP protocol is provided However it is assumed that you have information on the structure and attributes of your LDAP database Hence procedures to create an LDAP directory or manage a directory serve...

Page 455: ...mmetric 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...

Page 456: ...minal nodes of an LDAP directory is an entry In the preceding images each item is an entry For example in the first diagram both USA and Ferrari are entries The USA entry s attributes could include a...

Page 457: ...than one attribute value pair In multivalued RDNs a plus sign separates the attribute value pairs In the sample directories individuals could have complex RDNs consisting of their common name and the...

Page 458: ...specific usage indicator For standard attributes a registered numeric ID specifies the syntax and matching rule information For more information on attribute syntaxes see ETF RFC 2252 at http www iet...

Page 459: ...attributes port username password timeout secure rebind referral scope filter sort sortControl startRow maxRows separator delimiter add server dn attributes port username password timeout secure rebin...

Page 460: ...Jones specify the following filter filter cn Robert Jones cn Bobby Jones You can use object classes as search filter attributes for example you can use the following search filter filter objectclass...

Page 461: ...on their object class For example the following code retrieves the contents of the Airius directory cfldap name GetList server myServer action query attributes scope subtree start o airius com sort s...

Page 462: ...name fragment p form action cfldap cfm method POST input type text name name br br input type submit value Search form make the LDAP query Note that some search text is required A search filter of cn...

Page 463: ...nenumber td tr cfoutput table cfif body html 2 Change the server attribute from ldap airius com to the name of your installation of the Airius database 3 Save the page as cfldap cfm and run it in your...

Page 464: ...lara attributes cn sn ou mail telephonenumber sort ou sn maxrows 100 timeout 20000 Connects anonymously to LDAP server ldap airius com query the directory and return the results to a query object name...

Page 465: ...nd click Update the application deletes all the attributes for the User The application should ensure that all required attribute fields contain valid entries before updating the directory Adding a di...

Page 466: ...put h3 Entry for User ID Form uid has been added h3 cfoutput cfif cfif cfif html head title Update LDAP Form title head body h2 Manage LDAP Entries h2 cfform action update_ldap cfm method post table t...

Page 467: ...required for Add br cfform Output the user list h2 User List for the Human Resources Department h2 cfldap name GetList server myServer action query attributes cn sn mail telephonenumber uid start o A...

Page 468: ...Trim Form uid IS NOT Ensures that the user entered a User ID in the form cfif Form action is add If the user clicks Add processes the code that follows cfif Trim Form fullName is OR Trim Form surname...

Page 469: ...called The value attribute lets ColdFusion update the form contents when the form is redisplayed after the user clicks Add The code that handles cases in which the user fails to enter all the required...

Page 470: ...uid 1 cfelseif Form action is Delete cfldap action delete dn uid Trim Form UID ou People o Airius com server myServer username myUserName password myPassword cfoutput h3 Entry for User ID Form UID ha...

Page 471: ...with Value Delete at the bottom of the form delete the td mark Code Description cfelseif Form action is Retrieve cfldap name GetEntry server myServer action query attributes cn sn mail telephonenumbe...

Page 472: ...You can add or delete attributes only if the directory schema defines them as optional for the entry s object class Code Description cfelseif Form action is Update cfset attributelist cn Trim form Ful...

Page 473: ...separate attribute values in a value list Similarly an attribute can contain a semicolon which cfldap normally uses to delimit separate attributes in an attribute list To override the default separat...

Page 474: ...Ds attribute type syntax IDs or the object class descriptions The object class description values are all Standard Object Class Note To be able to view the schema for an LDAP server the server must su...

Page 475: ...ploc 5 mustloc suploc 7 cfoutput td cfelse td NONE td cfif cfif mayloc NEQ 0 td cfoutput Replace Mid thisElement mustloc 6 mayloc mustloc 9 all cfoutput td td cfoutput Replace Mid thisElement mayloc 5...

Page 476: ...foutput Mid thisElement descloc 6 syntaxloc descloc 8 cfoutput td cfif singleloc EQ 0 td cfoutput Yes cfoutput td cfelse td cfoutput No cfoutput td cfif tr cfloop table body html 2 Change the server f...

Page 477: ...scope base start Gets the value of the subschemaSubentry attribute from the root of the directory server The value is the DN of the schema cfldap name EntryList2 server ldap mycorp com action query at...

Page 478: ...ID The ID is not displayed Gets the length of the thisElement string for use in later calculations tr td cfoutput Mid thisElement nameloc 6 descloc nameloc 8 cfoutput td cfif suploc NEQ 0 td cfoutput...

Page 479: ...der 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 server It also...

Page 480: ...rts alias ldap file ldap crt keypass bl19mq The keytool utility initial keypass password is change it For more information on using the keytool utility see the Sun JDK documentation Once ColdFusion es...

Page 481: ...page 477 Recordsets returned from a query and CF query object including cfquery cfldap and cfpop queries You can build collections from individual documents or from an entire directory tree Collectio...

Page 482: ...e output to the client web browser Verity can index database text fields such as notes and product descriptions that native database tools cannot effectively index When indexing collections that conta...

Page 483: ...t Works WPS 1 through 2000 Microsoft Windows Write WRI 1 2 3 WordPerfect for Windows V5 WO 5 5 1 WordPerfect for Windows V6 and higher WPD 6 7 8 10 2000 WordPerfect for Macintosh 1 02 2 2 1 2 2 3 3 1...

Page 484: ...reelance Graphics 2 PRE 2 Microsoft PowerPoint for Windows PPT 95 97 2000 2002 Microsoft PowerPoint for PC PPT 4 Microsoft PowerPoint for Macintosh PPT 98 Microsoft Project MPP 98 2000 2002 Display fo...

Page 485: ...are indexing data select the language from the pop up menu when you create a collection with the ColdFusion Administrator In CFML the cfcollection cfindex and cfsearch tags have an optional language...

Page 486: ...the ColdFusion Administrator to create and index a collection Creating a collection with the ColdFusion Administrator Use the following procedure to quickly create a collection with the ColdFusion Adm...

Page 487: ...with creating a collection you can index a collection programmatically or by using the ColdFusion Administrator Use the following guidelines to determine which method to use You can use cfcollectiona...

Page 488: ...ent html head title Collection Creation Input Form title head body h2 Specify a collection h2 form action collection_create_action cfm method POST p Collection name input type text name CollectionName...

Page 489: ...case value Optimize cfcollection action Optimize collection Form CollectionName p The collection Form CollectionName is optimized p cfcase cfcase value Delete cfcollection action Delete collection For...

Page 490: ...e for the type attribute cfindex expects a corresponding value in the key attribute For example if you specify type file cfindex expects a directory path and filename for the key attribute The type at...

Page 491: ...Save the file as collection_index_form cfm in the myapps directory under the web_root Note The form does not work until you write an action page for it which you do when you index a collection Use cfi...

Page 492: ...the indexing operation to all directories below the selected path select the Recursively index subdirectories check box 6 Optional Enter a Return URL to prepend to all indexed files This step lets you...

Page 493: ...maximum number of records returned by the search Always specify this attribute to ensure optimal performance start with 300 or less if possible Attribute Description RecordCount The total number of r...

Page 494: ...this form which ColdFusion passes as the variable criteria to the action page which displays the search results Create the results page 1 Create a ColdFusion page with the following content html head...

Page 495: ...n retrieved documents to determine whether they contain the desired information This can be especially useful when searching lengthy documents letting users quickly locate relevant information returne...

Page 496: ...ernative spellings for misspelled queries using a dictionary that is dynamically built from the search index To implement alternative spelling suggestions you use the cfsearch tag s suggestions attrib...

Page 497: ...4 Enter any misspelled target words and click Search Narrowing searches by using categories Verity lets you organize your searchable documents into categories Categories are groups of documents or da...

Page 498: ...xing collections that contain categories When you index a collection with support for categories enabled do the following Specify a category name using the category attribute The name or names that yo...

Page 499: ...on a collection that was created without category information an exception is thrown To search collections that contain categories you use the cfsearch tag and create an application page that searche...

Page 500: ...s categoryList action The categoryList action returns a structure that contains two keys Use the information returned by categoryList to display to users the number of documents available for searchin...

Page 501: ...body cfoutput form action CGI SCRIPT_NAME method POST Enter Collection Name input Type text Name collection value collection br input Type submit Value GetInfo form cfoutput cfif isdefined Form collec...

Page 502: ...your website 4 Search the collection The information returned from the collection includes the database key and other selected columns You can then use the information as is or use the key value to r...

Page 503: ...a ColdFusion query 1 Create a Verity collection for the data that you want to index The following example assumes that you have a Verity collection named CodeColl You can use the ColdFusion Administr...

Page 504: ...l action Update type Custom key Emp_ID title Emp_ID body Emp_ID FirstName LastName Salary h2 Indexing Complete h2 Output the record set p Your collection now includes the following items p cfoutput qu...

Page 505: ...rm s in the box below You can use AND OR NOT and parentheses Surround an exact phrase with quotation marks p p input type text name criteria size 50 maxLength 50 p p input type submit value Search p f...

Page 506: ...w collection_db_search_form cfm in the web browser and enter the name of the collection and search terms Indexing a file returned by using a query You can index an individual file that uses a query by...

Page 507: ...d Custom 1 td td Custom1 td tr tr td Column list td td ColumnList td tr table p cfoutput Indexing a path returned by using a query You can index a directory path to a document or collection of documen...

Page 508: ...splay the directory path 1 Create a ColdFusion page that contains the following content cfsearch collection Form collname name getEmps criteria Form Criteria maxrows 100 Output the directory path cont...

Page 509: ...e OrgList server myserver action query attributes o telephonenumber dn mail scope onelevel filter O a O b sort o start c US Output query record set cfoutput query OrgList DN dn br O o br TELEPHONENUMB...

Page 510: ...tput POP query record set cfoutput query p_messages messagenumber br from br to br subject br body br hr cfoutput Index record set cfindex action refresh collection pop_query key messagenumber type cu...

Page 511: ...search for a phrase only if you use quotation marks Because Verity treats multiple word searches differently it helps your users if you provide examples on your search page or a brief explanation of h...

Page 512: ...t searches for the word that you specify as well as words that have the same stem For more information on the MANY modifier see Modifiers on page 521 In CFML enter your search terms operators and modi...

Page 513: ...Although NOT is a modifier you use it only with the AND and OR operators Therefore it is sometimes casually referred to as an operator For more information see Operators and modifiers on page 515 The...

Page 514: ...haracters The search engine handles several characters in particular ways as the following table describes Wildcard Description Example Search result Matches any single alphanumeric character apple ap...

Page 515: ...al parser supports searching the full text of documents only The Natural parser does not support searching collection fields and zones The Natural parser does not support Verity query language except...

Page 516: ...a series of names with commas Commas aren t needed when the phrases are surrounded by quotation marks The following example searches for a document that contains the phrases San Francisco and sourdou...

Page 517: ...template file to be modified Query syntax The query syntax is like the syntax that users expect to use on the web Queries are interpreted according to the following rules Individual search terms are s...

Page 518: ...se languages If you use the configurable Internet query parser for another language provide your own qp_inet stp file that contains the stop words that you want to ignore in that language This stop wo...

Page 519: ...hes first for documents that contain Larry and Jerome and then for documents that contain Moses OR Moses AND Larry Jerome The infix notation equivalent of this is as follows Moses OR Larry AND Jerome...

Page 520: ...ng table shows the operators according to type that are available for conducting searches of ColdFusion Verity collections Character Usage Left and right angle brackets are reserved for designating op...

Page 521: ...PAGES 5 in your search Similarly if a document field named DATE is defined you can search for documents dated before and including December 31 1999 by entering DATE 12 31 99 in your search The follow...

Page 522: ...ose titles contain music musical or musician search for TITLE CONTAINS Musi To retrieve CFML and HTML pages whose meta tags contain Framingham as a content word search for KEYWORD CONTAINS Framingham...

Page 523: ...type Explicit criteria 1990 and CF_TITLE SUBSTRING Utah cfoutput Record Counts br GetText RecordCount br GetText_Search RecordCount br cfoutput Query Results Should be 5 rows br cfoutput query Gettext...

Page 524: ...postrophe and question mark spam retrieves matches such as spam spammer and spamming WORD Performs a basic word search selecting documents that include one or more instances of the specific word that...

Page 525: ...of these words within close proximity to each other as defined by Verity To control search proximity use NEAR N NEAR N Selects documents containing two or more search terms within N number of words o...

Page 526: ...puters If the search element s original score is 785 the COMPLEMENT operator recalculates the score as 215 Modifier Description Example CASE Specifies a case sensitive search Normally Verity searches...

Page 527: ...ported file formats see Building a Search Interface on page 476 Verity searches XML files by treating the XML tags as zones When you use the zone filter the Verity engine builds zone information into...

Page 528: ...on bbb type explicit criteria Pete in Lead_Guitar Rhythm_Guitar Field searches Fields are extracted from the document and stored in the collection for retrieval and searching and can be returned on a...

Page 529: ...you can do this in CFML or in the ColdFusion Administrator The following table shows the relationship between the database column and cfindex attribute You begin by selecting all data in a query cfque...

Page 530: ...The following code displays the results of the refined search table border 1 cellspacing 5 tr th align LEFT KEY th th align LEFT TITLE th th align LEFT CUSTOM1 th tr cfoutput query search_calls tr td...

Page 531: ...ection name Language support Solr supports the following languages Danish Dutch Finnish French German Italian Norwegian Spanish Portugese Russian Swedish Chinese Japanese Korean Czech Greek Thai Solr...

Page 532: ...rch1 collection solr_complex criteria roam Alternate way to perform a fuzzy search for roam cfsearch name qsearch1 collection solr_complex criteria roam Searching for higher similarity with roam cfsea...

Page 533: ...eria title fuzzy1 txt OR title fuzzy2 txt Alternatively you can search using the following syntax cfsearch name qsearch collection solr_srch criteria title test fuzzy1 String search cfsearch name qsea...

Page 534: ...e default values for query parameters lst name defaults str name echoParams explicit str str name hl fl summary title str omp Only More Popular str name spellcheck onlyMorePopular false str exr Extend...

Page 535: ...e collection in the Name field 5 Browse and select the path of the Verity collection that you want to migrate 6 Click Submit Step 2 Change search engine in cfcollection tag Specify the search engine f...

Page 536: ...h examples on page 526 and for Verity see Using Verity Search Expressions on page 505 Configuring Solr memory Perform the following steps to increase the memory for Solr Non Windows platforms 1 Stop S...

Page 537: ...ng ColdFusion 9 Applications 1 In the ColdFusion Administrator go to ColdFusion Collections and then click a Solr collection 2 Use the Enable Disable button to enable disable term highlighting 3 Reind...

Page 538: ...ch as cfquery cfinsert and cfupdate which handle SQL statements Managing objects using ColdFusion components CFCs and object lifecycle using the application itself Writing SQL queries for each CFC eve...

Page 539: ...he persistent attribute should be set to true in the cfcomponent tag The table attribute should be set to the table name If table attribute is not specified then the CFC name is taken as the table nam...

Page 540: ...Obj setfax 612 832 2344 newArtistObj setemail jsmith company com newArtistObj setThePassword jsmith EntitySave newartistobj ormflush catch Exception ex WriteOutput p ex message p cfscript To update an...

Page 541: ...RTIST cfproperty name art type array fieldtype one to many cfc Art fkcolumn ARTISTID fieldtype one to many specifies the type of relation CFC Art is used to convey that the relationship is with ART cf...

Page 542: ...ation file if it is specified in the application The Hibernate configuration file contains various configuration parameters like including dialect cache settings and mapping files that are required fo...

Page 543: ...onfigured 1 Enable ORM for the application To do this set the ormenabled property to true in the THIS scope of application cfc 2 Provide the data source name by either setting data source property to...

Page 544: ...at should be used by ORM as secondary cache The values can be Ehcache JBossCache Hashtable SwarmCache OSCache Fully qualified name of the class for any other cache provider This setting is used only w...

Page 545: ...uest end If flushatrequestend isfalse ormflush isnotcalledautomaticallyatrequest end See ORM session management logSQL false Specifies whether the SQL queries that are executed by ORM will be logged I...

Page 546: ...s to be saved to disc If you set the value to true the Hibernate mapping XML file is saved with the filename CFC name hbmxml in the same directory as the CFC If any value of savemapping is specified i...

Page 547: ...the logs get logged to console using HIBERNATECONSOLE which is actually a console appender It can easily be changed to a FileAppender which will then be logged to a log file The configuration controls...

Page 548: ...ional Syntax cfcomponent accessors yes no persistent true false entityname entity_name table table_name schema schema catalog catalog dynamicInsert true false dynamicupdate true false readonly true fa...

Page 549: ...e values are not null are included in the SQL dynamicupdate Optional false Whether UPDATE SQL is to be generated at runtime true false Only those columns that have changed values are included in the S...

Page 550: ...ves the generated Hibernate mapping file to the disk If you have set savemapping for the application then the value you set here overrides it schema Optional Used to specify the schema name selectbefo...

Page 551: ...on to indicate that the column contains versioned data For details see Version Timestamp Specify the fieldtype timestamp to indicate the column contains data with timestamp For details see Time stamp...

Page 552: ...ription column Optional The value of the name attribute Used to specify the primary key column name fieldType Optional Should be id for primary key If fieldtype is not specified and the useDBForMappin...

Page 553: ...generated key This strategy requires ORM to execute two SQL queries to insert a new object sequence For databases such as DB2 Oracle PostgreSQL Interbase McKoi and SAP which support sequences you can...

Page 554: ...ate that a cfproperty maps to a column in the table specify fieldtype column If the fieldtype is not specified for cfproperty it is mapped as a column property Syntax cfproperty name Property name fie...

Page 555: ...lue for this property is always generated by database insert Specifies that the value for this property is generated at the time of insert but is not regenerated at updates insert optional true Specif...

Page 556: ...hrown Version Use the version attribute to indicate that the column contains versioned data The version attribute is useful for long transactions Attribute Req Opt Default Description dbdefault option...

Page 557: ...tive to the version attribute Syntax cfproperty name fieldname fieldtype timestamp column column name generated true false source vm db Attribute Req Opt Default Description column Optional The name o...

Page 558: ...pt Default Description column Optional The name of the column that contains time stamped data fieldtype Required Specifies the field type Specify the field type value as timestamp for a time stamped f...

Page 559: ...or bidirectional A unidirectional association means that source has the reference to the target but the target does not know about the source A bidirectional association means that both the objects ha...

Page 560: ...tch fetching cacheuse one to many many to many optional Use this value to specify the caching strategy to be used for caching this component s data in the secondary cache See Caching for details cache...

Page 561: ...the name of the index for the foreign key column insert many to one Optional true Specifies whether the column should be included in SQL UPDATE and or INSERT statements Values are true false Set updat...

Page 562: ...red Name of the field notnull many to one optional false Use this to add the not null constraint for the foreign key column when the table is created by ORM optimisticlock all Optional true Whether up...

Page 563: ...ibute is not used on a many to one or a many to many relationship singularname one to many many to many optional property name Use this property to define the custom name for generated relationship me...

Page 564: ...ART object While persisting ARTIST and the associated ART the relationship can be established in the database from both sides of the object Setting inverse true on one side of the relation tells ORM...

Page 565: ...e Size cfcomponent fieldtype one to one specifies that the property is a one to one property constrained true on Employee property in OFFICECUBICLE cfc means that a constraint is set on the OFFICECUBI...

Page 566: ...pe one to one cfc officecubicle mappedby Employee cfcomponent OFFICECUBICLE cfc cfcomponent persistent true table officecubicle cfproperty name id fieldtype id generator native cfproperty name Employe...

Page 567: ...he link table linkschema Schema for the link table fkcolumn Foreign Key column name inversejoincolumn Column name or comma separated list of primary key columns type array orderby order_by_string casc...

Page 568: ...ype int structkeycolumn ArtID type struct specifies that the artist object will contain art objects in a struct structkeycolumn ArtID specifies that the key of the struct would be ArtID Note that ARTI...

Page 569: ...in Art table references the primary key ARTISTID of ARTIST table Many to many relationships A many to many relationship is where the source objects contain a collection of target objects and the targe...

Page 570: ...relationship is established using a third table OrderProduct that has two foreign keys OrderId and ProductId OrderId references the primary key orderId in the order table and ProductId references the...

Page 571: ...olumn_name elementtype ormtype elementColumn column_name from the link table that should be used for populating orderby order by string lazy true false readonly true false optimisticlock true false ba...

Page 572: ...al The foreign key column in the specified table If you do not specify the foreign key column and useDBForMapping is true in ormsettings ColdFusion automatically determines a foreign key column after...

Page 573: ...ptional The foreign key column in the table If foreign key column is not specified and useDBForMapping is set to true in ORMSetting ColdFusion automatically determines the Foreign Key column after ins...

Page 574: ...chy In the preceding figure discriminatorColumn is PaymentType Depending on the values of PaymentType whether it is credit card or check the row is represented as a CreditCardpayment or checkPayment o...

Page 575: ...CheckPayment cfc cfcomponent persistent true extends Payment table CheckPayment joinColumn paymentId cfproperty name checkNo cfproperty name bankName cfproperty name city cfcomponent When an object o...

Page 576: ...y key of the Payment table The value of PaymentType is the value of disciminatorColumn attribute of the respective object Embedded mapping This mapping is used when a CFC has an embedded object which...

Page 577: ...o has to be defined in the XML as shown in the following example Here employee object has a collection of IMData objects Note that the IMData object is not persistent employee cfc cfcomponent persiste...

Page 578: ...roperty name houseno column houseno table Address joincolumn addressId cfproperty name street table Address joincolumn addressId cfproperty name city table Address joincolumn addressId cfproperty name...

Page 579: ...property name mediaid type int column length 10 name MEDIAID property property name issold type boolean column length 5 name ISSOLD property many to one class cfc artGallery Artists column artistid na...

Page 580: ...ssor methods for a property store the property value in the VARIABLES scope for ORM to access it Generated methods for relationships between CFCs When a relationship is defined in a CFC ColdFusion gen...

Page 581: ...example of artists ARTISTS table and artwork ART table where the artist forms a one to many relationship with artwork Artist cfc cfcomponent persistent true schema APP table Artists cfproperty name a...

Page 582: ...n with the given entityname an error will be thrown If the persistent CFC has an init method then the function EntityNew calls the init method while creating the object Syntax entity EntityNew entityN...

Page 583: ...init method the methods call the init method while creating objects Syntax EntityLoad entityname EntityLoad entityname id unique EntityLoad entityname filtercriteria unique EntityLoad entityname filte...

Page 584: ...sfies the condition an exception occurs This example loads the artist object whose firstName is Austin and lastname is Weber cfset artist EntityLoad artist firstname Austin lastname Weber true EntityL...

Page 585: ...ray If unique true and multiple records are returned then an exception occurs EntityReload entity Reloads data for an entity that is already loaded in this session This method refetches data from the...

Page 586: ...unning complex queries In general use HQL in the following scenarios The query is not specific to a particular object but only to some fields in the object To retrieve some fields of the object withou...

Page 587: ...iceid 100 cfset artObj ORMExecuteQuery from ART where priceid 100 To retrieve an array of objects that contain the first name of artists cfset firstNameArray ORMExecuteQuery select FirstName from Arti...

Page 588: ...the artwork being sold or not you can write a query similar to the following cfset artist ORMExecuteQuery SELECT art Artist Firstname art Artist Lastname SUM art Price as Sold FROM Art as art WHERE ar...

Page 589: ...he application has to flush close the session and commit rollback the transaction For more information on transactions go to the following URL http community jboss org wiki sessionsandtransactions Usi...

Page 590: ...lability in highly concurrent applications because it locks a database for a transaction that could run for a longer time Also a transaction cannot run beyond the duration of a request There can be sc...

Page 591: ...utomatically set to the current time Sometimes this is preferred over version because it also tells you when the user object was last modified In case updating fails because the timestamp was changed...

Page 592: ...single SQL query using Joins Fetch only required data to reduce the load on the database SQL queries are generated and executed by the underlying ORM engine Therefore Hibernate provides various hooks...

Page 593: ...many cfc ART fkcolumn artistId lazy true Extra lazy This applies to one to many and many to many relationships This type of lazy loading goes one step ahead of lazy and does not load all the associat...

Page 594: ...are referenced in the current request This is generally useful in nested tree loading You can specify this using batchsize attribute for CFC or relationship property There are two ways you can tune b...

Page 595: ...d Architecture on page 537 Secondary level cache ColdFusion provides the ability to store the data that is retrieved from the database in secondary cache The contents in secondary cache live longer th...

Page 596: ...ryThreadIntervalSeconds The number of seconds between runs of the disk expiry thread The default value is 120 seconds Note The functions cacheGetProperties and cacheSetProperties can be used to get se...

Page 597: ...overhead than the two preceding strategies Transactional This strategy provides the support for transactional cache It can only be used if the cache provider is transaction aware Support for these st...

Page 598: ...ng query data pass cacheable true and cachename cachename values in the options struct of the methods If you do not specify the cachename the query is cached in the default query cache It is recommend...

Page 599: ...mponent_name collection_name primarykey This method is used to evict all the collection association data for the given component name and collection name from the secondary cache If the primary key is...

Page 600: ...of cache which ensures that only one copy of an object exists in the session When CRUD operations are performed in the session data of the entity is not synchronized with the database immediately Tha...

Page 601: ...e data source specified in the application ORMFlush Flushes the current ORM session associated with the data source specified in the application ORMFlush flushes all the pending CRUD operations in tha...

Page 602: ...dle callback when any entity is inserted updated deleted or retrieved This CFC must be configured at the application level as an ORM setting ormsettings evenHandler X Y EventHandler The event handler...

Page 603: ...or the auto generated tables and columns DDL only attributes are used only for DDL generation For details of these attributes see the table in the section DDL only attributes in Column on page 549 Exa...

Page 604: ...the table name specified for the CFC If it is not specified the entity name is taken as the logical table name If the entity name is also not specified the unqualified CFC name for example Person for...

Page 605: ...u use in the mapping including link table and fkcolumn even though there is no CFC or cfproperty associated with them Populating the database using script After the tables are created using DDL you ca...

Page 606: ...act with each other A single data source makes it impossible to build the entire application using ORM Building three separate applications is not advisable as the interaction between the applications...

Page 607: ...scenarios the data source information must be provided in the CFC and not in hbmxml file Also all CFCs used in one hbmxml file must have the same data source Example The following example illustrates...

Page 608: ...the request If ORM is not configured for this data source it results in an exception If data source is not specified the Hibernate session of the default data source is returned Use this session obje...

Page 609: ...learSession Description Clears the Hibernate session associated with the given data source The function clears the first level cache and removes the objects that are not yet saved to the database If y...

Page 610: ...e this function for another data source specify the data source key value pair within the queryoptions Syntax ORMExecuteQuery hql params unique ORMExecuteQuery hql unique queryoptions ORMExecuteQuery...

Page 611: ...Remoting MX 2004 and Flash Remoting ActionScript Dictionary in Flash Help You can also access the Flash Remoting documentation on the Flash Remoting Developer Center at www adobe com go learn_cfu_flas...

Page 612: ...m business logic enables your ColdFusion applications to interact with multiple client types such as SWF applications web browsers and web services When you build ColdFusion applications for multiple...

Page 613: ...rule you do not have to change these web xml settings Flash Remoting MX 2004 ActionScript 2 0 API Features Enforcement of strict data typing which requires you to declare the data types of variables a...

Page 614: ...gateway config xml file Also the Flash gateway now supports a whitelist which specifies which remote sources can be accessed through the gateway The two web xml entries that identify the whitelist mu...

Page 615: ...specific application server By default the login command tag is set to the following values login command class flashgateway security JRunLoginCommand class server match JRun server match login comman...

Page 616: ...receive HTTP requests that are not sent with AMF data By default the redirect url tag is set to context root which is the context root of the web application redirect url context root redirect url cas...

Page 617: ...e if you pass the parameters as an ordered array from Flash array 1 references the first value If you pass the parameters as named parameters you use standard structure name syntax like params name Yo...

Page 618: ...ses a structure to a SWF application 1 Create a folder in your web root and name it helloExamples Collection ActionScript example Notes Strict array var myArray Array new Array myArray 0 zero myArray...

Page 619: ...ervice http localhost flashservices gateway null helloExamples null null Call the service helloWorld method var pc PendingCall howdyService helloWorld Tell the service what methods handle result and f...

Page 620: ...owing code calls the getData function of the CFMService and uses the first parameter to request a page size of 5 import mx remoting import mx services Log import mx rpc Connect to helloExamples servic...

Page 621: ...a ColdFusion page For more information see Using the Flash Remoting service with ColdFusion pages on page 611 Create a CFC that interacts with a SWF application 1 Create a CFC and save it as flashCom...

Page 622: ...loExamples directory Calling the helloWorld function in this example executes the function that is defined in flashComponent For ColdFusion components the component filename including the directory st...

Page 623: ...ngCall javaService sayHello Tell the service what methods handle result and fault conditions pc responder new RelayResponder this sayHello_Result sayHello_Fault function sayHello_Result re ResultEvent...

Page 624: ...ror message from causeError is fe fault description This example displays the trace message from the causeError_Fault function in the Flash Output panel The portion of the message that is contained in...

Page 625: ...compile in Flex Builder If you installed LiveCycle Data Services with ColdFusion and want to use messaging or data management select Flex Data Services 3 If you select Flex Data services select wheth...

Page 626: ...of the Properties dialog 3 In the Additional Compiler arguments add services followed by the absolute path to the services config xml file in the local ColdFusion installation For example on a Window...

Page 627: ...or the CFC for example service id remoting service class flex messaging services RemotingService messageTypes flex messaging messages RemotingMessage adapters adapter definition id cf object class col...

Page 628: ...xml The following table lists the XML attributes for services config xml Element Description destination id The destination attribute that the MXML mx RemoteObject tag must specify to access the CFC...

Page 629: ...ler for the returned result of the CFC method call for the mx RemoteObject tag as the following example shows private function my_CFC_handler event ResultEvent Show alert with the value that is return...

Page 630: ...tion These features let an AIR application use a local SQLite database that represents data on the ColdFusion server You cannot use these features in applications built with Flash which run in a brows...

Page 631: ...r Side notes When the sync function performs a DELETE operation it gets the primary key ID from the OriginalObject of the Sync method as the ClientObject is NULL For update and insert operations use t...

Page 632: ...from the server However the client method does not delete the stale record which no longer exists in the server database from the client database To prevent this issue The serverObject property of th...

Page 633: ...icates that the field is a primary key in the table For composite keys use Id tags on all the primary key fields Transient A Boolean value specifying whether the property or field is persistent A True...

Page 634: ...example of the Employee and Department objects in a database If you do not specify attribute values the default values are taken as follows The default table name is the class name The default value f...

Page 635: ...blic class Employee Id var id uint OneToMany targetEntity Department mappedBy department fetchType EAGER LAZY default var depts ArrayCollection There is no column specified in the Employee table but r...

Page 636: ...although it may not be as intuitive because of the asynchronous connection with the database The fetch type EAGER or LAZY determines the fetch type for the relationship that is loaded An EAGER fetch...

Page 637: ...When you specify cascadeType ALL or REMOVE and try to delete the parent object by passing it through session remove parentObj it does not delete the child objects To overcome this limitation use the...

Page 638: ...se the SyncManager fetch method to fetch data from the ColdFusion server by calling the fetch method of the server data object The syncManager fetch method takes the name of the CFC fetch method typic...

Page 639: ...accessible through the Documentation link on the Resources page of the ColdFusion Administrator Notes The SQLite database doesn t validate column types when it creates a table If you give it an inval...

Page 640: ...t happened on the session are passed to the CFC sync function The sync function determines if there are any conflicts between the returned information If there are no conflicts it updates the server d...

Page 641: ...nly property to the server value of the data and returning the array of conflict objects to the AIR client The following code is an ideal example of sync method that uses ORM methods for syncing opera...

Page 642: ...ult as ArrayCollection var token SessionToken session keepAllServerObjects conflicts token addResponder new mx rpc Responder conflictSuccess conflictFault The conflictevent object contains an array of...

Page 643: ...ave new data available from other clients ActionScript has a few reserved keywords When you name the Class SQLite table ensure that you do not use any of the reserved keywords For example Order is an...

Page 644: ...eType ALL fetchType EAGER JoinColumn name add_id referencedColumnName aid public var address Address Address as package onetoone Bindable RemoteClass alias AIRIntegration address Entity public class A...

Page 645: ...and CFC syncmanager new SyncManager syncmanager cfPort 80 syncmanager cfServer localhost Path of the Server side CFC from CF webroot syncmanager syncCFC AIRIntegration cusManager This handler is call...

Page 646: ...cess savefault else Alert show No data available from Server to save on local DB private function saveCacheSuccess event SessionResultEvent void Alert show Data saved on client Sqlite DB from Server A...

Page 647: ...eSuccess event SessionResultEvent void Alert show Customer was updated Successfully Let s Load another Customer for example with id 128 to perform a Delete operation on that var loadtoken SessionToken...

Page 648: ...function sessionclosesuccess event SessionResultEvent void Alert show Session Close Success Fault Handlers private function fetchFault event SyncFaultEvent void Alert show fetch fault event toString p...

Page 649: ...ver side code Create the following cfc files Application cfc Customer cfc Address cfc and Cusmanager cfc with code like the following The AIR client interacts with the Cusmanager cfc file in which you...

Page 650: ...object clientobjects i cfset originalobject originalobjects i cfif operation eq INSERT cfset obj ORMGetSession merge clientobject cfset EntitySave obj cfelseif listfindnocase UPDATE DELETE operation n...

Page 651: ...uced in AIR 1 5 Cache file used by ActionScript ORM to track the operations on SQLite database is now in the applicationStoragedirectory instead of applicationDirectory You can specify the location of...

Page 652: ...y has a key value 5 then the next key is generated with the value 6 5 1 if incrementBy is set to 1 Example Integer Primary Keys package test apollo CFSQLiteSupport INCREMENTPK Entity RemoteClass alias...

Page 653: ...e File userDirectory resolvePath customerManger db dbDir File applicationStorageDirectory var keyGenerator EncryptionKeyGenerator new EncryptionKeyGenerator var encryptionKey ByteArray keyGenerator ge...

Page 654: ...onScript ORM The following ActionScript class definition for customer entity illustrates how all the self join relationships are defined package Bindable RemoteClass alias AIRIntegration customer Enti...

Page 655: ...ray ArrayCollection to hold multiple entities In addition to Array you can now use ArrayCollection to hold multiple entities in a database relationship ArrayCollection can also be used in the ActionSc...

Page 656: ...e client object for every conflict instance in the ArrayCollection Returns An instance of coldfusion air SessionToken which is the token for keepAllClientObjects call Syntax public function keepAllCli...

Page 657: ...dd additional information that can be passed from where the API is called to the success or fault handlers Example private function fetchData void var token AsyncToken syncmanager fetch fetch token ad...

Page 658: ...PK event autoGeneratedId toString var loadtoken SessionToken session loadByPK Order oid RememberINTPK true loadtoken addResponder new mx rpc Responder loadsuccess loadfailure Note Assume that the serv...

Page 659: ...add the cfservices swc file to your project by right clicking Flex AIR Project Properties Flex BuildPath Library Path Add SWC For details on all ColdFusion service classes and other classes in the col...

Page 660: ...ttachment to the server on which the action has to be performed The upload URL to supply to the flash net FileReference APIs can be constructed as follows in the ActionScript part of the application u...

Page 661: ...ctionality of the cfmail tag You specify the required cfmail and child tag attributes for the action as Mail tag attributes The default Mail action on this tag is send The following AIR application us...

Page 662: ...edentials are correct and CF server is running Error private function checkCollapse event MouseEvent void if event clickCount 2 currentState currentState collapsed collapsed private function rememberC...

Page 663: ...P mx TextInput id cfip text width 70 mx Label text CFServer Port mx TextInput id cfprt text width 40 mx Labeltext CFServer Context Root if any mx TextInput id cfcnxtrt text width 70 mx Label text CFSe...

Page 664: ...private var fileslist ArrayCollection private var filereflist FileReferenceList public var fileRef FileReference new FileReference Bindable public var mailPartArray Array type text content Plain text...

Page 665: ...Event UPLOAD_COMPLETE_DATA dataHandler fileRef upload uploadURL else if fileslist length 0 sendmail called after a file has been successfully uploaded We use this as well to check if there are any fil...

Page 666: ...00 mx HBox width 100 mx Text text From width 100 mx TextInput width 100 id from mx HBox mx HBox width 100 mx Text text To width 100 mx TextInput width 100 id too mx HBox mx HBox width 100 mx Text text...

Page 667: ...edApplication Using the Image class The Image class is the proxy for the ColdFusion Image service which provides the functionality of the cfimage tag You specify the required cfimage attributes for th...

Page 668: ...get the modified image back from the server To use this action use an associative array of actions and corresponding attributes It is easier to create an associative array in ActionScript than MXML Th...

Page 669: ...t action extractpages source http localhost 8500 lcds26_devguide_040908 pdf pages 2 keepBookmark true resultHandler handleExtractResult errorHandler handleExtractError addwatermark cf Pdf id pdftest a...

Page 670: ...Chart class The Chart class is the proxy for the ColdFusion Chart service which provides the functionality of the cfchart tag and its child chartdata and chartseries tags You specify the cfchart attri...

Page 671: ...tion init void chaDat item Facilities value 35000 item Facilities1 value 32000 chaSer type bar chartdata chaDat type line chartdata chaDat chartest execute function handleResult event ResultEvent void...

Page 672: ...ent that is not in a section as a content element of the document object You represent document sections in the documentSection element of the document object The documentSection element is an arrays...

Page 673: ...shows some typical document use xml version 1 0 encoding utf 8 mx Application xmlns mx http www adobe com 2006 mxml layout vertical xmlns cf coldfusion service mxml creationComplete init mx Script CDA...

Page 674: ...lt tr gt lt table gt doc item case cf Document id doctestnow action generate format flashpaper result handleResult event fault handleError event documentItem docItem doc section case cf Document id d...

Page 675: ...re public function handleGetAll event ResultEvent void var res Array event result as Array for var i uint 0 i res length i var key String for key in res i trace object key key toString if res i key nu...

Page 676: ...assembler lets you use ColdFusion components CFCs to provide the back end data management for a Flex application that uses the Data Management Service You can run LiveCycle Data Services ES as part of...

Page 677: ...r CFC which runs the appropriate methods in the DAO CFC 7 The ColdFusion application creates an array of Value Objects or appropriate return value which it sends to the ColdFusion server 8 The ColdFus...

Page 678: ...adapter the channels to use to transport messages to and from the destination the CFC that contains the fill get sync and count methods and other settings To provide configuration information you edit...

Page 679: ...her case here could be that you have integrated LCDS 2 6 1 with ColdFusion 9 and still you want to use old Flash Remoting You can implement this scenario but in this case you cannot take advantages of...

Page 680: ...llection All the other files that need to be referenced from services config xml are now included in services config xml In ColdFusion 8 the services config xml files looked similar to the following C...

Page 681: ...definition The new services config xml file looks similar to this channel definition id cf polling amf class mx messaging channels AMFChannel endpoint uri http server name server port context root fl...

Page 682: ...cf rtmp channel in the channels section If you are running LiveCycle Data Services ES in ColdFusion the services config xml file is in the wwwroot WEB INF flex directory and contains the channel defi...

Page 683: ...y property of the value object CFC in the this scope If your CFC does not have any getters and setters you can increase performance by setting this to false so that ColdFusion does not spend time look...

Page 684: ...name or IP address of the ColdFusion host If you are running LiveCycle Data Services as part of ColdFusion you do not specify a host name or IP address however if you are running LiveCycle Data Servi...

Page 685: ...ult value is true auto refresh true auto refresh Determines whether order is important for this filled collection Allows for performance optimization when order is not important Optional Default value...

Page 686: ...ethod returns the results of a read operation In the fill method you create an array to hold the results of the read and then return the results of the read operation The essential elements of a fill...

Page 687: ...var ret ArrayNew 1 Loop through the query to create each Value Object based on each row of the query for example cfloop query qRead cfscript obj createObject component samples contact Contact init obj...

Page 688: ...ipt property If you use the other syntax for example contact firstName Joan ColdFusion makes the key name uppercase Managing fills To determine whether to refresh a fill result after an item is create...

Page 689: ...getLastName If the first or last name contains the search string cfif FindNoCase search first NEQ 0 OR FindNoCase search last NEQ 0 this record is in the fill cfreturn true cfelse this record is NOT i...

Page 690: ...d changes cfset var newchanges ArrayNew 1 Loop over the changes and apply them cfloop from 1 to ArrayLen changes index i cfset co changes i cfif co isCreate cfset x doCreate co cfelseif co isUpdate cf...

Page 691: ...iveCycle Data Services ES assembler you use the Flex setRemoteCredentials method on the DataService object The credentials which are in the FlexSession object are passed to the ColdFusion application...

Page 692: ...RE To enable SSL you do the following 1 Create the keystore 2 Configure Flex 3 Enable SSL in the ColdFusion Administrator Create the keystore Generate the SSL server ColdFusion keystore file by using...

Page 693: ...Flex Integration and specify the keystore file in the Full Path to Keystore text box 2 Specify the keystore password in the Keystore password text box 3 Select the Enable RMI over SSL for Data Managem...

Page 694: ...server side ActionScript you want to use For example notice the embedded comments This include is needed to connect to the Flash Remoting service include NetServices as This line determines where Flas...

Page 695: ...r on the server anywhere below the root directory of the web server To specify subdirectories of the web root or a virtual directory use package dot notation use dots instead of slashes in a fully qua...

Page 696: ...e the reference pages for these functions in the CFML Reference For additional information on using Flash Remoting see Using the Flash Remoting Service on page 606 and Using Flash Remoting Connecting...

Page 697: ...convention that ties it to the function that calls the server side ActionScript For example if you defined a client side ActionScript function called basicCustomerQuery you also must create a results...

Page 698: ...1 Create a server side ActionScript file that performs queries against a ColdFusion data source 2 Write ActionScript code in your SWF movie that references your ActionScript file asr on the ColdFusion...

Page 699: ...urce ordinarily means the entry point to a ColdFusion database Your ColdFusion administrator can help you identify and configure data sources To create ActionScript files that successfully perform que...

Page 700: ...he syntax for the positional argument style CF query positional argument syntax CF query datasource sql CF query datasource sql maxrows CF query datasource sql username password CF query datasource sq...

Page 701: ...The server side ActionScript application that you create provides the back end services in an application This example requires the following A server side ActionScript file named personneldirectory a...

Page 702: ...e searchdata CF query datasource bigDSN sql SELECT from personnel WHERE fname firstName AND lname lastName if searchdata return searchdata else return null Creating the SWF movie interface The SWF mov...

Page 703: ...e following example the results function search_Result supplies the record set to the dataView setDataProvider function function search_Result resultset dataView setDataProvider resultset status text...

Page 704: ...P Get and Post methods as follows Using the Get method you send information to the remote server directly in the URL This method is common for a one way transaction in which the CF http function retri...

Page 705: ...harset is specified in the charset parameter of the Content Type header field of the HTTP protocol For example the following HTTP header announces that the character encoding is EUC JP Content Type te...

Page 706: ...d ColdFusion page or an executable that interprets the variables being sent and returns data For example when you build an HTML form using the Post method you specify the name of the page to which for...

Page 707: ...things like file content header information MIME type and so on The following example uses the CF http function to show a common approach to retrieving data from the web Returns content of URL define...

Page 708: ...lent in HTML cfcalendar Lets users select dates from a Flash month by month calendar cfgrid Displays and lets users enter data in a row and column grid format can get data directly from a query cfslid...

Page 709: ...featured pleasing forms The CFML tags used here do not describe or use most of their special features See Building Dynamic Forms with cfform Tags on page 722 for information on how to use many of the...

Page 710: ...First Name cfinput type Text name FirstName size 20 maxlength 35 br Last Name cfinput type Text name LastName size 20 maxlength 35 br Salary cfinput type Text name Salary size 10 maxlength 10 p List...

Page 711: ...eck boxes radio buttons and list boxes do not pass data 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 n...

Page 712: ...se with a SQL SELECT statement When the WHERE clause is processed it filters the query data based on the results of the comparison For example to return employee data for only employees with the last...

Page 713: ...h the name you typed followed by a line with the text Contractor Yes 5 Click Back in your browser to redisplay the form 6 Remove the check mark from the check box and submit the form again This time a...

Page 714: ...in fields To specify a field as required you can do either of the following Use the required attribute of the cfinput cfselect cftextarea and cftree tags Use a hidden field that has a name attribute...

Page 715: ...tring if you do not enter text An error occurs if the action page tries to use a variable that was not passed If multiple controls have the same name one form variable is passed to the action page wit...

Page 716: ...ry td tr cfoutput table br cfif IsDefined Form Contractor cfoutput Contractor Form Contractor cfoutput cfif body html 3 Save the page as actionpage cfm in the myapps directory 4 View the formpage cfm...

Page 717: ...construct a database query To give users the option to enter multiple search criteria in a form you can wrap conditional logic around a SQL AND clause as part of the WHERE clause The following action...

Page 718: ...Departmt Dept_Name cfqueryparam value Form Department CFSQLType CF_SQL_VARCHAR cfif cfif Form LastName IS NOT AND Employee LastName cfqueryparam value Form LastName CFSQLType CF_SQL_VARCHAR cfif cfqu...

Page 719: ...ame Add a procedure after the cfif tag that displays a message to the user Add a procedure after the cfelse tag to format the returned data Follow the second procedure with a cfif tag end to indicate...

Page 720: ...ram value Form Department CFSQLType CF_SQL_VARCHAR cfif cfif Form LastName is not AND Employee LastName cfqueryparam value Form LastName CFSQLType CF_SQL_VARCHAR cfif cfquery cfif GetEmployees recordc...

Page 721: ...formation is available because some browsers do not respond if you flush only a small amount Similarly if you use an interval attribute set it for a reasonable size such as a few hundred bytes or more...

Page 722: ...llowing table describes the code and its function Code Description h2 We are sure you will agree it was worth the short wait h2 cfflush Sends the HTML header and all HTML output to the cfflush tag to...

Page 723: ...ally populate the options of this form control Dynamically populate a list box 1 Open the formpage cfm page 2 Modify the file so that it appears as follows html head title Input form title head body c...

Page 724: ...s with the same name or a multiple selection list box that is a box in which users can select multiple items from the list the user s entries are made available as a comma delimited list with the sele...

Page 725: ...e for a simple set of check boxes that lets the user select departments looks like the following cfinput type checkbox name SelectedDepts value 1 Training br cfinput type checkbox name SelectedDepts v...

Page 726: ...cified qualifying character here a single quotation mark around each item in the list If you select the second and fourth check boxes in the form the following statement gets sent to the database SELE...

Page 727: ...ield The query retrieves detailed information on the selected departments as follows cfselect name SelectDepts multiple option value Training Training option value Marketing Marketing option value HR...

Page 728: ...e user submits the form so the data reappears if the form gets redisplayed The information here describes features of the cfform tag and focuses on using several of the cfform child tags that do not h...

Page 729: ...orrectly set the completePath attribute to True The preservedata attribute has no effect on a cfgrid tag If you populate the control from a query update the data source with the new data typically by...

Page 730: ...e cftree tag you use individual cftreeitem tags to populate the control You can create trees in three formats Applet Creates a Java applet that the client must download Downloading an applet takes tim...

Page 731: ...hscroll No border Yes height 350 required Yes cftreeitem value Dept_ID FullName query deptquery queryasroot Dept_ID img computer folder document imgopen computer folder expand yes cftree br br input t...

Page 732: ...using the queryasroot tag that value is returned as the root If you do not specify a root name ColdFusion returns the query name as the root If there is no query name ColdFusion returns the tree name...

Page 733: ...ployee ORDER BY Dept_ID cfquery cfform name form1 action submit cfm cftree name tree1 cftreeitem value FullName query deptquery queryasroot Department img folder document cftree br cfinput type submit...

Page 734: ...value Finance parent Divisions img element cftree cfform Image names in a cftree tag Note The information here applies to applet format trees In Flash you cannot control the tree icons Flash uses open...

Page 735: ...e href attribute of the cftreeitem tag The URL for the link can be a relative URL or an absolute URL as in the following examples Embed links in a cftree control 1 Create a ColdFusion page named tree3...

Page 736: ...trol over user inputs provides error handling and most importantly lets you automatically populate the selection list from a query You can populate the drop down list box from a query or using lists o...

Page 737: ...ame myslider bgcolor cyan bold Yes range 0 1000 scale 100 value 600 fontsize 14 label Slider value height 60 width 400 cfform 2 Save the file as slider cfm and view it in your browser To get the value...

Page 738: ...1 action submit cfm cfgrid name employee_grid query empdata selectmode single cfgridcolumn name Emp_ID cfgridcolumn name LastName cfgridcolumn name Dept_ID cfgrid br cfinput name submitit type Submit...

Page 739: ...itable Use the cfgrid attribute selectmode edit to edit cell contents Use the cfgridcolumntype attribute to control sorting order to make the fields check boxes or to display an image Use the cfgridco...

Page 740: ...row number All rows for a particular change have the same index in all arrays Unchanged rows do not have entries in the arrays If the user changes a single cell in col2 the following array elements c...

Page 741: ...ge with the following content cfquery name empdata datasource cfdocexamples SELECT FROM Employee cfquery cfform name GridForm action handle_grid cfm cfgrid name employee_grid height 425 width 300 vspa...

Page 742: ...a ColdFusion page with the following contents Code Description cfgrid name employee_grid height 425 width 300 vspace 10 selectmode edit query empdata insert Yes delete Yes Populates a cfgrid control w...

Page 743: ...ll modify the cell contents and then press Return Reviewing the code The following table describes the highlighted code and its function Updating the database with the cfquery tag You can use the cfqu...

Page 744: ...yee_grid rowstatus action counter is D cfquery name DeleteExistingEmployee datasource cfdocexamples DELETE FROM Employee WHERE Emp_ID cfqueryparam value Form employee_grid original Emp_ID counter CFSQ...

Page 745: ...code and its function Code Description cfif isdefined Form employee_grid rowstatus action cfloop index counter from 1 to arraylen Form employee_grid rowstatus action If there is an array of edit type...

Page 746: ...re all the applet s parameters every time you want to use it in a ColdFusion page cfelseif Form employee_grid rowstatus action counter is U cfquery name UpdateExistingEmployee datasource cfdocexamples...

Page 747: ...et with a simple form of the cfapplet tag cfapplet appletSource appletname name form_variable Overriding alignment and positioning values To override any of the values defined in the ColdFusion Admini...

Page 748: ...en a user enters a name in a telephone number field or the form could force the user to enter the number in the correct format They help prevent application errors that can arise when processing inval...

Page 749: ...ut the test is not done until the user submits the form In Flash format this validation type is identical to onBlur Validation Flash checks do not differentiate between the two events for validation o...

Page 750: ...The following table describes additional considerations for selecting a validation technique For additional considerations that are specific to form fields see Validation type considerations on page...

Page 751: ...idation rules are submitted with the form Hidden form field Does not require browser support Can be used with HTML or CFML form elements Limited to forms Can be circumvented because validation rules a...

Page 752: ...ese cases the table indicates the limitations The onBlur and onSubmit validation algorithms for Flash forms can vary from the validation algorithms described in the following table and most commonly h...

Page 753: ...CE format xxxxxxxx xxxx xxxx xxxx xxxxxxxxxxxx where x is a hexadecimal number uuid A universally unique identifier UUID that follows the ColdFusion format xxxxxxxx xxxx xxxx xxxxxxxxxxxxxxxx where x...

Page 754: ...ffer depending on the validation technique and the form type As a result the algorithms used vary in some instances including the following The validation algorithms used for date time values in onSub...

Page 755: ...erations For detailed information on error handling in ColdFusion including invalid data handling see Handling Errors on page 275 1 For onBlur onSubmit or onServer validation you can use the cfinput o...

Page 756: ...g code goes here cfif Masking form input values The cfinput tag mask attribute controls the format of data that can be entered into a text or datefield input field You can also use a mask attribute in...

Page 757: ...pattern You can concatenate simple regular expressions into complex search criteria to validate against complex patterns such as any of several words with different endings You can use ColdFusion var...

Page 758: ...the caret the expression matches any character except those characters in the set It does not match the empty string For example akm matches any character except a k or m The caret loses its special m...

Page 759: ...ater than zero indicating the start of the range and n is equal to or greater than m indicating the end of the range For example ba 0 3 matches up to three pairs of the expression ba The form m requir...

Page 760: ...ation To specify hidden field validation you do the following Create one HTML input element or CFML cfinput tag of type hidden for each validation rule Specify the name of the field to validate as the...

Page 761: ...y format that ColdFusion can understand converts the input to ODBC date format Allows entry of a time part but removes it from the ODBC value _cfformusdate A date in the form m d y m d y or m d y The...

Page 762: ...h the form page and its action page The page uses an IsDefined function to check that form data has been submitted This way the pages does not show any results until you submit the input The form uses...

Page 763: ...length 16 br Salary input type text name Salary size 10 maxlength 10 br input type reset name ResetForm value Clear Form input type submit name SubmitForm value Insert Data form br Action part cfif is...

Page 764: ...st enter a start date input type hidden name StartDate_cfformdate value Enter a valid date as the start date Requires input into the StartDate input field If there is no input displays the error infor...

Page 765: ...from 8 through 12 characters long If the password is invalid the browser displays a message box If the password is valid it redisplays the page with a brief success message Use JavaScript to validate...

Page 766: ...rm body html 2 Save the page as validjs cfm 3 View the validjs cfm page in your browser Handling failed validation The onError attribute lets you specify a JavaScript function to execute if an onValid...

Page 767: ...fform Validating data with the IsValid function and the cfparam tag The IsValid function and cfparam tag validate any ColdFusion variable value not just forms variables Because they reside entirely on...

Page 768: ...l cfinput type Text name emailAddr br cfinput type submit name saveSubmit value Save Data br cfform Examples cfparam tag validation The following two examples use cfparam tags to do the same tests as...

Page 769: ...type Text name emailAddr br cfinput type submit name saveSubmit value Save Data br cfform The expresserr cfm page looks as follows cfoutput You entered invalid data br Please click the browser Back bu...

Page 770: ...I SCRIPT_NAME preservedata Yes User ID cfinput type Text name UserID br Phone cfinput type Text name phoneNo br E mail cfinput type Text name emailAddr br cfinput type submit name saveSubmit value Sav...

Page 771: ...A Flash form example Flash forms provide many features that help you quickly create easy to use professional looking complex forms The following image contains a two tab form that shows many of these...

Page 772: ...ally aligned boxes or tabbed navigators that let you group organize and structure the form contents Flash forms follow a hierarchical structure of containers and children 1 The cfform tag is the maste...

Page 773: ...rt plain text in the form You can use the style attribute to apply a consistent format to the text The cfformitem type html tag lets you insert formatted text and images in the form You can include ba...

Page 774: ...font color FF0000 size 4 face serif This form has formatted text including font b br textformat blockindent 20 leading 2 li colored text li li i italic and bold text i li li a bulleted list in an inde...

Page 775: ...ical form group the controls inside the included cfformgroup tag do not align with other controls in the vertical group hbox Arranges groups of controls horizontally Does not apply a label Use this at...

Page 776: ...me pets label Cats value Cats cfformgroup cfformgroup Group the fruit selector box contents aligned vertically cfformgroup type VBox height 130 cfformitem type text height 20 Fruits cfformitem cfformg...

Page 777: ...pecify any height or width attributes on individual tags These values must be in pixels 4 Repeat step 3 for various tags and possibly step 2 until your form has a pleasing appearance Repeating Flash f...

Page 778: ...flash height 220 width 450 cfselect label select a teacher name sel1 query q1 value id display firstname width 100 cfformgroup type repeater query q1 cfformgroup type horizontal label name cfinput ty...

Page 779: ...ars increase the cfform tag height attribute to 310 and the tabnavigator tag height attribute to 260 cfif IsDefined Form fieldnames cfdump var form label form scope br br cfif br cfform name myform he...

Page 780: ...bel Cats value Cats cfformgroup cfformgroup Group the fruit selector box contents aligned vertically cfformgroup type VBox height 130 cfformitem type text height 20 Fruits cfformitem cfformgroup type...

Page 781: ...the individual values in the array as in myTree selectedItems 1 data The selectedItems array exists only if the user selects multiple items otherwise it is undefined You can use ActionScript expressio...

Page 782: ...eristics using CSS syntax You can specify a style attribute in the following tags cfform cfformgroup cfcalendar cfformitem types hrule and vrule cfgrid cfinput cfselect cftextarea cftree The attribute...

Page 783: ...tyles support only the hexadecimal color format Some controls accept multiple colors For example the tree control s depthColors style property can use a different background color for each level in th...

Page 784: ...ld controls inherit the background color and font settings cfformgroup type Panel label Contact Information style marginTop 20 marginBottom 20 fontSize 14 fontStyle italic headerColors FFFF00 999900 b...

Page 785: ...on writing ActionScript is not provided For details on ActionScript and how you can use it see the Flash ActionScript 2 0 documentation including the documents available in the Flash and Flex sections...

Page 786: ...oldFusion creates if you specify insert yes and delete yes in the cfgrid tag but they allow you to specify you own button text and placement This example puts the buttons on the side of the grid inste...

Page 787: ...en elements This tag does not require recompiling when the number of elements changes It does have a processing overhead that increases with the number of loops and elements however so for large data...

Page 788: ...ific style or appearance ColdFusion forms and XForms ColdFusion skinnable forms conform to and extend the W3C XForms specification This specification provides an XML syntax for defining interactive fo...

Page 789: ...ldFusion uses a default skin If you specify skin none ColdFusion performs the first step but omits the remaining steps Your application must handle the XML version of the form as needed This technique...

Page 790: ...ontainer and its contents are children containers and controls Each cfformgroup tag defines a container that organizes its child elements The specific tags and attributes that you use in your form dep...

Page 791: ...such as strong p ul or li and their attributes For example the following text from the Example a simple skinnable form section shows how you could use a cfformitem tag to insert descriptive text in a...

Page 792: ...ormat xml skin basiccss width 400 preservedata Yes cfformgroup type fieldset label Contact Information cfformgroup type vertical cfformgroup type horizontal label Name cfinput type text size 20 name f...

Page 793: ...orizontal cfinput type submit name submit style width 80 value Tell Us cfinput type reset name reset style width 80 value Clear Fields cfformgroup cfform ColdFusion XML format The XML generated from a...

Page 794: ...ents and their children One xf instance element One xf submission element One xf bind element for each form control that can submit data xf instance element The XForms xf instance element contains inf...

Page 795: ...page 783 xf submission action _MyStuff phase1 forms XForms FrameExamples Figure1 cfm method post xf bind elements The xf bind elements provide information about the input control behavior including t...

Page 796: ...a cf validate element Data validation specification Has one attribute name and body text Each cf validate element can have multiple cf argument children corresponding to the validation related CFML t...

Page 797: ...ension xf bind xf bind id satisfaction nodeset xf model xf instance cf data satisfaction required false xf extension cf attribute name type SELECT cf attribute cf attribute name onerror _CF_onError cf...

Page 798: ...standard XForms control element can represent has the following general structure xf tagname bind bindid id bindid xf label label xf label xf extension cf attribute name type controltype cf attribute...

Page 799: ...so shows the use of a cfformgroup tag to arrange and label the radio button group CFML cfformgroup type horizontal label Accept cfinput type Radio name YesNo value Yes checked cfinput type Radio name...

Page 800: ...item xf item xf label No xf label xf value No xf value xf extension xf item xf choices xf select1 xf group cfgrid tags ColdFusion represents a cfgrid tag using the cf grid XML tag This tag has four at...

Page 801: ...ibute1 value columns rows row column1Name row1Column1Value column1Name column2Name row1Column2Value column2Name row row column1Name row2Column1Value column1Name column2Name row2Column2Value column2Nam...

Page 802: ...gt notsupported picturebar false picturebar insertbutton insert insertbutton deletebutton delete deletebutton sortAscendingButton SortAsc sortAscendingButton sortDescendingButton SortDesc sortDescendi...

Page 803: ...Development parent Divisions img folder cftree cfform XML The following code shows only the XML that is related to the tree appearance cf tree format xml id tree1 metadata fontWeight align lookAndFeel...

Page 804: ...the body text in a CDATA section The following example shows two cformitem tags and the resulting XML CFML cfformitem name text1 type text style color green Please tell us a little about yourself and...

Page 805: ...on email cf attribute xf extension xf input xf output CDATA b We value your input b br em Please tell us a little about yourself and your thoughts em xf extension xf output xf group appearance vertica...

Page 806: ...ogramming General information on writing XSLT transformations or CSS styles is not provided here However information about the following areas is provided How ColdFusion passes form attribute values t...

Page 807: ...nd multiple base skins share the files The following table describes the XSL files which are located in the cf_webroot x Format Location cfform format xml skin basic Searches for XML CSS in the defaul...

Page 808: ...vertical form groups You can add custom cfformgroup and cfformitemtype attributes by including additional XSL files Extending basic xsl cfformgroup and cfformitem support The following procedure desc...

Page 809: ...f web technologies for creating interactive web applications Ajax applications typically combine HTML and CSS for formatting and displaying information JavaScript for client side dynamic scripting Asy...

Page 810: ...res The tags and tag attribute combinations can be divided into the following categories Container tags that lay out or display contents File management tags that handle files Forms tags that dynamica...

Page 811: ...ayout cfpod and cfwindow controls Some of the data interaction features include the HTML cfgrid control the cfmenu control and dynamic autosuggest lists for text input controls Most display layout and...

Page 812: ...ntial flexibility in dynamically populating the page contents The cfdiv tag is also useful if you want a form to submit asynchronously That is whether or not you use a bind expression to populate the...

Page 813: ...p any space that other regions do not use You can also dynamically show or hide individual regions or let users collapse expand or close regions As a tabbed display where selecting a tab changes the d...

Page 814: ...ting tabs via JavaScript br a href onClick ColdFusion Layout selectTab mainTab tab1 return false Click here to select tab 1 a br a href onClick ColdFusion Layout selectTab mainTab tab2 return false Cl...

Page 815: ...ayout areas The layout has a light pink background color and the layout areas have three pixel wide red borders cflayout name layout1 type tab style background color FFCCCC cflayoutarea title area1 st...

Page 816: ...ts feed would go here cfpod cflayoutarea cflayoutarea position right size 302 cfpod width 300 height 20 name thetime title The Weather source podweather cfm headerstyle background color DDAADD font st...

Page 817: ...calling the ColdFusion Window hide function You can use the ColdFusion Window onShow and ColdFusion Window onhide functions to specify JavaScript functions to run when a window shows or hides The foll...

Page 818: ...ng contents cfoutput p This content was loaded into window 2 from a URL br p cfoutput Use the window show and hide events You can use the onShow and onHide events that are triggered each time a window...

Page 819: ...ue script head The body tag onLoad event calls the window show hide initializer function body onLoad initWindow cfwindow name testWindow initshow true title test window closable true Window contents c...

Page 820: ..._body technique to simpler use cases The following example shows how you can use various techniques to change container contents It consists of a main page and a second windowsource cfm page with text...

Page 821: ...windowsource cfm The callback handler puts its output in the following div block div id callback div Using menus and toolbars The cfmenu and cfmenuitem tags let you create vertical menus and horizonta...

Page 822: ...ript selected File gt Open gt Template cfmenuitem divider true cfmenuitem display CSS href javascript selected File gt Open gt CSS cfmenuitem cfmenuitem display Close href javascript selected File gt...

Page 823: ...ipts ajax resources yui directory For more information about these styles see the Yahoo User Interface Library menu documentation Uploading files The cffileupload tag lets you select multiple files an...

Page 824: ...upload cfcatch type any cfset str STATUS 500 cfset str MESSAGE Error occurred while uploading the file cfoutput serializeJSON str cfoutput cfcatch cftry If the user tries to upload a file already pre...

Page 825: ...t require a Java applet or Flash The cftextarea control has a rich text editor option The text editor is configurable The cfinput tag supports a datefield type with an Ajax based pop up calendar from...

Page 826: ...function that you call after the SetForm function This way you can pass the current values of fields in a form to a CFC function which can then do the necessary processing and return a result When yo...

Page 827: ...oLogin function displays a message in the login window title bar The following example shows the setForm cfm application html head script type text javascript function doLogin Create the Ajax proxy in...

Page 828: ...name username type string cfargument name password type string cfset var validated false Ensure that attempts to authenticate start with new credentials cflogout cflogin cfif arguments username is use...

Page 829: ...lback text function errorHandler code msg alert Error code msg script head body cfform name myform cfinput name mytext1 br cfinput name mytext2 cfform a href javascript submitForm Submit form a body h...

Page 830: ...g a bind attribute with a bind expression that calls a CFC or JavaScript function or a URL The bind expression uses bind parameters to specify dynamic information provided by the grid and the values o...

Page 831: ...e use the queryConvertForGrid function to convert a query into a structure and then use the serializeJSON function to convert the structure into a JSON representation If you manually create a JavaScri...

Page 832: ...nt name page cfargument name pageSize cfargument name gridsortcolumn cfargument name gridsortdirection cfquery name team datasource cfdocexamples SELECT Emp_ID FirstName EMail FROM Employees cfif grid...

Page 833: ...econd control load themselves at the onLoad page event Then the first control loads itself again in response to a change event from the second control when that control completes loading So the first...

Page 834: ...t in a CFC or URL returning an HTTP error status The method must take two parameters the HTTP error code and a text message that describes the error The following example shows an onError handler func...

Page 835: ...the getData function in Dynamically filling form data on page 825 This example shows the editData function in the CFC cffunction name editData access remote output false cfargument name gridaction cf...

Page 836: ...emps active Y 1 cfset querysetcell emps firstname Doherty 2 cfset querysetcell emps department Finance 2 cfset querysetcell emps salary 120000 2 cfset querysetcell emps active Yes 2 cfset querysetcell...

Page 837: ...m name form01 cfgrid format html insert yes insertButton Add Row name grid01 selectmode edit width 600 collapsible true title Employees autowidth yes query emps sort yes groupField active cfgridcolumn...

Page 838: ...Name header FirstName cfgridcolumn name Department header Department cfgridcolumn name Salary display true header Salary type numeric values 1000000 1200000 valuesdisplay 1000000 1200000 cfgridcolumn...

Page 839: ...generates an event that the tree is listening for the tree is refreshed For example if the tree uses a bind expression that includes a select box as a bind parameter the tree collapses to the root no...

Page 840: ...lowercase letters for the field names JavaScript is case sensitive so the JavaScript function must match the uppercase field names If you use a URL to get the tree items from a CFML page you can use...

Page 841: ...a expansion indicator in the tree leaf node tree entries and from attempting to expand the node The following example shows how you use the LEAFNODE field Example 2 a more complex tree with leaf node...

Page 842: ...s artgallery img var imgDiv document getElementById image imgDiv innerHTML imgURL script head body The form uses a table to place the tree and the image cfform name ex1 action ex1 cfm method post tabl...

Page 843: ...oop If the value argument has one list entry it is a media type Get the artists for the media type cfelseif listLen arguments value is 1 cfquery name q datasource variables dsn SELECT artists lastname...

Page 844: ...in the bind parameter it is ignored Tree JavaScript functions You can use the following JavaScript functions to manage an HTML tree For more information see the ColdFusion Tree getTreeObject and Cold...

Page 845: ...fy the toolbar name in the toolbar attribute Create custom toolbars in the fckconfig js file The editor has a single toolbar consisting of a set of active icons and fields and separators The toolbar a...

Page 846: ...s the text Each Attribute child element defines the name and value of an attribute of the HTML tag For example the following definition creates a style that makes the selected text bold and underlined...

Page 847: ...l buttons Place all other images used by the skin that are specified in the CSS files in the images subfolder The most common way of customizing the skin is to change the fck_editor css and fck_dialog...

Page 848: ...st overflow visible br cfform name mycfform1 div style float left Date 1 div cfinput type datefield name mydate1 br br br div style float left Date 2 div cfinput type datefield name mydate2 value 15 1...

Page 849: ...lay attribute to specify the minimum time between function invocations as the user types This limits the number of requests that are sent to the server If you use a dynamic list the input field has an...

Page 850: ...nter A or J in the First Name box you get a name suggestion The following example shows the application html xmlns http www w3 org 1999 xhtml head head body cfform Last Name br cfinput type text name...

Page 851: ...that match the last name and the typed characters SELECT FIRSTNAME FROM Employees WHERE LASTNAME cfqueryparam value lastName cfsqltype cf_sql_varchar AND FIRSTNAME LIKE cfqueryparam value suggestvalue...

Page 852: ...r sliderChange function slider value get slider name slidername slider getId get slider value currValue ColdFusion Slider getValue slidername set a new slider value newValue parseInt currValue 10 Cold...

Page 853: ...ample address or latitude and longitude The marker window can be populated with static or dynamic content Populating data using static content To manually populate data in the marker window specify th...

Page 854: ...mapname cfmaplatitude cfmaplongitude cfmapaddress showmarkerwindow true cfmapitem name m1 address Taj Mahal Agra India tip Taj Mahal Agra India cfmapitem name m2 latitude 40 46 longitude 117 05 showma...

Page 855: ...getMapData function cfmapname cfmaplatitude cfmaplongitude cfmapaddress var msg msg msg Map Name cfmapname br msg msg Latitude longitude cfmaplatitude cfmaplongitude br msg msg Address cfmapaddress b...

Page 856: ...te a map provide a valid Google map API key and specify the latitude and longitude of the location or the address of the location The Google map API key can be specified in the following ways Using th...

Page 857: ...rmines the indicator length The following CFM code shows how to use a CFC bind expression cfajaxproxy cfc pbar jsclassname pbar head script var utils new pbar var count 0 var init function document ge...

Page 858: ...nd message components of the progressbar cfset data status session count 0 1 message session count 10 cfreturn data cffunction cfcomponent The following CFM code explains how to use the URL bind expre...

Page 859: ...back via URL binds must use SerializeJSON cfoutput SerializeJSON data cfoutput The following CFM code has the JavaScript bind expression head script var count 0 var init function document getElementBy...

Page 860: ...e ColdFusion ProgressBar hide pBar script head cfform div id cfpbLabel style display none Saving File div cfprogressbar name pBar duration 10000 autodisplay false onComplete hideProgessBar width 400 c...

Page 861: ...atus 100 ColdFusion ProgressBar updateStatus pBar status message utils sleep 1000 hideProgessBar script head cfform div id cfpbLabel style display none Saving File div cfprogressbar name pBar autodisp...

Page 862: ...Yes Click Yes to continue labelNo No x 100 y 200 This example illustrates usage of the Confirm dialog in YesNoCancel mode cfmessagebox type confirm name msgbox2 title Save File message Do you want to...

Page 863: ...eatures on page 804 About ColdFusion Ajax data and development features Ajax Asynchronous JavaScript and XML is a set of web technologies for creating interactive web applications Ajax applications ty...

Page 864: ...pry data sets Applications that use Spry framework elements such as dynamic regions use this tag to populate the Spry elements with information based on ColdFusion control input This feature lets you...

Page 865: ...values as parameters to a CFC function a JavaScript function or an HTTP request and uses the function or request response to update the page Use the following as the data source for a bind expression...

Page 866: ...and the city control is in the inputForm form If a bind attribute specifies a page that defines JavaScript functions the function definitions on that page must have the following format functionName...

Page 867: ...r radio button specify an HTML label tag for each button or check box and use the id value in the for attribute in this case users select items by clicking the label not just the button or box If a cf...

Page 868: ...e as the event This is useful for example if a bind expression uses multiple bind parameters binding to different form fields and you want the bind expression to trigger changes only when one of the f...

Page 869: ...the following methods to access CFCs logical mappings defined in the ColdFusion Administrator per app mappings defined in Application cfc imports using cfimport import Usage The following code shows t...

Page 870: ...ql execute return QueryConvertForGrid rs1 getResult page pageSize remote any function editEmployees gridaction gridrow gridchanged writelog edit employee info cfscript cfcomponent Employee cfm cfform...

Page 871: ...Oranges label for pickers2 Oranges label cfinput id pickers3 name pickone type radio value Mangoes label for pickers3 Mangoes label br cfinput name pickone selected bind pickone br br Pick as many as...

Page 872: ...n the documentation for ColdFusion Ajax features use binding including more complex forms of binding Using the cfajaxproxy tag to bind to display controls The cfajaxproxy tag with a bind attribute mak...

Page 873: ...on two things must happen The application must call a mycfc deleteButton CFC function to delete the row from the database The grid must update to remove the deleted row When the user edits the grid co...

Page 874: ...avaScript proxy for a CFC and its functions You then call the proxy functions in client JavaScript code to access the server side CFC functions Use the cfsprydataset tag to dynamically populate a Spry...

Page 875: ...arts with the cfajaxproxy tag or tags and the remainder of the page consists of the HTML and JavaScript required to control the display and perform the page logic on the client Note Because JavaScript...

Page 876: ...ield values of the specified form to the CFC function In the CFC function Arguments scope the argument names are the form control ID attributes or by default the name attributes and the argument value...

Page 877: ...var getEmployees function Create an instance of the proxy var e new emp If you set a callback handler for the proxy the proxy s calls are asynchronous e setCallbackHandler populateEmployees e setErro...

Page 878: ...r edepartment employee DATA 0 5 with document simpleAJAX empData innerHTML span style width 100px Employee Id span font color green span align left eId font span br span style width 100px First Name s...

Page 879: ...ployees cfif empid neq 0 where Emp_ID empid cfif Cfquery cfreturn qryEmp cffunction cfcomponent Using Spry with ColdFusion ColdFusion provides support for mixing native ColdFusion elements and Spry el...

Page 880: ...n For more information see the cfsprydataset tag in the CFML Reference Spry data set example This example has the following behavior 1 It uses a CFC function directly to populate a Spry XML data set f...

Page 881: ...hat lists the filters Call the GridDataManager CFC getFilter method directly from a Spry XMLDataSet function because no binding is needed script var dsFilters new Spry Data XMLDataSet GridDataManager...

Page 882: ...ata method Pass the method the value of the name field of the selected item in the dsfilters Spry dynamic region cfgrid name bookgrid format html bind CfC GridDataManager getData page cfgridpage pageS...

Page 883: ...equired yes cfargument name sortDir required yes cfargument name filter required no cfquery name books datasource cfbookclub select TITLE GENRE from BOOKS cfif isDefined arguments filter AND arguments...

Page 884: ...Filters xml file xml version 1 0 encoding iso 8859 1 filters filter filterid 1 filterid name name description No Filter description filter filter filterid 2 filterid name Fiction name description Loo...

Page 885: ...g scriptsrc attribute to specify the source directory This tag overrides the setting in the administrator and does not affect the files used for standard cfform features The directory you specify must...

Page 886: ...ML or JSON As a general rule ColdFusion automatically handles all necessary serialization and deserialization when you use ColdFusion Ajax features The proxies that you create with the cfajaxproxy tag...

Page 887: ...h user data you get the user names in your JavaScript by specifying values such as userData firstName 0 and userData lastName 0 For more information see the SerializeJSON function in the CFML Referenc...

Page 888: ...totalResultsAvailable Entries br Here are the first myJSON ResultSet totalResultsReturned p cfloop index i from 1 to myJSON ResultSet totalResultsReturned h3 a href myJSON ResultSet Result i URL myJSO...

Page 889: ...rmation option on the Debug Output Settings page Make sure that the IP address of the system where you do the debugging is included on the ColdFusion Administrator Debugging Logging Debugging IP List...

Page 890: ...ColdFusion Log error b Invalid value b br arg A Pod A Standard ColdFusion logging messages ColdFusion automatically logs messages in the following categories Ajax programming rules and techniques The...

Page 891: ...xceptions to this rule include the following You can use the same name attribute for all options in a radio button group Bind expressions get information about the selected button You can use the same...

Page 892: ...use the cffunction tag to set the prefix As a general rule use one of these techniques for any CFC or CFML page that returns sensitive data such as credit card numbers When you use any of these techn...

Page 893: ...ogged in when it displays You can use the AjaxOnLoad function to specify a JavaScript function that determines the login status and pops up the window only if necessary Use the following ColdFusion Ja...

Page 894: ...nOffice OpenOffice is an open source office software that supports word processing spreadsheets presentations and more OpenOffice stores data in an international open standard format See http www open...

Page 895: ...information about the people presenting the slides You use the cfpresentation tag to convert a PowerPoint presentation to an Adobe Connect presentation or HTML Browsers like Internet Explorer Mozilla...

Page 896: ...Q1 Sales Figures h3 cfchart format png showborder yes chartheight 250 chartwidth 300 pieslicestyle sliced cfchartseries type pie cfchartdata item Europe value 9 cfchartdata item Asia value 20 cfchart...

Page 897: ...ng variable Add a sheet to an existing XLS file Use the spreadsheet functions to manipulate rows and columns in a spreadsheet and the data in the rows and columns You can also specify and get comments...

Page 898: ...report1 cfoutput The following example uses data from a query and writes it to a single sheet in the spreadsheet file SingleSheet1 xls cfquery name excelquery datasource cfdocexamples SELECT PARKNAME...

Page 899: ...L to the WSDL Web Services Description Language of the web service that is loaded For information about the supported SharePoint features see the CFML Reference Using cfsharepoint Sharepoint integrati...

Page 900: ...1 bytes myimage filename bird jpg fOverwriteifexist true Rotates the picture downloaded from the SharePoint server cfsharepoint name result1 action download login login params strListName getpics strf...

Page 901: ...this case you see the following error message coldfusion jsp JavaCompiler s UnknownCompiler Unable to run the internal Java compiler java lang NoClassDefFoundError javax tools StandardJavaFileManager...

Page 902: ...e 1 Navigate to the web page on the SharePoint server where you want the Web Part to be accessible 2 In the Web Part page click Site Actions Site Settings 3 In the Site Settings page click Galleries W...

Page 903: ...ity and Additional Settings Manage Web Part Gallery 2 Click New in the toolbar in the Web Part Gallery The New Web Parts List appears 3 Select the CFSSOwebpart dwp Web Part and click Populate Gallery...

Page 904: ...portal can access portlets deployed on a remote ColdFusion server instance Prerequisites Before you start developing ColdFusion portlets you must Install JDK 1 5 x For JSR 168 install bundled version...

Page 905: ...the WEB INF folder of ColdFusion web root The portlet xml file looks similar to the following xml version 1 0 encoding UTF 8 portlet app xmlns http java sun com xml ns portlet portlet app_1_0 xsd xml...

Page 906: ...port 8080 so launch the server using the URL http matching_IP port portal For example http 127 0 0 1 8080 portal 6 Log in to the portal by clicking the login link in the upper right corner The defaul...

Page 907: ...5 2010 Adding instance of CFHelloPortlet 12 Click the Portal Objects tab 13 Create a new portal page by specifying the portal name in the Create a portal named box Creating a portal 14 Select the crea...

Page 908: ...ION 9 APPLICATIONS ColdFusion Portlets Last updated 8 5 2010 Managing created portal 16 From the Portlet instance associated with this Window list select the portlet instance you created in step 10 Po...

Page 909: ...te the ColdFusion HelloPortlet cfc as described in step 1 of Build a portlet for a local server on page 899 2 Save the HelloPortlet cfc file in the following directory ColdFusion_webroot portlets hell...

Page 910: ...oducer producer WSDL After clicking Refresh Save the system prompts you to provide the consumerRole registration property Use the string public and click Update Properties If the BEA WSRP Producer doe...

Page 911: ...object User code goes here cffunction doEdit Helper method to serve up the EDIT mode cffunction name doEdit returntype void output true cfargument name renderRequest type any required true hint A jav...

Page 912: ...to the CFC called getTitle as follows cffunction name getTitle returntype string output false access public cfargument name renderRequest type any required true hint A javax portlet RenderRequest java...

Page 913: ...an action request cfargument name actionRequest type any required true hint A javax portlet ActionRequest java object cfargument name actionResponse type any required true hint A javax portlet Action...

Page 914: ...st and only after that it would render any request Some of the capabilities of JSR 286 include the following Publishing and Processing Events To define an event you would have to declare it in portlet...

Page 915: ...me of the event object and the type of object defined in portlet xml Following is an example of processAction method cffunction name processAction returntype void access public output false hint Calle...

Page 916: ...tion EventReceivingPortletEvents ArrayNew 1 cfif cfset ArrayAppend application EventReceivingPortletEvents e cfcatch type any cfcatch cftry cffunction Using filters Filter definition and mapping in po...

Page 917: ...name doResourceFilter returntype void cfargument name resourceRequest cfargument name resourceResponse cfargument name filterChain cflog file portlet filter type information text doResourceFilter invo...

Page 918: ...Portlets Last updated 8 5 2010 5 Go to repackage the WAR file using jar cvf cfusion war 6 Deploy it through WebSphere Portal Server administrator console The portlets would be visible present in port...

Page 919: ...Format XFDF file format Forms created in LiveCycle use the XML Forms Architecture XFA format introduced in Acrobat and Adobe Reader 6 For examples see Populating a PDF form with XML data on page 915...

Page 920: ...tput to an XDP file on page 920 Note If you do not specify a destination the populate action displays the populated PDF form in a browser window Task Tags and actions Populate a PDF form with XML data...

Page 921: ...m Subform1 SSN Subform1 form1 xfa Prefilling PDF form fields ColdFusion lets you prefill individual form fields with data extracted from a data source For example you can run a query to extract return...

Page 922: ...ng cfpdfsubform cfpdfform Note In dynamic forms created in LiveCycle forms forms saved as Dynamic PDF Form Files in LiveCycle Designer you have the option to mark how many times a record is repeated T...

Page 923: ...cfpdfsubform tags cfpdfform source c grantForm pdf destination c employeeid123 pdf action populate cfpdfsubform name form1 cfpdfsubform name grantapplication cfpdfsubform name page1 cfpdfformparam na...

Page 924: ...ample shows cfdocument format pdf cfdocumentitem type header font size 1 This is the Header font cfdocumentitem cfdocumentitem type footer font size 1 This is the Footer font cfdocumentitem cfdocument...

Page 925: ...binary format not XML format Extracting data from a PDF submission Use the following code to extract data from a PDF submission and write it to a structure called fields The following code reads the s...

Page 926: ...ep the blank PDF form used as the template you can use the populate action to regenerate the PDF file For more information on populating forms see Populating a PDF form with XML data on page 915 Extra...

Page 927: ...he following code shows cfquery name updateEmpInfo datasource cfdocexamples UPDATE EMPLOYEES SET FIRSTNAME FORM1 SUBFORM HEADER TXTFIRSTNAME LASTNAME FORM1 SUBFORM HEADER TXTLASTNAME DEPARTMENT FORM1...

Page 928: ...rmation When the employee completes the form and clicks the PDF Submit button the entire PDF form with the data is submitted to a second processing page where ColdFusion writes the completed form to a...

Page 929: ...orm tag to match the structure of the form in ColdFusion Likewise the field names in the cfpdfformparam tags must match the field names in the PDF form If the form structures and field names do not ma...

Page 930: ...database The form was created in LiveCycle Designer On the ColdFusion login page an employee enters a user name and password The following code creates a simple form for entering a user name and passw...

Page 931: ...employee updates the information in the form and clicks the HTTP post Submit button Acrobat sends the form data but not the form itself to a second ColdFusion processing page Note In LiveCycle Designe...

Page 932: ...before and after the interactive PDF form cfquery name getEmpInfo datasource cfdocexamples SELECT FROM EMPLOYEES WHERE EMAIL cfqueryparam value FORM username cfquery The following code creates a PDF...

Page 933: ...xisting supply request The user has the option to submit the completed form as an e mail attachment supplyReq1 cfm The following code prefills fields in a blank form in LiveCycle and writes the prefil...

Page 934: ...izes the display based on field values extracted from the PDF form p cfoutput fields form1 txtRequester cfoutput p p Your changes have been recorded for supply request cfoutput fields form1 txtRequest...

Page 935: ...tag The cfpdfparam tag gives you more control over which files are included in the output file for example you can merge pages from multiple files in different directories Action Description addWater...

Page 936: ...action processddx with the TableOfContents DDX element cfpdf action extracttext can also be used Add automatic page numbers to a PDF document cfpdf action processddx with the _PageNumber and _LastPage...

Page 937: ...isplays the image in the background of each page in the output file In the following example ColdFusion displays the watermark in the foreground offset 100 pixels from the left margin of the page and...

Page 938: ...llery jeff01 jpg br cfinput type radio name art value cfdocs images artgallery jeff01 jpg Celebration td td img src cfdocs images artgallery paul01 jpg br cfinput type radio name art value cfdocs imag...

Page 939: ...ted image as a watermark specify the image variable as the following example shows Verify that an image file exists and is in a valid format cfif IsImageFile cfdocs images artgallery form art Use the...

Page 940: ...the copyFrom attribute to create a watermark from the first page of a PDF file and apply it to another PDF document In the following example ColdFusion creates a watermark from the first page of imag...

Page 941: ...ever it does not discriminate between dumb encodings like LZW and encodings like flate so only unencoded streams get flate encoded Example cfpdf action write source inputFiles Source pdf destination o...

Page 942: ...can scale a page specify the position and rotation values for pages in a PDF document using the transform action This action has four attributes that define the size hscale vscale position position an...

Page 943: ...or add passwords For a list of permissions that an owner can set for PDF documents see cfpdf in the CFML Reference Except for all or none owners can specify a comma separated list of permissions on a...

Page 944: ...xKeys StructNew cfset taxKeys keywords Sole Proprietor Partnership S Corporation cfpdf action setInfo source taxes p535 pdf info taxKeys destination taxes p535 pdf overwrite yes When you use the setIn...

Page 945: ...ion wwwroot lion Chap2 pdf destination twoChaps pdf overwrite yes For more control over which files are added to the merged document use the cfpdfparam tag with the cfpdf tag The cfpdfparam tag merges...

Page 946: ...eated in Acrobat as a source file for merge action of the cfpdf tag ColdFusion automatically flattens the form and removes data from the form fields if the fields are filled in ColdFusion does not sup...

Page 947: ...ributes for the thumbnail action hires You can set this attribute to true to extract high resolution images from the page If a document contains high resolution images and you want to retain the resol...

Page 948: ...Cycle Assembler is a server based application that processes DDX a declarative markup language used to define PDF output files The processddx action lets you process DDX instructions without installin...

Page 949: ...ile merge ddx inputfiles inputStruct outputfiles outputStruct name myBook The name attribute creates a variable that you can use to test the success or failure of the action If the action is successfu...

Page 950: ...file cfset outputStruct StructNew cfset outputStruct Out1 Book pdf This code processes the DDX instructions and generates the book cfpdf action processddx ddxfile makeBook ddx inputfiles inputStruct...

Page 951: ...r Footer PDF PDF DDX In this example the Header and Footer elements apply only to Doc2 because they are contained within that PDF source start and end tags they do not apply to the table of contents o...

Page 952: ...ng the styleReference attribute of the Header element as the following example shows xml version 1 0 encoding UTF 8 DDX xmlns http ns adobe com DDX 1 0 xmlns xsi http www w3 org 2001 XMLSchema instanc...

Page 953: ...DDX instructions to create a book on page 954 Setting the initial view of a PDF document To set the initial view of a PDF document use the InitialViewProfile DDX element Setting the initial view dete...

Page 954: ...ance xsi schemaLocation http ns adobe com DDX 1 0 coldfusion_ddx xsd PDF result Out1 Watermark rotation 30 opacity 65 StyledText p font size 50pt font weight bold color lightgray font Arial DRAFT p St...

Page 955: ...t Background PDF PDF source Doc4 PDF DDX For more information on using DDX instructions to create watermarks see the Adobe LiveCycle Assembler Document Description XML Reference Extracting text from a...

Page 956: ...documents into one output file xml version 1 0 encoding UTF 8 DDX xmlns http ns adobe com DDX 1 0 xmlns xsi http www w3 org 2001 XMLSchema instance xsi schemaLocation http ns adobe com DDX 1 0 coldfu...

Page 957: ...ue 2 cfpdfform Application examples The following examples show you how to use the cfpdf tag to perform PDF document operations in simple applications Merging documents based on a keyword search The f...

Page 958: ...The merge action assembles the files in the list into an output PDF file Create a variable for the business type selected from the form cfset bizType form businessType Create a variable for the path o...

Page 959: ...coding UTF 8 DDX xmlns http ns adobe com DDX 1 0 xmlns xsi http www w3 org 2001 XMLSchema instance xsi schemaLocation http ns adobe com DDX 1 0 coldfusion_ddx xsd PDF result Out1 PDF source Doc0 Table...

Page 960: ...watermark to a form created in Acrobat The following example shows how to prefill an interactive Acrobat tax form and apply a text string watermark to the completed form that the user posted Specific...

Page 961: ...hod post table tr td User name td td cfinput type text name username required yes message A user name is required td tr tr td SSN td td cfinput type text name SS1 maxLength 3 size 3 required yes mask...

Page 962: ...pass the first name last name and the three parts of the SSN to the tax form Also create a hidden field for the filerID variable cfinput type hidden name FirstName value getEmpInfo FirstName cfinput t...

Page 963: ...form Phone cfpdfformparam name f1_003 0 value form SS1 cfpdfformparam name f1_004 0 value form SS2 cfpdfformparam name f1_005 0 value form SS3 cfpdfformparam name filerID value form taxFiler _1040ez c...

Page 964: ...es and searches convert images from one format to another and write images to the hard drive About ColdFusion images ColdFusion lets you create and manipulate images dynamically With ColdFusion you ca...

Page 965: ...a Base64 string cfimage tag or the ImageWriteBase64 function Create a ColdFusion image from a Base64 string ImageReadBase64 function Insert a ColdFusion image as a Binary Large Object Bitmap BLOB in a...

Page 966: ...mage IsImageFile GetReadableImageFormats GetWriteableImageFormats Retrieving image information ImageGetEXIFTag ImageGetHeight ImageGetIPTCTag ImageGetWidth ImageInfo Reading writing and converting ima...

Page 967: ...nction which writes the image to a new file cfset myImage ImageNew cfdocs images artgallery jeff01 jpg cfset ImageWrite myImage myImageTest png The following code produces the same result cfimage sour...

Page 968: ...tag to write the images to PNG files cfimage source GetBLOBs Image destination employeeImage i png action write img src employeeImage i png td tr cfoutput table The following example shows how to use...

Page 969: ...he ImageCopy function to copy a rectangular area of an existing image and generate a new ColdFusion image from it You can paste the new ColdFusion image onto another image or write it to a file as the...

Page 970: ...ge tag and the ImageNew function to duplicate images as the following example shows Use the cfimage tag to create a ColdFusion image myImage and make a copy of it myImageCopy cfimage source cfdocs ima...

Page 971: ...JPEG file cfimage source aiden01 jpg name myImage Use the cfquery tag to insert the ColdFusion image as a BLOB in the database cfquery name InsertBlobImage datasource myBlobData INSERT into EMPLOYEES...

Page 972: ...u can convert a JPEG file to a lower quality image by using the write action of the cfimage tag Specify a value between 0 low and 1 high for the quality attribute as the following example shows cfimag...

Page 973: ...source image are tiled to create the border cfset myImage ImageNew cfdocs images artgallery jeff03 jpg cfset ImageAddBorder myImage 20 wrap cfset ImageWrite myImage testMyImage jpg img src testMyImag...

Page 974: ...image shows three CAPTCHA images with low medium and high levels of difficulty respectively Using the ImageDrawText function To create a text image by using the ImageDrawText function specify the text...

Page 975: ...sent the width and height of the shape in pixels For a line the values represent the x and y coordinates of the start point and end point of the line respectively To create filled shapes set the fille...

Page 976: ...lines in the image cfset ImageSetDrawingStroke myImage attr cfset ImageDrawRect myImage 40 40 100 100 Set the drawing color to red for all subsequent drawing functions cfset ImageSetDrawingColor myIm...

Page 977: ...k cfset myImage ImageNew http www google com images logo_sm gif cfset ImageResize myImage 50 Save the modified image to a file cfimage source myImage action write destination test_myImage jpeg overwri...

Page 978: ...idth is exactly 200 pixels and the height of the image is proportional to the width This example shows how to resizes an image so that it is 200 pixels wide while maintaining the aspect ratio of the s...

Page 979: ...e drawing transparency to 75 cfset ImageSetDrawingTransparency myImage 75 Create a ColdFusion image from scratch cfset textImage ImageNew 150 140 Set the drawing color to white cfset ImageSetDrawingCo...

Page 980: ...ge myImage2 0 0 Save the combined image to a file cfimage source myImage action write destination test_watermark jpg overwrite yes Display the image in a browser img src test_watermark jpg Writing ima...

Page 981: ...d the image file cffile action upload fileField image destination thisDir result fileUpload nameconflict overwrite Determine whether the image file is saved cfif fileUpload fileWasSaved Determine whet...

Page 982: ...le action delete file fileUpload serverDirectory fileUpload serverFile cfoutput p The file you uploaded fileUpload clientFile was not a valid image p cfoutput cfif cfif cfif Generating a gallery of wa...

Page 983: ...artwork largeImage cfset myImage ImageNew cfdocs images artgallery artwork largeImage td valign top align center width 200 cfset xctr xctr 1 For artwork that has been sold display the text string SOL...

Page 984: ...K L M N P Q R S T U V W X Y Z cfset rndString Create a loop that builds the string from the random characters cfloop from 1 to stringLength index i cfset rndNum RandRange 1 listLen stringList cfset rn...

Page 985: ...the cfimage tag to create a ColdFusion image from the title selected from the list Use the ImageNew function to create three clones of the ColdFusion image Use the ImageSharpen function to change the...

Page 986: ...setting cfset ImageSharpen clone3 2 Create a form with a radio button for each selection The value of the hidden field is the relative path of the original image file p Please choose an image p table...

Page 987: ...destination c myImage jpg overwrite yes img src c myImage jpg Creating Charts and Graphs You can use the cfchart tag to display charts and graphs About charts The ability to display data in a chart o...

Page 988: ...fchart cfchartseries and cfchartdata tags in a ColdFusion page Using the chart wizard that is included with the ColdFusion Report Builder For more information see Creating Reports and Documents for Pr...

Page 989: ...you can specify using the cfchart cfchartseries and cfchartdata tags For information about using the Report Builder chart wizard see Creating Reports and Documents for Printing on page 1007 Charting...

Page 990: ...chart represents data from one row column coordinate in your result set A related group of data is called a chart series Because each bar dot line or slice represents the intersection of two axes craf...

Page 991: ...ar values The example in the following procedure analyzes the salary data in the cfdocexamples database using a query of queries and displays the data as a bar chart 1 Create a ColdFusion page with th...

Page 992: ...the page as chartdata cfm in the myapps directory under the web root directory For example the directory path in Windows could be C Inetpub wwwroot myapps 3 Return to your browser and enter the follow...

Page 993: ...se to get the Dept_Name and Salary for each employee Because the Dept_Name is in the Departmt table and the Salary is in the Employee table you need a table join in the WHERE clause You can use the ra...

Page 994: ...ub wwwroot myapps 4 Return to your browser and enter the following URL to view the chartqueryanddata cfm page http localhost myapps chartqueryanddata cfm Charting multiple data collections Sometimes y...

Page 995: ...re creates the chart in the previous figure which shows a bar chart with a line chart added to it In this example you chart the salary of permanent employees bar against contract employees line Note T...

Page 996: ...series cfchartseries type bar query DeptSalaries valueColumn AvgByDept itemColumn Dept_Name seriesColor gray paintStyle plain seriesLabel Dept Average Salaries cfchart 3 Save the file as chart2queries...

Page 997: ...end the chart to the user as a JPEG PNG or SWF file The SWF file is the default format All Size chartWidth chartHeight The width and height in pixels of the chart This size defines the entire chart ar...

Page 998: ...is number The xAxisTitle and yAxisTitle attributes specify the title for each axis All Border showBorder Use the showBorder attribute to draw a border around the chart The foregroundColor attribute sp...

Page 999: ...you specify the cfchartdataitem attribute whose values are treated as text By default the items are displayed in the order in which they are entered in the first chart series Area Bar Cone Curve Cylin...

Page 1000: ...hat of the first slice Subsequent slices are automatically colored based on the specified initial color or use the colorList attribute All Paint paintStyle Specifies the way color is applied to a data...

Page 1001: ...rt style file Note ColdFusion uses the same rules to look for the chart style XML files as it does for files included using the cfinclude tag For more information seecfinclude 8 Click Save The followi...

Page 1002: ...wXGridlines Frame isVGridVisible showYGridlines Frame isHGridVisible tipbgColor Popup background tipStyle Popup show on MouseOver show on MouseDown Disabled url Elements action Series action xAxisTitl...

Page 1003: ...in the following procedure adds a pie chart to the page 1 Open the chartdata cfm file in your editor 2 Edit the DeptSalaries query and the cfloop code so that it appears as follows Code Description s...

Page 1004: ...DeptSalaries SumByDept i Round DeptSalaries SumByDept i 1000 1000 cfset DeptSalaries AvgByDept i Round DeptSalaries AvgByDept i 1000 1000 cfloop 3 Add the following cfchart tag Pie chart from DeptSala...

Page 1005: ...tml tag Code Description SUM Salary AS SumByDept In the DeptSalaries query add a SUM aggregation function to get the sum of all salaries per department cfset DeptSalaries SumByDept i Round DeptSalari...

Page 1006: ...ry AS AvgByStart FROM GetSalaries GROUP BY StartDate cfquery Round average salaries to thousands cfloop index i from 1 to HireSalaries RecordCount cfset HireSalaries AvgByStart i Round HireSalaries Av...

Page 1007: ...f the chart has already been rendered If so ColdFusion loads the chart from the cache The following table describes the settings for the ColdFusion charting and graphing engine Code Description Employ...

Page 1008: ...as a SWF file both tips and drill down URLs work For more information on data drill down see Linking charts to URLs on page 1004 Write a chart to a variable and a file 1 Create a ColdFusion page with...

Page 1009: ...sers click the graph to open the page moreinfo cfm and pass all three values to the page you use the following URL url moreinfo cfm Series SERIESLABEL Item ITEMLABEL Value VALUE The variables are not...

Page 1010: ...tract FROM Departmt Employee WHERE Departmt Dept_Name URL Item AND Departmt Dept_ID Employee Dept_ID ORDER BY Employee LastName Employee Firstname cfquery html head title Employee Salary Details title...

Page 1011: ...the highlighted code and its function Code Description cfquery name GetSalaryDetails datasource cfdocexamples SELECT Departmt Dept_Name Employee FirstName Employee LastName Employee StartDate Employee...

Page 1012: ...ata_withJS cfm in the myapps directory under the web root directory 3 View the chartdata_withJS cfm page in your browser 4 Click the slices of the pie chart to display the pop up window Creating Repor...

Page 1013: ...creates an Excel spreadsheet Note The Excel report output format type provides limited support for the formatting options available in ColdFusion reporting Images and charts are not supported and num...

Page 1014: ...ery EmpList EmpList FirstName EmpList LastName LSCurrencyFormat EmpList Salary EmpList Contract br cfoutput cfdocument Creating sections headers and footers You can use the cfdocument and cfdocumentse...

Page 1015: ...cfdocumentsection tags The margin attributes override margins specified in previous sections or in the parent cfdocument tag If you specify margin attributes the unit attribute of the parent cfdocumen...

Page 1016: ...is scope contains the following variables currentpagenumber Displays the current page number totalpagecount Displays the total page count currentsectionpagenumber Displays the current section number t...

Page 1017: ...section cfdocumentsection name Conclusion h3 Conclusion h3 p The conclusion goes here p cfdocumentsection cfdocument The bookmarks appear in the bookmarks panel of the PDF document Using cfhttp to dis...

Page 1018: ...yption Use the encryption attribute to specify whether PDF output is encrypted Specify one of the following 128 bit 40 bit none User password Use the userpassword attribute to specify a password that...

Page 1019: ...ment Creating reports with Crystal Reports Windows only When running on Windows the cfreport tag also supports the execution of reports created using Crystal Reports version 9 or 10 Note When you inst...

Page 1020: ...ldFusion server as necessary The Report Builder stores report definition information in a ColdFusion Report CFR file This file contains field definitions formatting database SQL statements CFML and ot...

Page 1021: ...Wizard radio button the Report Builder runs the Report Creation Wizard which prompts you for information and automatically generates a complete report definition For more information on the Report Cr...

Page 1022: ...ides three panels that you use to place and format data elements in the workspace Properties panel Contains display and report characteristics for the selected field To display the Properties panel ch...

Page 1023: ...and advanced query mode Use this option when you use a ColdFusion query encapsulated in the report definition This option is also useful if the query comes from the cfdirectory cfldap or cfpop tags q...

Page 1024: ...a locale codes see the Sun website The ColdFusion install includes a cffont properties ja file for the Japanese locale This discussion applies to both the cfdocument and cfreport tags For more informa...

Page 1025: ...ample if your result set is sorted by the passpercentage column you could use the Boolean expression query passpercentage LT 50 5 Specify group break options Start New Column Forces a new column on a...

Page 1026: ...t contain a period 5 Type a default label 6 Specify the data type of the corresponding database column as follows 7 Click OK Note The Query Builder defines query fields automatically for all database...

Page 1027: ...page 1033 Place a query field calculated field or input parameter on a report band 1 In the Fields and Parameters panel use the radio buttons to specify whether to place the label the field or both 2...

Page 1028: ...so drag the BLOB field from the Fields and Parameters tab to a report band 1 Click Cancel The Expression Builder appears 2 Click the Image Type pop up menu and change File URL to BLOB 3 Select the que...

Page 1029: ...ight and width of the band Relative to each other When Align to Band is disabled Report Builder aligns and spaces two or more elements relative to each other Use the Align Palette 1 Select two or more...

Page 1030: ...their most recent changes If your report uses an internal query and you established default web root settings preview functionality is enabled automatically If your report uses a passed query define a...

Page 1031: ...port Builder includes a built in calculated field named PAGE_NUMBER which displays the current page number when you place it on a report band Add a built in calculated field 1 Click the Field tool in...

Page 1032: ...or page within another report An HTML page optionally specifying an anchor and URL parameters One use for links is to create drill down reports in which you click an item to display detailed informat...

Page 1033: ...nt element Select the element from the pop up menu When you select a new element the Report Builder selects the element and displays its properties Although the Properties panel is a powerful way to s...

Page 1034: ...y 2 Create a CFM page and add a cfreport tag that runs the report Optionally pass a query attribute as described in the previous procedure Include a filename attribute that specifies the fully qualifi...

Page 1035: ...u can create reports that select and format data to meet your needs You use CFML in the following areas of the Report Builder Advanced query mode Report functions Expressions Advanced query mode In so...

Page 1036: ...s to retrieve data and for many other purposes Three built in functions are unique to Report Builder InitializeReport BeforeExport and FinalizeReport For more information see the Report Builder online...

Page 1037: ...variables ResultVar variables CRLF cfif cfset variables ResultVar variables ResultVar arguments City arguments State arguments Zip cfreturn variables ResultVar Use a report function 1 Place a dynamic...

Page 1038: ...llowing panels Chart Types Select the chart type for example bar and subtype for example 3D stacked Chart Series Select the data for the series When you add a series the Report Builder lets you hard c...

Page 1039: ...E clause specifying the name of the input parameter used in the main report s Subreport Expression property If you have already defined a subreport you add it to the main report and define subreport p...

Page 1040: ...eter name later in the procedure 8 Click Save and then click Next 9 Specify grouping fields if appropriate for your subreport and click Next 10 Specify Free Form or Grid and click Next 11 Specify Only...

Page 1041: ...and report level pie charts that show the ratio of sold and unsold art for each artist and for all the artists in the database Export report styles to a Cascading Style Sheet CSS file Create a report...

Page 1042: ...s 6 Click the Next button three times to accept the default values 7 Choose Silver and click the Next button 8 Change the title of the report to Sales Report and click the Finish button The Report Cre...

Page 1043: ...o 1 Double click the query ISSOLD element in the detail band Report Builder displays the Expression Builder for that element 2 In the Expression Builder expand the Functions folder 3 Choose Display an...

Page 1044: ...arameters 2 Report Builder displays the Fields and Parameters panel 3 Expand the list of calculated fields 4 With Calculated Fields selected click the button at the upper edge of the Fields and Parame...

Page 1045: ...button 3 In the Name field enter GroupFooter 4 Click the Color and Style tab and change the color to 9999CC 5 Click the Font tab and change the Font to Tahoma and click the bold option Then click OK R...

Page 1046: ...AGE column to the select statement 3 Click the Test Query button A list of image filenames appears to the right of the ISSOLD column 4 Close the Test Query window and click the Save button in the Quer...

Page 1047: ...the report footer band In Adding a calculated field on page 1039 you added a calculated field for the total dollar amount of artwork sold Before you can create the pie chart for this example create a...

Page 1048: ...art Title field type Total Sales for query LASTNAME b In the X Axis Title field type Sold c In the Y Axis Title field type Unsold d In the Label Format field choose Currency from the pop up menu e Cli...

Page 1049: ...calculations are correct Using Cascading Style Sheets The Report Creation Wizard automatically creates and applies the following styles to your report ReportTitle CompanyName PageTitle ReportDate Sub...

Page 1050: ...matically adds the CSS extension 4 Navigate the artStyles css file and double click it to open it The following example shows the generated CSS code ReportTitle color Black font size 24pt CompanyName...

Page 1051: ...Builder does not support all CSS styles For more information see the cfreport tag in the CFML Reference Import the CSS file 1 Choose Window Report Styles 2 Click the import styles icon the one with t...

Page 1052: ...last name The cfreport tag uses the pathname of the CFR file as the report template cfquery name artsales datasource cfartgallery SELECT FROMAPP ART APP ARTISTS WHERE APP ART ARTISTID APP ARTISTS ART...

Page 1053: ...hat points to valid CSS code The CSS style names must match the report style names defined in Report Builder The following code shows how to override the styles in the ArtSalesReport1 cfr report with...

Page 1054: ...on the ColdFusion page for the duration specified in each slide The presenter information is displayed in a control panel next to the slide to which it is assigned Creating a slide presentation Use t...

Page 1055: ...oes not overwrite the files referenced by the slides in the presentation changes to the generated presentation files do not affect the source files Adding presenters Optionally you can add one or more...

Page 1056: ...slide in the presentation has no presenter assigned to it Because Wilson is not assigned to a slide his information does not appear in the presentation In the second slide Anne s photo is displayed i...

Page 1057: ...garden com index htm duration 15 cfpresentation In this example ColdFusion generates the files required to run the presentation in the gardenPresentation directory It generates a new SWF file in the d...

Page 1058: ...a item Scarecrow value 15 cfchartdata item Lion value 50 cfchartdata item Toto value 5 cfchartseries cfchart cfpresentationslide cfpresentationslide title The Golden Age of Ballooning duration 10 src...

Page 1059: ...image cfdocs images artgallery lori01 jpg cfpresenter name Paul title VP Sales email paul company com logo cfdocs getting_started photos somewhere jpg image cfdocs images artgallery paul01 jpg The fol...

Page 1060: ...GetSalaryDetails tr td FirstName LastName td td dateFormat StartDate mm dd yyyy td td numberFormat Salary 9999 9999 td td dept_name td td Contract td tr cfoutput table td td width 200 img src images r...

Page 1061: ...e defines the presenter information You can assign each presenter to one or more slides cfpresenter name Aiden title Artist email Aiden artgallery com image cfdocs images artgallery aiden01 jpg cfpres...

Page 1062: ...data extracted from the query of queries cfpresentationslide title Sales by Artist presenter Paul duration 5 audio myAudio3 mp3 h3 Total Sales by Artist h3 table border cellspacing 10 cellpadding 0 TR...

Page 1063: ...ponent can all share information with each other in XML format They could use a common XML DTD of different components could communicate with each other using different DTDs After an application parse...

Page 1064: ...le XML document The descriptions of the basic and node views use the following simple XML document This document is used in many of the examples in the ColdFusion XML documentation xml version 1 0 enc...

Page 1065: ...sition in the text while the basic view does not ColdFusion also lets you use the DOM objects methods and properties defined in the W3C DOM Level 2 Core specification to manipulate the XML document ob...

Page 1066: ...e Description XmlName String The name of the element includes the namesapce prefix XmlNsPrefix String The prefix of the namespace XmlNsURI String The URI of the namespace XmlText or XmlCdata String A...

Page 1067: ...page 1059 mydoc XmlName mydoc XmlValue mydoc XmlRoot XmlName mydoc employee XmlType mydoc employee XmlNodes 1 XmlType ColdFusion XML tag and functions The following table lists the ColdFusion tags and...

Page 1068: ...n the object For more information on using theXmlElemNew function see Adding an element on page 1073 XmlTransform XMLVar XSLTStringVar parameters Applies an Extensible Stylesheet Language Transformati...

Page 1069: ...tion such as mydoc employee Associative array bracket notation such as mydoc employee Referencing the contents of an XML object Use the following rules when you reference the contents of an XML docume...

Page 1070: ...elements Use an array index into the XmlChildren array to specify an element without using its name for example mydoc XmlRoot XmlChildren 1 Use associative array bracket notation to specify an elemen...

Page 1071: ...st the following expression replaces mydoc employee name 1 with a new element named address not an element named name mydoc employee name XmlElemNew mydoc address After executing this line if there ha...

Page 1072: ...br cfoutput br The XML text representation of Mydoc is cfoutput XMP tostring MyDoc XMP cfoutput h3 Assigning a value to MyDoc myRoot XmlChildren 1 XmlText h3 cfset MyDoc myRoot XmlChildren 1 XmlText...

Page 1073: ...ct which you must then populate For information on how to populate a new XML document see Adding deleting and modifying XML elements on page 1073 Note You cannot set the XmlDocType property for an XML...

Page 1074: ...to save the string as a file For example use the following code to save the XML document myXMLDocument in the file C temp myxmldoc xml cfset XMLText ToString myXMLDocument cffile action write file C t...

Page 1075: ...range of entries in an XmlChildren array to equal the contents of a specified element structure Each entry in the array range is a copy of the structure Can be used to set a single element by specifyi...

Page 1076: ...mPath elemName Always returns False ArrayClear elemPath elemName Removes all the elements with name elemName from the elemPath element ArrayLen elemPath elemName Returns the number of elements named e...

Page 1077: ...ar xmlElemPath elemName A specific child ArrayDeleteAt xmlElemPath XmlChildren position ArrayDeleteAt xmlElemPath elemName position Not available Type Using a function Using an assignment statement Pr...

Page 1078: ...nodeName nodesFound nodesFound 1 return nodesFound cfscript The following lines use this function to display the number of nodes named name in the mydoc employee element cfoutput Nodes Found NodeCoun...

Page 1079: ...function to add an element you can assign the element to a namespace by including the namespace prefix in the element name If you have not yet associated the prefix with a namespace URI also include a...

Page 1080: ...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 r...

Page 1081: ...atus Active To delete an attribute use StructDelete for example cfset StructDelete mydoc employee name 1 XmlAttributes Status Changing element properties To change an element s properties including it...

Page 1082: ...r example the following lines move the phoneNumber element from mydoc employee name 1 to mydoc employee name 2 cfset mydoc employee name 2 phoneNumber mydoc employee name 1 phoneNumber cfset StructDel...

Page 1083: ...eryAddRow myquery size cfloop index i from 1 to size cfset temp QuerySetCell myquery fname mydoc employee name i first XmlText i cfset temp QuerySetCell myquery lname mydoc employee name i last XmlTex...

Page 1084: ...a Boolean status variable indicating whether the document is valid Your application can examine the status information and determine how to handle it further For examples of XML validation see XmlPar...

Page 1085: ...expression with the XML The returned results can be any XPath return type that ColdFusion can represent such as an array of XML object nodes or a Boolean value For more information see XmlSearch in th...

Page 1086: ...ave a body One items element exists that contains multiple item elements Each item element has an id attribute and contains a name quantity and unitprice element The name quantity and unitprice elemen...

Page 1087: ...he order into a query object cfset orderquery QueryNew item_Id name qty unitPrice cfset temp QueryAddRow orderquery numItems cfloop index i from 1 to numItems cfset temp QuerySetCell orderquery item_I...

Page 1088: ...Discount Price b discountPrice cfoutput br br Generate an XML Receipt cfxml variable receiptxml receipt num 34 cfoutput price discountPrice price cfif drate GT 0 discountRate drate discountRate cfif...

Page 1089: ...XML document object into a query object Creates a query with columns for the item_id name qty and unitPrice values for each item For each XML item entry in the mydoc order items entry fills one row of...

Page 1090: ...pplications now expose WDDX capabilities The best source of information about WDDX is www openwddx org This site offers free downloads of the WDDX DTD and SDK and additional resources including a WDDX...

Page 1091: ...ty b string var struct var When you deserialize this XML into CFML or JavaScript the result is a structure that is created by either of the following scripts Conversely when you serialize the variable...

Page 1092: ...ary type Because most languages start array indexes at 0 while CFML array indexes start at 1 working with array indexes can lead to nonportable data Structure Structures are string indexed collections...

Page 1093: ...cal time In this way you need not worry about the details of time zone conversions However when the JavaScript objects supplied with ColdFusion deserialize WDDX to JavaScript expressions they do not u...

Page 1094: ...js The CFML Reference describes these objects and their methods in detail The example Transferring data from the browser to the server on page 1090 shows how you can use these objects to serialize Ja...

Page 1095: ...lize 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 automatica...

Page 1096: ...ment personForm names add entry script Data collection form form action cgi script_name method Post name personForm Input fields Personal information br First name input type text name firstName br La...

Page 1097: ...e The client did not send a well formed WDDX data packet cfif cfelse No WDDX data to process at this time cfif Storing complex data in a string The following simple example uses WDDX to store complex...

Page 1098: ...nerated from client wddxRelatives br cfdump var sameRelatives Using Web Services Web services let you publish and consume remote application functionality over the Internet When you consume web servic...

Page 1099: ...nformation Operations that you can call on the web service Input parameters that you pass to each operation Return values from an operation Consuming web services typically is a two step process 1 Par...

Page 1100: ...know what web services are available As a publisher of web services you want others to be able to find information about your web services Universal Description Discovery and Integration UDDI provides...

Page 1101: ...s button The Add Using WSDL dialog box appears 4 Specify the URL of the WSDL file After the web service is defined to Dreamweaver you can drag it onto a page to call it using the cfinvoke tag For more...

Page 1102: ...soap encoding input output soap body use encoded namespace urn xmethods Temperature encodingStyle http schemas xmlsoap org soap encoding output operation binding service name TemperatureService docume...

Page 1103: ...ed ZIP code Passing parameters to a web service The message and operation elements in the WSDL file contains subelements that define the web service operations and the input and output parameters of e...

Page 1104: ...the getTempResponse message as containing a single string parameter named return Using cfinvoke to consume a web service With the cfinvoke tag you reference the WSDL file and invoke an operation on th...

Page 1105: ...b service After connecting you can make requests to the service For CreateObject syntax see the CFML Reference After creating the web service object you can call operations of the web service using do...

Page 1106: ...re encodingStyle http schemas xmlsoap org soap encoding input output soap body use encoded namespace urn xmethods Temperature encodingStyle http schemas xmlsoap org soap encoding output operation bind...

Page 1107: ...S cfscript cfoutput S cfoutput Even though this web service takes as input the value of S because you pass it as an inout parameter you do not enclose it in number signs Note ColdFusion supports the u...

Page 1108: ...such as string and numeric a WSDL data type maps directly to a ColdFusion data type For complex WSDL data types the mapping is not as straight forward In many cases you map a complex WSDL data type to...

Page 1109: ...ge wsdl message name echoQueryRequest wsdl part name input type tns1 QueryBean wsdl message For information on displaying WSDL see Producing WSDL files on page 1106 Since ColdFusion automatically hand...

Page 1110: ...be remote 2 The cffunction tag must include the returnType attribute to specify a return type 3 The output attribute of the cffunction tag must be set to No because ColdFusion converts all output to...

Page 1111: ...utomatically creates a WSDL file for any component referenced as a web service For example if you have a component named echo cfc in your web root directory you can view its corresponding WSDL file by...

Page 1112: ...p www w3 org 2001 XMLSchema WSDL created by ColdFusion wsdl types schema targetNamespace http rpc xml coldfusion xmlns http www w3 org 2001 XMLSchema import namespace http schemas xmlsoap org soap enc...

Page 1113: ...name echoService wsdl port binding impl echo cfcSoapBinding name echo cfc wsdlsoap address location http localhost 8500 ws echo cfc wsdl port wsdl service wsdl definitions Publish a web service 1 Crea...

Page 1114: ...se address and name to define data types in a ColdFusion component created to publish a web service as the following example shows cfcomponent cffunction name echoName returnType name access remote ou...

Page 1115: ...ut br cfloop cfelse h1 Error thearray is not an array h1 cfif Publishing document literal style web services In addition to RPC oriented operations for which consumers specify a method and arguments C...

Page 1116: ...By default ColdFusion secures access to all URLs that directly reference a CFC file and prompts you to enter a password upon the request Use the ColdFusion RDS password to view the file To disable sec...

Page 1117: ...e the user name password information from the authorization header decode the binary string and extract the user name and password as the following excerpt from an Application cfc onRequestStart metho...

Page 1118: ...header GetSOAPResponseHeader called after the request to retrieve a SOAP header GetSOAPResponse called after the request to retrieve a SOAP response In the web service CFC IsSOAPRequest called to dete...

Page 1119: ...ml cfscript ws CreateObject webservice http localhost 8500 soapexamples HeaderFuncs cfc WSDL addSOAPRequestHeader ws http www cfdevguide com testrequestheader xml_obj cfscript cfscript ret ws showSOAP...

Page 1120: ...ponseHeader http www cfdevguide com testresponseheader xml_obj ret Invoked as a web service Use GetSOAPRequest and GetSOAPResponse to view headers cfscript cfelse cfset ret Not invoked as a web servic...

Page 1121: ...e type s string s element minOccurs 1 maxOccurs 1 name active type s boolean s element minOccurs 1 maxOccurs 1 name age type s int s element minOccurs 1 maxOccurs 1 name hiredate type s dateTime s ele...

Page 1122: ...take some practice Handling return values as complex types When a web service returns a complex type you can write that returned value directly to a ColdFusion variable The previous section used a com...

Page 1123: ...er nesting level is necessary However the variable myReturnVar is not a ColdFusion structure It is a container for the complex type but has none of the attributes of a ColdFusion structure Calling the...

Page 1124: ...he complex type XML schema in WSDL looks like the following complexType name mapItem sequence element name key nillable true type xsd anyType element name value nillable true type xsd anyType sequence...

Page 1125: ...rieve and display the XML passed to and from a web service Although advanced users can use this information for custom functionality you typically use these functions for debugging Use these functions...

Page 1126: ...based application that lets you watch the request and response flow of HTTP traffic However you can also use it to watch the request and response flow of SOAP traffic To run TCPMonitor 1 On Windows a...

Page 1127: ...u do not want to save click Remove Selected and Remove All 7 To resend the request that you are currently viewing and view a new response click Resend You can edit the request in the Request panel bef...

Page 1128: ...dual addresses address ranges of the form 10 30 or wild cards You can specify IPv4 or IPv6 addresses For example you can use the following address patterns 10 10 30 50 20 30 10 10 10 10 10 10 10 FF 2...

Page 1129: ...me source is the source URL of the image in the PHP server Other attributes are the same as the ImageAddborder ColdFusion function Batch operation on Image The following code performs multiple operati...

Page 1130: ...hOperation input Access a ColdFusion service from NET Create a new Web service project in Visual Studio and add ColdFusion WSDL as a web reference to the project Then add a new item such a web form Ex...

Page 1131: ...oldFusion includes a Copytext sample applet that copies text from one text box to another The ColdFusion Setup automatically registers the applet in the Administrator To use this applet incorporate it...

Page 1132: ...ans ColdFusion pages use the cfobject tag to access Java objects ColdFusion searches for the objects in the following order 1 The ColdFusion Java Dynamic Class Load directories 2 Java archive jar file...

Page 1133: ...JSP page or servlet are case independent If you share the Application or Session scope variables between a CFML page and a JSP page or servlet and use an unnamed ColdFusion application the variable na...

Page 1134: ...fimport tag must be on the page that uses the imported tag You cannot place the cfimport tag in Application cfm 4 Use the custom tag using the form prefix tagName for example random number id myNum ra...

Page 1135: ...r the particular customer number The ColdFusion application could use the following CFScript code to call the response JSP page urlParams UID order uid cost order total orderNo order orderNo shipDate...

Page 1136: ...named ColdFusion Application and Session scopes If you do not specify an application name in the This name variable in the Application cfc initialization code or by using the ColdFusion cfapplication...

Page 1137: ...a header and the three variables in the remainder of the body page import java util h2 Hello request getParameter name h2 br Request myVariable request getAttribute myVariable br session myVariable Ma...

Page 1138: ...isplays the value of the Request scope variable myVariable The JSP page must use all lowercase characters to reference all request scope variables that it shares with CFML pages You can use any case o...

Page 1139: ...hare Session variables independent of the variable name case The variable on the JSP page can have any case mixture and still share the value with the ColdFusion page For example instead of myVariable...

Page 1140: ...WEB INF classes For example cfobject type Java class MyClass name myObj Although the cfobject tag loads the class it does not create an instance object Only static methods and fields are accessible im...

Page 1141: ...rn As a result you can set or get the property by referencing it directly without having to explicitly invoke a method For example if the myFishTank class is a JavaBean the following code returns the...

Page 1142: ...ded SetJobGrade method Save the following Java source code in the file Employee java compile it and place the resulting Employee class file in a directory that is specified in the classpath public cla...

Page 1143: ...cfset emp init cfset emp firstname john cfset emp lastname doe cfset firstname emp firstname cfset lastname emp lastname body cfoutput Employee name is firstname lastname cfoutput html When you view...

Page 1144: ...e explicitly calls one of the alternate constructors for the Employee object html body cfobject action create type java class Employee name emp cfset emp init John Doe 100000 00 10 cfset firstname emp...

Page 1145: ...column indicates the Java data types into which ColdFusion can automatically convert the data The following table lists how ColdFusion converts data returned by Java methods to ColdFusion data types C...

Page 1146: ...e whose type you are setting You can specify the following Java data types boolean int long float double and String For more information about the JavaCast function see the CFML Reference Handling Jav...

Page 1147: ...ion handling code The following CFML code calls the testException class doException method The cfcatch block handles the resulting exception cfobject action create type java class testException name O...

Page 1148: ...untime lib directory in ColdFusion Although the specific steps for using an EJB depend on the EJB server and on the EJB itself they generally correspond to the following order 1 Use the cfobject tag t...

Page 1149: ...javax naming Context Create the Properties object and call an explicit constructor CFOBJECT action create name prop type JAVA class java util Properties Call the init method provided by cfobject to in...

Page 1150: ...ipulates integer float array Boolean and Example object types The Example class The following Java code defines the Example class The Java class Example has one public integer member mPublicInt Its co...

Page 1151: ...Buffer s return new String buffer reverse public String ReverseStringArray String arr String ret new String arr length for int i 0 i arr length i ret arr length i 1 arr i return ret public int Add int...

Page 1152: ...ction ensures that CFML variables convert into the appropriate Java data types html head title CFOBJECT and Java Example title head body Create a reference to an Example object cfobject action create...

Page 1153: ...rayNew 1 cfset intarray 1 1 cfset intarray 2 2 cfset IntVal obj sumarray intarray cfset reversedarray obj ReverseArray intarray Display the results cfoutput br IntVal1 IntVal br array1 reversedarray 1...

Page 1154: ...e cfobject tag or CreateObject function to create a reference to a NET class object by specifying either NET or dotnet as the object type You use the reference to access the NET class fields and call...

Page 1155: ...mmunication to access a NET side agent The agent then uses a DLL to invoke the NET assembly classes This communication is required in all cases even if ColdFusion and the NET assemblies are on the sam...

Page 1156: ...ly remote assemblies For information on installing the ColdFusion NET extension see Installing ColdFusion guide Accessing local assemblies For local access ColdFusion automatically generates and uses...

Page 1157: ...rectory When you use the stand alone installer the programs are located in the installDir jnbridge directory This document provides the basic information necessary to generate a proxy JAR file using t...

Page 1158: ...From Assembly File and navigate to the directory that you added to the assembly list in step a Select the assembly file or files that contain classes that require proxies and click OK c The classes in...

Page 1159: ...xyGui tool when you click the Add button the list includes only the explicitly listed classes When you click the Add button the list also includes the supporting classes In the jnbproxy command line p...

Page 1160: ...ame assemblyList type com jnbridge jnbcore AssemblyListHandler JNBShare sectionGroup jnbridge javaToDotNetConfig scheme jtcp port 6086 assemblyList x assembly file System Windows Forms Version 1 0 500...

Page 1161: ...nstructors Using the init method causes ColdFusion to call the class constructor with the corresponding number and types of parameters For example the following tags cause ColdFusion to call the MyCla...

Page 1162: ...mong NET Common Language Runtime CLR primitive and standard data types the Java data types used in the proxies to represent CLR data types and ColdFusion data types in your CFML application NET type J...

Page 1163: ...ument type and you want to pass primitive values as arguments to that method use the javacast function to identify the data conversion Once ColdFusion knows the data type it automatically converts to...

Page 1164: ...ecial objects in the same manner as you create other NET classes before you use them in your assignment statement For example the following line creates a ushort representation of the value 100 cfset...

Page 1165: ...NET objects can be passed as it is Handling ambiguous type conversions ColdFusion cannot determine the correct data type conversion if a method has multiple signatures with the same number of paramet...

Page 1166: ...element keys differ only in case Therefore to get the values of the keys that differ only in case use associative array notation The following example shows this issue It creates a Hashtable object wi...

Page 1167: ...oad reader return dt ColdFusion code cfset query1 netObject datasetMethod cfoutput query query1 Query1 CurrentRow query1 CurrentRow br cfoutput Using ColdFusion complex types in NET input parameters W...

Page 1168: ...er include the following setting in the JVM config file Dcoldfusion dotnet disableautoconversion true Manually converting complex NET objects Use the DotNetToCFType function to convert a System Collec...

Page 1169: ...ity has the following limitations You cannot invoke methods with pointers as arguments or the return type You cannot invoke methods that take Out parameters ColdFusion can only convert from System Dat...

Page 1170: ...type string required yes Local variables cfset var pingClass cfset var pingReply Get Ping class cfobject type NET name pingClass class System Net NetworkInformation Ping Perform synchronous ping using...

Page 1171: ...dCreator newParagraph cfloop cfset wordCreator save The C source for the WordCreator class is as follows using System using System IO using System Collections Generic using System Text The commented o...

Page 1172: ...sionally the use of additional tools for generating proxies and running the NET extension software can be helpful in some workflows Using the jnbproxy command You can use the jnbproxy command line too...

Page 1173: ...localhost java javapath Optional Use the first java exe file found using the system PATH environment variable Specifies the path of the directory that contains the java exe program to use when automat...

Page 1174: ...time that it was passed The passed object maintains no connection to the underlying NET object therefore the passed value does not reflect any updates to the underlying NET object that are made after...

Page 1175: ...able package on the system that runs ColdFusion Then reinstall the ColdFusion NET extension so that it uses the correct NET version Running the NET extension agent as an application The ColdFusion NET...

Page 1176: ...Object Request Broker Architecture is a distributed computing model for object oriented applications defined by the Object Management Group OMG In this model an object is an encapsulated entity whose...

Page 1177: ...he ColdFusion page execution Using properties Use standard ColdFusion statements to access properties as follows 1 To set a property use a statement or cfset tag such as the following cfset obj proper...

Page 1178: ...nd prevent further web server requests from being serviced ColdFusion can call Inproc Local or Remote COM objects The attributes specified in the cfobject tag determine which type of object is called...

Page 1179: ...registered as described in Registering the object on page 1173 The Object Viewer retrieves all COM objects and controls from the Registry and presents the information in a simple format sorted into gr...

Page 1180: ...s Create method cfobject action Create Takes a COM object typically a DLL and instantiates it before executing methods and assigning properties Connect method cfobject action Connect Links to an objec...

Page 1181: ...immediately release resources if an object is no longer needed Use the ReleaseCOMObject function to release COM objects that are launched as an external process such as Microsoft Excel The garbage co...

Page 1182: ...ject Classes in the left pane 3 Locate your COM object The left pane lists the objects by name 4 Select your object 5 Select the Implementation tab in the right pane 6 Select the Inproc Server tab bel...

Page 1183: ...nue to use the cfobject tag with a type attribute value of COM or the CreateObject function with a first argument of COM and you access the object properties and methods as you normally do for COM obj...

Page 1184: ...gh this naming convention is not necessary consider using a similar package naming convention for clarity if you use many COM objects e Click the Generate Proxies button to display the File browser Se...

Page 1185: ...tlook COM object outlookXP is the package name you specified in step 3c and Application is the main class of the COM object 8 Restart the ColdFusion server Open the Services control panel select ColdF...

Page 1186: ...sible problems use both techniques Example 1 Using the FileSystem object The following example uses the Microsoft FileSystem Scripting object in the Application scope This code creates a user defined...

Page 1187: ...ten To work with Word 97 change Val 8 to Val 10 This example uses an Application scope lock to ensure that no other page interrupts creating the object Once the Word object exists the example uses a n...

Page 1188: ...Complete br Execution Time int getTickCount start milliseconds br cfoutput Getting started with CORBA The ColdFusion cfobject tag and CreateObject function support CORBA through the Dynamic Invocation...

Page 1189: ...is context and register the appropriate name Using CORBA objects in ColdFusion After you create the object you can invoke attributes and operations on the object using the syntax described in Creating...

Page 1190: ...s by value in parameters CORBA in parameters are always passed by value When calling a CORBA method with a variable in ColdFusion specify the variable name without quotation marks as shown in the foll...

Page 1191: ...ColdFusion supports and whether they can be used as parameters or return variables NA means not applicable IDL double method out double a CFML cfset foo 3 1415 cfset ret handle method foo cfoutput ret...

Page 1192: ...ng wchar One character string string String wstring String octet One character string short Integer long Integer float Real number double Real number unsigned short Integer unsigned long Integer void...

Page 1193: ...characters in ColdFusion convert appropriately to wstring and wchar data when they are used However the CORBA 2 0 IDL specification does not support the wchar and wstring types and uses the 8 bit Lati...

Page 1194: ...er CORBA object This simplified object determines whether an applicant is approved for a loan based on the information that is supplied The LoanAnalyzer CORBA interface has one method which takes the...

Page 1195: ...his case the applicant has a Master Card a Visa card and a Diners card Because Master Card MC is the first entry in the enumerator type definition it is represented in ColdFusion by the number 0 Visa...

Page 1196: ...count struct cfset a StructNew cfif IsStruct a cfset a person p cfset a age 34 cfset a income 150120 50 cfif Declare a CreditCards sequence cfset cards ArrayNew 1 cfset cards 1 0 corresponds to Amex c...

Page 1197: ...gs to send and receive e mail respectively How ColdFusion sends mail The ColdFusion implementation of SMTP mail uses a spooled architecture If you select to spool mail on the Mail page in the ColdFusi...

Page 1198: ...Server Port and Connection Timeout default settings 4 Select the Verify Mail Server Connection option to make sure ColdFusion can access your mail server 5 If your mail server does not use port 25 th...

Page 1199: ...ou customize your mail or control how it is sent For a description of all attributes including options to wrap mail text at a specified column specify the mail character encoding and specify the mail...

Page 1200: ...Note In the HTML version of the message escape any number signs such as those used to specify colors by using two characters for example bgcolor C5D9E5 Sample uses of the cfmail tag An application pa...

Page 1201: ...tag you can send e mail to multiple recipients by using the query attribute of the cfmail tag The following examples show how you can send the same message to multiple recipients and how you can cust...

Page 1202: ...ble To all Widget beta testers Widget Beta Four is now available for downloading from the MyCompany site The URL for the download is http beta mycompany com Regards Widget Technical Support beta MyCom...

Page 1203: ...our firm Our current information is as follows Company Name GetCustomers Company Contact GetCustomers FirstName GetCustomers LastName Address GetCustomers Address1 GetCustomers Address2 GetCustomers C...

Page 1204: ...s are available on the Java SDK web site Using the cfmailparam tag You use the cfmailparam tag to include files in your message or add a custom header to an e mail message You can send files as attach...

Page 1205: ...location in your HTML where you want the message included use an img tag such as the following img src cid myImage1 The following example shows a simple mail message with an inline image In this case...

Page 1206: ...her major e mail protocol Internet Mail Access Protocol IMAP Here are three instances in which implementing POP mail makes sense If your site has generic mailboxes that more than one person reads sale...

Page 1207: ...e query that cfoutput or cfloop in a query driven loop is processing The query includes one variable that the cfquery tag does not return the UID variable contains the unique identifier of the e mail...

Page 1208: ...der Example title head body h2 This example retrieves message header information h2 cfpop server mail company com username myusername password mypassword action GetHeaderOnly name Sample cfoutput quer...

Page 1209: ...ueryname messageNumber cfoutput Retrieving messages When you use the cfpop tag with action GetAll ColdFusion returns the same columns as with getheaderonly plus the following additional columns attach...

Page 1210: ...ur 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 normally see it in a mail program that supports...

Page 1211: ...s HTMLEditFormat Sample Attachments br Attachment Files HTMLEditFormat Sample AttachmentFiles br br Body br Sample body br br Header br HTMLCodeFormat Sample header br hr cfoutput body html 2 Edit the...

Page 1212: ...use valid values for your POP mail server user name and password cfpop server mail company com username myusername password mypassword 3 Save the file as message_delete cfm in the myapps directory und...

Page 1213: ...ent or transient A persistent connection lasts until you explicitly close it Persistent connections let you use a single connection for multiple tasks which saves the processing overhead of opening an...

Page 1214: ...the login user Outlook web access Check and grant web access 1 In the Exchange administrator open Administrative Tools Active Directory Users and Computers your domain name users 2 Right click the use...

Page 1215: ...the name of the connection which you use in subsequent tags to specify the connection You typically also specify a password and can specify several other attributes including a proxy host or a delega...

Page 1216: ...var theUID Accessing delegated accounts In Exchange one user can grant or delegate another user access rights to their account Users can delegate reviewer read only author read write or editor read wr...

Page 1217: ...ifies a structure with the information you are adding You can also specify a result variable that contains the value of the Exchange UID for the entry that you create You can use this UID to identify...

Page 1218: ...width 100 option value CA CA option option value MA MA option option value WA WA option cfselect cfinput type text label Country name Country width 200 Value U S A cfformitem type html b Phone b cffor...

Page 1219: ...items from only a single mail folder at a time You can use the cfexchangeconnection tag to get the names paths and sizes of all folders in a mailbox and can use the results to iterate over the folder...

Page 1220: ...cfexchangeconnection action getSubfolders connection conn1 name folderInfo folder Inbox recurse yes Get the information from the Inbox top level The getSubfolders results do not include an Inbox row c...

Page 1221: ...fy in the name attribute You determine the items to get by specifying selection conditions in cfexchangefilter child tags The code to get items from the Exchange server has the following pattern cfexc...

Page 1222: ...e folders see Getting and using folder names on page 1214 When ColdFusion gets the results it creates the query object specified in the name attribute if it does not exist and populates each row with...

Page 1223: ...ave the UID of the message and know that the message has attachments Use a ColdFusion Exchange tag such as cfexchangemail with the get action to determine this information When the tag completes proce...

Page 1224: ...hortUID Mid weeksMail UID 2 atpos 2 cfexchangemail action getAttachments connection conn1 folder Inbox MailTest uid weeksMail uid name attachData attachmentPath C temp cf_files attachments shortUID ge...

Page 1225: ...om the attachments Open the connection to the Exchange server cfexchangeconnection action open username user1 password password1 server exchangeServerIP connection testconn Get the mail message cfexch...

Page 1226: ...item the new attachments are added to the previous attachments they do not replace them Use the deleteAttachments action to remove any obsolete or changed attachments Modifying calendar contact and t...

Page 1227: ...Form date Day Form date Hour Form endTime Minute Form endTime 0 sEvent Location Form location sEvent RequiredAttendees Form requiredAttendees sEvent OptionalAttendees Form optionalAttendees sEvent Res...

Page 1228: ...nder style width 200 cfselect name importance label Importance style width 100 option value normal Normal option option value high High option option value low Low option cfselect cfselect name sensit...

Page 1229: ...fexchangemail tag move action as shown in the following code snippet which moves all messages with the subject Rams and Ewes from the Unread folder in the Inbox to the Sheep folder in the inbox cfexch...

Page 1230: ...he Inbox cfloop index i from 1 to ArrayLen meetingData cfif meetingData i StartTime LTE now cfexchangemail action delete connection conn1 UID meetingData i UID cfif cfloop cfexchangeconnection action...

Page 1231: ...he cfexchangemail tag completes processing the MeetingUID column of the structure specified by the cfexchangemail tag name attribute contains the UIDs of the meetings 2 For each meeting get the inform...

Page 1232: ...lue Meeting_Request cfexchangemail Get the meeting request data cfloop query requests cfexchangemail action getmeetinginfo connection conn1 name meeting meetinguid MeetingUID cfset meetingData request...

Page 1233: ...eNoEndDate value is automatically false therefore Specify a RecurrenceNoEndDate field only if you are changing an existing event with a recurrence count or end date to one with no end date Specify the...

Page 1234: ...T SUN If you omit this attribute the event recurs on the day of the week determined by the startTime field value The following CFScript code sample sets an event that occurs on Tuesday and Thursday of...

Page 1235: ...d Thursday of August three months IsRecurring true RecurrenceType YEARLY RecurrenceMonth AUG RecurrenceWeek third RecurrenceDay THU Example Setting calendar recurrence The following example lets you c...

Page 1236: ...alAttendees sEvent Resources Form resources if Form reminder NEQ sEvent Reminder Form reminder else sEvent Reminder 0 sEvent Importance Form importance sEvent Sensitivity Form sensitivity Recurrence F...

Page 1237: ...abel Location name location style width 435 br cfinput type text label Required Attendees name requiredAttendees style width 435 br cfinput type text label Optional Attendees name optionalAttendees st...

Page 1238: ...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 offerings across the web About interac...

Page 1239: ...d You use Get to retrieve files including text and binary files from a specified server The retrieved information is stored in a special variable cfhttp fileContent The following examples show several...

Page 1240: ...ng table describes the code and its function Get a binary file and save it 1 Create a ColdFusion page with the following content cfhttp method Get url http www adobe com adobe accessibility images spo...

Page 1241: ...haracter To include the text qualifier character in a field use a double character For example if the text qualifier is use to include a quotation mark in the field The first row of text is always int...

Page 1242: ...ery_textfile cfm in the myapps directory under your web_root and view it in the web browser Using the cfhttp Post method Use the Post method to send cookie form field CGI URL and file variables to a s...

Page 1243: ...y html 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 Write a page to...

Page 1244: ...param type File name myfile file c pix trees gif Send a file in the request The tag ends the http request cfoutput File Content br cfhttp filecontent br Display the contents of the file that the page...

Page 1245: ...he Sandbox Security page in the Security area in the ColdFusion Administrator In the Standard Edition select Security Basic Security For server browser operations use the cffile cfcontent and cfdirect...

Page 1246: ...stoponerror Yes Close the connection cfftp action close connection Myftp p Did the connection close successfully cfoutput cfftp succeeded cfoutput p output dirlist results hr p FTP Directory Listing p...

Page 1247: ...nnection Myftp server MyServer username MyUserName password MyPassword action Open stoponerror Yes Open an FTP connection to the MyServer server and log on as MyUserName If an error occurs stop proces...

Page 1248: ...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 specify the username password a...

Page 1249: ...ote Consider the security and logical structure of directories on the server before allowing users access to them You can disable the cffile tag in the ColdFusion Administrator Also to access files th...

Page 1250: ...to upload and submit the form The file you specified uploads Reviewing the code The following table describes the code and its function Code Description form action uploadfileaction cfm enctype multi...

Page 1251: ...e of file that is uploaded for example to not accept graphic files in a document library You use the accept attribute to restrict the type of file that you allow in an upload When an accept qualifier...

Page 1252: ...mple attributes ReadOnly Hidden If you do not use the attributes attribute the existing attributes of the file are maintained If you specify any other attributes in addition to Normal the additional a...

Page 1253: ...name of the source file on the client system with the filename extension for example myfile txt clientFileExt Extension of the source file on the client system without a period for example txt not txt...

Page 1254: ...se the cffile tag to read an existing text file The file is read into a local variable that you can use anywhere in the application page For example you could read a text file and then insert its cont...

Page 1255: ...ut type text name FileName size 25 txt p p Enter your message textarea name message cols 45 rows 6 textarea p input type submit name submit value Submit form body html 2 Save the file as writetextfile...

Page 1256: ...e tag you can disable cfdirectory processing in the ColdFusion Administrator For details on the syntax of this tag see the CFML Reference Returning file information When you use the action list attrib...

Page 1257: ...ine 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 Using cfcontent The cfcontent tag downlo...

Page 1258: ...cfcontent_message htm in the myapps directory under your web_root The ColdFusion file that you write in steps 3 through 7 calls this file 3 Create a ColdFusion page with the following content html he...

Page 1259: ...mployees_to_excel cfm in the myapps directory under your web_root and view it in the browser The data appears in an Excel spreadsheet Using Event Gateways Adobe ColdFusion provides event gateways whic...

Page 1260: ...essage clients Java Sockets which let your ColdFusion application communicate with TCP IP based devices and programs such as Telnet terminal clients Java Messaging Service JMS resources such as storef...

Page 1261: ...instant messaging protocol or Sockets You generally have one event gateway type per communication protocol You configure each event gateway type on the Gateway Types page in the Event Gateways area i...

Page 1262: ...not do both The example DirectoryWatcherGateway discussed in Example event gateways on page 1271 listens for events only and the asynchronous CFML event gateway receives messages from CFML only You c...

Page 1263: ...C methods to initiate outgoing messages The application also could use an event gateway specific GatewayHelper object to do tasks such as getting buddy lists in IM applications or getting the status o...

Page 1264: ...gateway that monitors changes to the contents of a directory A Java Messaging Service JMS gateway that acts as a JMS consumer or producer Several sample applications including the following A menu app...

Page 1265: ...s page lets you add remove configure start and stop individual event gateway instances You configure an event gateway instance by specifying a unique ID the gateway type one or more listener CFC paths...

Page 1266: ...n tag The role of ColdFusion pages ColdFusion CFM pages cannot receive event messages However they can send messages using an event gateway Therefore an event gateway application that initiates outgoi...

Page 1267: ...ay Event gateway applications can also use the following code elements SendGatewayMessage CFML functions to send messages from outside the listener CFC or optionally from the CFC GatewayHelper objects...

Page 1268: ...scopes to store data that must be preserved over multiple CFC invocations or shared with other CFML elements Listener methods The ColdFusion event gateway service calls one or more listener methods in...

Page 1269: ...listener CFCs ColdFusion listener CFCs can use the Application Client and Session persistent scopes Because incoming event gateway messages are not associated with HTTP requests ColdFusion uses diffe...

Page 1270: ...nt ID for all interactions with a particular client For many technologies and gateways such as the IM and SMS gateways this requirement is not an issue Note To use Client scope variables with gateways...

Page 1271: ...messages to the console window as the following code shows cfscript sys createObject java java lang System sys out println Debugging message goes here cfscript Note You do not have to restart the eve...

Page 1272: ...ue as required for the event gateway type cfif arguments CFEVENT GatewayType is Socket cfset retValue structNew cfset retValue MESSAGE retmsg cfset retValue originatorID orig cfelseif arguments CFEVEN...

Page 1273: ...ava GatewayHelper object that provides event gateway specific helper methods and properties To use this function the event gateway must implement a GatewayHelper class For example an instant messaging...

Page 1274: ...esigned to let multiple event gateway instances share a configuration file Others could require a separate file for each event gateway instance 3 Install the event gateway application listener CFC and...

Page 1275: ...eway type Specify the following A unique Gateway ID The path to the CFC that you created in step 1 The startup mode Select Automatic startup mode to start the event gateway when ColdFusion starts up D...

Page 1276: ...ateway Sending an event to the CFML event gateway that is registered in the ColdFusion Administrator as Asynch Logger br cfscript status false props structNew props Message Replace me with a variable...

Page 1277: ...containing the socket IDs of all Java sockets that are open The event gateway opens a socket for each remote client killSocket String socketid removes the specified socket Returns a Boolean success i...

Page 1278: ...However if the directory watcher monitors changes infrequently for example once every minute or more the time in the log entry could differ from the time a file was added or changed so the informatio...

Page 1279: ...as a Java Messaging Service consumer or producer The source for this event gateway is located in gateway src examples JMS The gateway requires a configuration file which is in gateway config jmsgatewa...

Page 1280: ...ured with an instance of the application that uses SMS as follows The Gateway Instances page in the ColdFusion Administrator includes a gateway instance for this application that uses the SMS gateway...

Page 1281: ...run the SMSClient bat file on Windows or SMSClient sh file on UNIX or Linux to start the SMS phone simulator The simulator is preconfigured by default to call the default SMS event gateway configurati...

Page 1282: ...owing websites provide additional information about the XMPP protocol Jabber Software Foundation www jabber org This site includes information on available XMPP servers and clients IETF has copies of...

Page 1283: ...you configure the gateway instance in the ColdFusion Administrator The gateway passes outgoing messages from this CFC and from other CFML code to the IM server The IM event gateway also provides seve...

Page 1284: ...the cf_root WEB INF cfusion gateway config directory on J2EE configurations and cf_root gateway config directory on server configurations The configuration file can have the following information Note...

Page 1285: ...this event to a CFC onAddBuddyResponseF unction onAddBuddyResponse Name of CFC method to call to handle an incoming response to a buddy request sent by ColdFusion If you specify the property without a...

Page 1286: ...cline Your application can handle this response as appropriate for example to add or remove the ID from a list of message recipients This method does not return a value onBuddyStatus Message indicatin...

Page 1287: ...ssage event and a Gateway management CFC that responds to all other events This example shows how an application can respond to events and send outgoing messages You can configure a gateway to use bot...

Page 1288: ...nd last name cfif listlen message eq 2 and FirstName like listFirst message and LastName like listlast message No space the user entered a first or a last name cfelse and FirstName like listFirst mess...

Page 1289: ...icular it does the following The onBuddyStatus function updates the Application scope buddy status structure when the gateway gets an event message indicating that a buddy s status has changed The onA...

Page 1290: ...gument name CFEvent type struct required YES cfquery name buddysearch datasource cfdocexamples select IM_ID from Employees where IM_ID CFEvent Data SENDER cfquery cflock scope APPLICATION timeout 10 t...

Page 1291: ...ew if CFEVENT Data MESSAGE IS accept Create a new entry in the buddyStatus record for the buddy if NOT StructKeyExists Application buddyStatus CFEvent Data SENDER Application buddyStatus CFEvent Data...

Page 1292: ...lability status presence information Gateway buddy management methods The following table describes the methods that you can use to manage the gateway s buddy list Method Description getName Returns t...

Page 1293: ...and tells the IM server to stop sending the gateway messages with the user s online state Method Description addDeny Tells the IM server to add the specified user to the gateway s deny list If the pe...

Page 1294: ...ct one of the following to get or set h3 ul li a href cgi script_name cmd buddyinfo buddyinfo a li LIST a href cgi script_name cmd buddylist buddylist a a href cgi script_name cmd permitlist permitlis...

Page 1295: ...ame cmd getsignontimestamp getsignontimestamp a a href cgi script_name cmd getstatustimestamp getstatustimestamp a li setPermitMode cfloop list PERMIT_ALL DENY_ALL PERMIT_SOME DENY_SOME IGNORE_IN_LIST...

Page 1296: ...r setStatus url status cfcase cfcase value setstatus2 cfset ret helper setStatus url status url custommsg cfcase cfcase value getcustomawaymessage cfset ret helper getCustomAwayMessage cfcase cfcase v...

Page 1297: ...om 1 to arraylen ret cfdump var helper getBuddyInfo ret i label ret i cfloop cfif cfif cfoutput Using the SMS Event Gateway You can develop an application that uses the short message service SMS event...

Page 1298: ...your account the SMSC gets the messages that are sent to this number The SMSC can store and forward messages A ColdFusion application can initiate messages to wireless devices or it can respond to in...

Page 1299: ...mobile devices can send messages to a ColdFusion listener CFC by using the gateway instance s telephone number Incoming messages include the sender s number so listener CFCs can respond to messages s...

Page 1300: ...MPP provider s SMSC It is designed to help you to understand the basics of SMPP interactions and defines the terms necessary to for you to understand gateway configuration and message handling For mor...

Page 1301: ...sends a message to multiple destinations data Sends a data_sm PDU with the message contents to the SMSC This command is an alternative to the submit command and interactive applications such as those...

Page 1302: ...ting the event gateway to the SMSC To connect to the ColdFusion SMS test server the password must be cf source ton 1 Type of Number TON of the source address that is of the address that the event gate...

Page 1303: ...The gateway attempts to resend the message Retrying is useful if the gateway is in asynchronous mode where the CFML SendGatewayMessage function does not return an error no The gateway does not retry s...

Page 1304: ...ructure see Appendix B of the SMS 3 4 specification SME Delivery Acknowledgement An indication from the recipient device that the user has read the short message Supported by TDMA and CDMA wireless ne...

Page 1305: ...ent originatorID cfset retValue structNew cfset retValue command submit cfset retValue sourceAddress arguments CFEVENT gatewayid cfset retValue destAddress arguments CFEVENT originatorid cfset retValu...

Page 1306: ...sends the message to the SMS client simulator h3 Sending SMS From a Web Page Example h3 cfif IsDefined form oncethrough is Yes cfif IsDefined form SMSMessage is True AND form SMSMessage is not h3 Send...

Page 1307: ...et retValue structNew cfset retValue command submitmulti cfset retValue sourceAddress arguments CFEVENT gatewayid cfset retValue destAddresses arraynew 1 One destination is incoming message originator...

Page 1308: ...formation on other ways to configure outgoing message see the SMPP specification Synchronization mode You can specify asynchronous or synchronous message mode in the gateway configuration file If you...

Page 1309: ...nu App 5551212 msg cfscript cfif cfif isDefined ret AND ret NEQ h3 Text message sent h3 cfoutput The Message Id is ret cfoutput br br cfif hr noshade cfif begin by calling the cfform tag cfform SMS Te...

Page 1310: ...propriate To change this value include a validityPeriod field in the Data parameter of a SendGatewayMessage function or the return variable of the CFC listener method To specify a time period use the...

Page 1311: ...mited function mobile phone It can connect to the SMS test server and exchange messages with it Note On UNIX and Linux systems the client simulator requires X Windows Use the following procedure to us...

Page 1312: ...uld let the user get multiple lists of messages to provide access to all names If the user enters a number and previously got a multiple match list the application returns the information for the name...

Page 1313: ...dCount records else returnVal shortMessage Records found employees recordCount The session users structure contains the found names The record key is a number that is also returned in front of the nam...

Page 1314: ...shared objects ColdFusion provides the following tools for developing FMS applications FCSj jar The JAR file that implements the Java API to communicate with Flash Media Server FMSGateway The class fo...

Page 1315: ...opriate shared object 5 Flash Media Server updates the shared object 6 Flash Media Server notifies the Flash client that a shared object has changed 7 The Flash client makes the changes in its content...

Page 1316: ...pass a ColdFusion query object to Flash Media Server as an array of java util HashMap Each HashMap object in the array contains a key value pair for column names and values for each row in the query...

Page 1317: ...s the onIncomingMessage method of the Data Services Messaging event gateway listener CFC 6 The ColdFusion application generates a message which it sends to the ColdFusion server 7 The ColdFusion serve...

Page 1318: ...e Server host 127 0 0 1 If you create a configuration file save it in the cf_root gateway config directory with the extension cfg Sending outgoing messages Your ColdFusion application sends a message...

Page 1319: ...hat properties maintain the correct case define Flex related information as follows myStruct mySensitiveProp myOtherSensitiveProp The following is an example of using headers to send to a specific sub...

Page 1320: ...plication sends the message in the header instead of in the body you create and populate the structure as the following example shows cfset messageheader StructNew cfset messageheader sendto event dat...

Page 1321: ...use the Data Management event gateway to send messages to a Flex application the Flex application must be running on LiveCycle Data Services ES How ColdFusion and Flex interact You can send messages f...

Page 1322: ...server and the Flex server Application development and deployment process The following is a typical process for developing and deploying a ColdFusion application that communicates with a Flex applic...

Page 1323: ...to send the message to The body is the body of the message The sendGatewyMessage CFML function sends the message to the instance of the gateway Name Contents destination Destination of the message Th...

Page 1324: ...ation all StructNew all destination cfcontact all action batch all changes ArrayNew 1 all changes 1 createEvent all changes 2 updateEvent all changes 3 deleteEvent r sendGatewayMessage LCDS all cfscri...

Page 1325: ...gateway forwards the message as appropriate to the external receiver The event gateway architecture is not limited to handling messages from external sources such as SMS devices or IM clients It can a...

Page 1326: ...sets the ID void setCFCListeners String listeners Identifies the CFCs that listen for incoming messages from the event gateway The array contains one or more paths to the listener CFCs ColdFusion cal...

Page 1327: ...Returns a ColdFusion Logger object that the event gateway can use to log informationintheeventgateway loglogfile thedefault orthespecifiedlogfile The logfile attribute must be a filename without a fi...

Page 1328: ...s the socket IDs the other closes a specified socket These classes let an application monitor and end session connections void setCFCMethodmethod String getCFCMethod The method in the listener CFC tha...

Page 1329: ...path in the gateway constructor when it instantiates the event gateway The configuration file format and content handling is up to you It is the responsibility of the gateway class to parse the file...

Page 1330: ...ation and the cf_root WEB INF cfusion directory on J2EE configurations This file contains minimal versions of all methods in the coldfusion eventgateway Gateway interface It defines a skeleton listene...

Page 1331: ...Start method also loads the file Load the file because the constructor does not run in an independent thread and ColdFusion can display an error in the ColdFusion Administrator of the file fails to l...

Page 1332: ...th methods ColdFusion calls the setGatewayID method when it starts a gateway The getGatewayID method must return the value set by this method ColdFusion calls the getHelper method when an application...

Page 1333: ...e Doing so lets users change the configuration file and restart the gateway without restarting ColdFusion Also load the configuration file in the constructor for more information see Class constructor...

Page 1334: ...rSocket close catch IOException e1 Release the serverSocket serverSocket null Shutdown succeeded set the status variable status STOPPED The restart method In most cases you implement the restart metho...

Page 1335: ...usion event gateway services event queue could reach the maximum value set in the ColdFusion Administrator When the queue reaches the maximum the gatewayService addEvent method returns False and fails...

Page 1336: ...CfcMethod cfcEntryPoint event setCfcTimeOut 10 if path null event setCfcPath path boolean sent gatewayService addEvent event if sent log error SocketGateway gatewayID Unable to place message on event...

Page 1337: ...until the message is delivered to the SMSC or an error occurs This way an SMS application can get a message ID for later use such as to compare with a message receipt Example outgoingMessage method T...

Page 1338: ...neral exception messages and the exception name in the eventgateway log file and also automatically logs the exception in the exceptions log file catch Exception e logger error SMSGateway gatewayID Ex...

Page 1339: ...art button green triangle on the entry for the gateway instance to start the instance Using the ColdFusion Extensions for Eclipse The Adobe ColdFusion Extensions for Eclipse include wizards that help...

Page 1340: ...mber 8500 if you are using the built in web server Context root if necessary For more information about the context root see Installing ColdFusion guide Password which is the RDS password 3 To specify...

Page 1341: ...a sources on the RDS server You use the buttons as indicated in the following table You can build queries using either the RDS Query Viewer or the Visual Query Builder The RDS Visual Query Builder is...

Page 1342: ...sed to join them by dragging a column from one table to the related column in the second table 4 Optional Specify sort order by doing the following a Locate the column in the Properties panel b Click...

Page 1343: ...sing Visual Query Builder see Using Visual Query Builder on page 1337 Designing your application Before starting the ColdFusion Flex Application wizard you should determine which pages to include in y...

Page 1344: ...s you specify the pages to use in your application You can create master detail or master detail pages In your application you can link master detail and master detail pages as follows Create a page 1...

Page 1345: ...you previously created If you create a master page and a detail page for a table in which there is no primary key defined the wizard selects the first field in the database as the key value to represe...

Page 1346: ...to Project Folder text box or click Browse and select the location 5 Enter the filename of the CFC in the CFC Filename text box 6 To replace an existing file select Overwrite file 7 To create get and...

Page 1347: ...ods read primary key value create cfc instance update cfc instance delete cfc instance Data Service assembler CFC which includes a Bean also referred to as a Value Object a DAO CFC and an assembler CF...

Page 1348: ...e components Manage web services Browsing components The Service Browser lists the following components Components that the ColdFusion component browser lists The ColdFusion component browser is locat...

Page 1349: ...generate ActionScript To view the list of web services click the Show Web Services button in the top right corner of the Services Browser view Add a web service to the list 1 Right click in the Servic...

Page 1350: ...e list of web services 3 Highlight a web service or a method in a web service and right click 4 Select Insert CFInvoke The code that the Service Browser generates appears in the ColdFusion file The fo...

Reviews: