Adobe COLDFUSION 9 Скачать руководство пользователя страница 269

264

DEVELOPING

 

COLDFUSION 9 APPLICATIONS

Developing CFML Applications

Las

t

 upda

te

d 8/5/2010

Example

<cftry>  

<cfset dir = "s3://bucket_name/">  
<cfset perm = structnew()>  
<cfset perm.group = "authenticated">  
<cfset perm.permission = "READ">  
<cfset perm1 = structnew()>  
<cfset perm1.email = "email_ID">  
<cfset perm1.permission = "READ_ACP">  
<cfset myarrray = [perm,perm1]>  
<cfif NOT DirectoryExists(dir)>  

<cfset directoryCreate(dir)>  

</cfif>  
<cfset fileWrite("#dir#/Sample.txt","This is to test 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

Returns an ACLObject

Syntax

StoreGetACL(url, ACLObject)

Parameters

History

ColdFusion 9 Update 1: Added this function

Example

<cfset dir = "s3://bucket_Name">  

<cfif NOT DirectoryExists(dir)>  

 <cfset directoryCreate(dir)>  

        </cfif>  

<cfset test = StoreGetACL("#dir#")>  
<cfdump var="#test#"> 

Parameter

Description

url

Amazon S3 URLs  (content or object)

ACLObject

An array of struct where each struct represents a permission or grant as discussed in “

ACLObject

” on page

 

262.

Содержание COLDFUSION 9

Страница 1: ...Developing Applications ADOBE COLDFUSION 9...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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_...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 237: ...w OutputQuery DebugRequest request new DebugRequest attributes query DebugResponse response new DebugResponse tag processRequest request response response printResults catch Throwable e e printStackTr...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 256: ...Q cfinclude template noauthuserfooter cfm cfelse cfinclude template authuserfooter cfm cfif cffunction cffunction name onSessionStart cfscript Session started now Session shoppingCart StructNew Sessio...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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_...

Страница 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...

Страница 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...

Страница 274: ...Info GetDirectoryFromPath GetFileFromPath ImageNew ImageRead ImageWrite ImageWriteBase64 IsImageFile IsPDFFile FileSetLastModified Example The following syntax explains the function FileSetLastModifie...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 315: ...e function or the DeleteClientVariable function For example the following lines are equivalent cfset IsDeleteSuccessful DeleteClientVariable MyClientVariable cfset IsDeleteSuccessful StructDelete Clie...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 353: ...ces createGatewayConnection gatewayConnection setCredentials userID password myService gatewayConnection getService securityTest thecfc this For more information on using Flash Remoting see Using the...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 653: ...e File userDirectory resolvePath customerManger db dbDir File applicationStorageDirectory var keyGenerator EncryptionKeyGenerator new EncryptionKeyGenerator var encryptionKey ByteArray keyGenerator ge...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 801: ...ibute1 value columns rows row column1Name row1Column1Value column1Name column2Name row1Column2Value column2Name row row column1Name row2Column1Value column1Name column2Name row2Column2Value column2Nam...

Страница 802: ...gt notsupported picturebar false picturebar insertbutton insert insertbutton deletebutton delete deletebutton sortAscendingButton SortAsc sortAscendingButton sortDescendingButton SortDesc sortDescendi...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 917: ...name doResourceFilter returntype void cfargument name resourceRequest cfargument name resourceResponse cfargument name filterChain cflog file portlet filter type information text doResourceFilter invo...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 966: ...mage IsImageFile GetReadableImageFormats GetWriteableImageFormats Retrieving image information ImageGetEXIFTag ImageGetHeight ImageGetIPTCTag ImageGetWidth ImageInfo Reading writing and converting ima...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 1305: ...ent originatorID cfset retValue structNew cfset retValue command submit cfset retValue sourceAddress arguments CFEVENT gatewayid cfset retValue destAddress arguments CFEVENT originatorid cfset retValu...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Страница 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...

Отзывы: