background image

718

Chapter 32:  Using Web Services

Handling inout and out parameters

Some web services define inout and out parameters. You use 

out

 parameters to pass a placeholder 

for a return value to a web service. The web service then returns its result by writing it to the out 
parameter. 

Inout

 parameters let you pass a value to a web service and lets the web service return its 

result by overwriting the parameter value. 

The following example shows a web service that takes as input an inout parameter containing a 
string and writes its results back to the string: 

<cfset S="foo">
<cfscript>

ws=createobject("webservice", "

URLtoWSDL

")

ws.modifyString("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 pound signs. 

Note: 

ColdFusion MX supports the use of inout and out parameters to consume web services. 

However, ColdFusion MX does not support inout and out parameters when creating web services for 
publication. 

Configuring web services in the ColdFusion MX Administrator

The ColdFusion MX Administrator lets you register web services so that you do not have to 
specify the entire WSDL URL when you reference the web service. 

Note: 

The first time you reference a web service, ColdFusion MX automatically registers it in the 

Administrator. 

For example, the following code references the URL to the BabelFish WSDL file:

<cfscript>

ws = CreateObject("webservice",

"http://www.xmethods.net/sd/2001/BabelFishService.wsdl"

);

xlatstring = ws.BabelFish("en_es", "Hello world, friend");
writeoutput(xlatstring);

</cfscript>

If you register the BabelFish web service in the Administrator using, for example, the name 
wsBabel, you could then reference the web service as follows:

<cfscript>

ws =

 CreateObject("webservice", "wsBabel");

xlatstring = ws.BabelFish("en_es", "Hello world, friend");
writeoutput(xlatstring);

</cfscript>

Not only does this enable you to shorten your code, registering a web service in the Administrator 
lets you change a web service’s URL without modifying your code. So, if the BabelFish web 
service moves to a new location, you only update the administrator setting, not your application 
code. 

For more information, see the ColdFusion MX Administrator online Help. 

Summary of Contents for ColdFusion MX

Page 1: ...Developing ColdFusion MX Applications...

Page 2: ...dia Inc or other entities and may be registered in certain jurisdictions including internationally This product includes code licensed from RSA Data Security This guide contains links to third party w...

Page 3: ...Markup Language 30 ColdFusion application services 32 ColdFusion MX Administrator 32 Using ColdFusion MX with Macromedia Flash MX 32 About J2EE and the ColdFusion architecture 33 About ColdFusion MX...

Page 4: ...ypes 61 Using periods in variable references 64 Understanding variables and periods 65 Creating variables with periods 66 Data type conversion 67 Operation driven evaluation 67 Conversion between type...

Page 5: ...g Arrays and Structures 103 About arrays 104 Basic array concepts 104 About ColdFusion arrays 104 Basic array techniques 106 Referencing array elements 106 Creating arrays 106 Adding elements to an ar...

Page 6: ...ling exceptions 139 CFScript example 140 CHAPTER 7 Using Regular Expressions in Functions 143 About regular expressions 144 Using ColdFusion regular expression functions 144 Basic regular expression s...

Page 7: ...more information 171 Selecting among ColdFusion code reuse methods 171 CHAPTER 9 Creating and Using Custom CFML Tags 173 Creating custom tags 174 Creating and calling custom tags 174 Securing custom...

Page 8: ...les and constants 208 Using function names as function arguments 208 Handling query results using UDFs 208 Identifying and checking for UDFs 209 Using the Evaluate function 210 Passing complex data 21...

Page 9: ...ing C CFX tags 262 Locating your C library files on UNIX 262 Implementing C CFX tags 262 Debugging C CFX tags 262 Registering CFX tags 263 PART III Developing CFML Applications CHAPTER 13 Designing an...

Page 10: ...r application page 295 Logging errors with the cflog tag 297 Handling runtime exceptions with ColdFusion tags 299 Exception handling tags 299 Using cftry and cfcatch tags 299 Using cftry an example 30...

Page 11: ...Using ColdFusion security tags and functions 352 Using the cflogin tag 353 Getting the user ID and password 353 Logging a user in using Flash Remoting 354 Logging users out 354 Security scenarios 355...

Page 12: ...g Applications 389 Configuring debugging in the ColdFusion MX Administrator 390 Debugging Settings page 390 Debugging IP addresses page 392 Using debugging information from browser pages 392 General d...

Page 13: ...with dynamic data 428 Retrieving data 428 The cfquery tag 429 The cfquery tag syntax 429 Building queries 430 Outputting query data 431 Query output notes and considerations 433 Getting information ab...

Page 14: ...ates 473 Understanding Query of Queries performance 473 BNF for Query of Queries 474 CHAPTER 23 Managing LDAP Directories 477 About LDAP 478 The LDAP information structure 479 Entry 480 Attribute 480...

Page 15: ...Using Verity Search Expressions 535 About Verity query types 536 Using simple queries 536 Stemming in simple queries 537 Preventing stemming 538 Using explicit queries 539 Using AND OR and NOT 539 Us...

Page 16: ...ols 584 Preserving input data with preservedata 585 Browser considerations 585 Building tree controls with cftree 586 Grouping output from a query 587 The cftree form variables 589 Input validation 58...

Page 17: ...641 About using the Flash Remoting service with ColdFusion 642 Planning your Flash application 642 Using the Flash Remoting service with ColdFusion pages 643 Using Flash with ColdFusion components 646...

Page 18: ...1 Basic view 671 DOM node view 672 XML document structures 673 ColdFusion XML tag and functions 676 Using an XML object 677 Referencing the contents of an XML object 677 Assigning data to an XML objec...

Page 19: ...ient 717 Catching errors when consuming web services 717 Handling inout and out parameters 718 Configuring web services in the ColdFusion MX Administrator 718 Data conversions between ColdFusion and W...

Page 20: ...OM and CORBA 762 About objects 762 About COM and DCOM 762 About CORBA 762 Creating and using objects 763 Creating objects 763 Using properties 763 Calling methods 764 Calling nested objects 764 Gettin...

Page 21: ...g cfpop 797 The cfpop query variables 798 Handling POP mail 798 CHAPTER 36 Interacting with Remote Servers 807 About interacting with remote servers 808 Using cfhttp to interact with the web 808 Using...

Page 22: ...22 Contents...

Page 23: ...des a solid grounding in the tools that ColdFusion MX provides to develop web applications Because of the power and flexibility of ColdFusion MX you can create many different types of web applications...

Page 24: ...g variables expressions dynamic code CFScript and regular expressions Reusing CFML Code Techniques for writing code once and using it many times including the cfinclude tag user defined functions cust...

Page 25: ...ou can then read the remaining chapters as you add new features to your ColdFusion application Developing an in depth knowledge of ColdFusion If you have a basic understanding of ColdFusion as present...

Page 26: ...cumentation set includes the following titles Viewing online documentation All ColdFusion MX documentation is available online in HTML and Adobe Acrobat Portable Document Format PDF files Go to the do...

Page 27: ...cluding Macromedia Flash MX based applications This chapter also introduces the topics discussed in this book Contents About Internet applications and web application servers 28 About ColdFusion MX 30...

Page 28: ...such as XML web services J2EE Java 2 Platform Enterprise Edition and Microsoft NET the Internet has become a multifaceted tool for integrating business activities Now enterprises can use the Internet...

Page 29: ...e browser If the user requests a file that is a page that a web application server must process one with a CFM CFML or CFC extension for ColdFusion requests the web server passes the request to the we...

Page 30: ...Language ColdFusion Markup Language CFML is a tag based language similar to HTML that uses special tags and functions With CFML you can enhance standard HTML files with database commands conditional...

Page 31: ...features let you easily create reusable functionality that is customized to the types of applications or websites that you are building CFML development tools Macromedia Dreamweaver MX helps you devel...

Page 32: ...ash MX clients ColdFusion MX Administrator ColdFusion MX Administrator configures and manages the ColdFusion application server It is a secure web based application that you can access using any web b...

Page 33: ...m functionality across multiple operating systems About ColdFusion MX and the J2EE platform ColdFusion MX is implemented on the Java technology platform and uses a J2EE application server for many of...

Page 34: ...eate custom ColdFusion tags using CFML These tags can have bodies and can call other custom tags 9 User defined functions UDFs You can use CFScript or the cffunction tag to create your own functions T...

Page 35: ...text search capabilities for documents and data sources using the Verity search engine 24 25 Dynamic forms With ColdFusion you can use HTML and forms to control the data displayed by a dynamic web pag...

Page 36: ...ages You can add interactive e mail features to your ColdFusion applications using the cfmail and cfpop tags 35 HTTP and FTP The cfhttp and cfftp tags provide simple methods of using HTTP Hypertext Tr...

Page 37: ...CFScript scripting language and regular expressions The following chapters are included Chapter 2 Elements of CFML 39 Chapter 3 Using ColdFusion Variables 53 Chapter 4 Using Expressions and Pound Sig...

Page 38: ......

Page 39: ...variables expressions and CFScript The chapters in Part I of this book describe these topics in detail Contents Introduction 40 Character case 40 Tags 40 Functions 42 Expressions 43 Constants 44 Vari...

Page 40: ...epresent the cfset tag cfset CFSET CFSet and even cfsEt However you should get in the habit of consistently using the same case rules in your programs for example Develop consistent rules for case use...

Page 41: ...ocessing ColdFusion pages Managing the CFML application framework Manipulating files and directories Using external tools and objects including Verity collections COM Java and CORBA objects and execut...

Page 42: ...tform specific for example if they take advantage of COM objects or the Windows API For more information on CFX tags see Chapter 12 Building Custom CFXAPI Tags on page 251 Functions Functions typicall...

Page 43: ...he 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 mathematical routines such as a f...

Page 44: ...es Data types on page 45 lists data types which also apply to constant values For detailed information on ColdFusion variables including data types scopes and their use see Chapter 3 Using ColdFusion...

Page 45: ...ibute specifies the application name Server Variables that are associated with the current ColdFusion server This scope lets you define variables that are available to all your ColdFusion pages across...

Page 46: ...hin a language CFScript is a scripting language that is similar to JavaScript but is simpler to use Also unlike JavaScript CFScript only runs on the ColdFusion server it does not run on the client sys...

Page 47: ...ows 1 The cfif tag tests a condition and executes its body if the condition is True 2 If the preceding cfif or cfelseif test condition is False the cfelseif tag tests another condition and executes it...

Page 48: ...ch tag provides better performance than a cfif tag with multiple cfelseif tags and is easier to read Switch processing is commonly used when different actions are required based on a a string variable...

Page 49: ...on NOT foundit AND i LT ArrayLen myArray cfset i i 1 cfif myArray i IS kumquats cfset foundit True cfif cfloop cfoutput i is i br foundit is foundit br cfoutput Note You can get an infinite conditiona...

Page 50: ...t just tag bodies functions calls and variable text in pound signs ColdFusion ignores the text in comments such as the following cfset MyVar var1 var2 cfoutput Dateformat now dddd mmmm yyyy cfoutput T...

Page 51: ...tirely For a complete list of reserved words see CFML Reference Built in function names such as Now or Hash Scope names such as Form or Session Any name starting with cf However when you call a CFML c...

Page 52: ...52 Chapter 2 Elements of CFML...

Page 53: ...bes how to create and use ColdFusion variables It includes the following information How variables can represent different types of data How the data types get converted How variables exist in differe...

Page 54: ...iable name must begin with a letter underscore or Unicode currency symbol The initial character can by followed by any number of letters numbers underscore characters and Unicode currency symbols A va...

Page 55: ...n values and date time values Complex A container for data Generally represent more than one value ColdFusion built in complex data types include arrays structures queries and XML document objects You...

Page 56: ...IsNumeric ColdFusion does not use a null data type However if ColdFusion receives a null value from an external source such as a database a Java object or some other mechanism it maintains the null v...

Page 57: ...between a pair of single quotation marks with nothing in between Strings can be any length limited by the amount of available memory on the ColdFusion server There is however a 64K limit on the size o...

Page 58: ...s the empty element For 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 repres...

Page 59: ...rovides 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 locale identifies a language and locality s...

Page 60: ...es the data in the lowest six bits of each byte It ensures that binary data and non ANSI character data can be transmitted using e mail without corruption The MIME specification defines the Base64 enc...

Page 61: ...ray you can use functions or direct references to manipulate its contents When you assign an existing array to a new variable ColdFusion creates a new array and copies the old array s contents to the...

Page 62: ...s can be the names of complex data objects including structures or arrays This lets you create arbitrarily complex structures For more information on using structures see Chapter 5 Using Arrays and St...

Page 63: ...ect exists The following example shows how this works cfscript depts structnew cfscript cfset newStructure depts cfset depts John Sales cfset depts 0 cfoutput newStructure John br depts cfoutput This...

Page 64: ...lines print the word ben cfset myCol myQuery Firstname cfoutput mycol cfoutput But the following lines display an error message cfset myCol myQuery Firstname cfoutput mycol 1 cfoutput br If you refer...

Page 65: ...bject checks whether b is the name of a simple variable and returns the value of b If myVar is a complex object but a is not a complex object checks whether a b is the name of a simple variable and re...

Page 66: ...var Client myVar a b Creating variables with periods You should avoid creating the names of simple variables including arrays that include periods However ColdFusion provides mechanisms for handling...

Page 67: ...types to ensure error free program execution For example the previous expression might have to be written as ToNumber 8 10 In ColdFusion however the expression 8 10 evaluates to the number 80 without...

Page 68: ...lse FALSE and false are equivalent No NO and no are equivalent and True TRUE and true are equivalent Value As Boolean As number As date time As string Yes True 1 Error Yes No False 0 Error No True Tru...

Page 69: ...ion function The Int Round Fix and Ceiling functions convert real numbers to integers and differ in their treatment of the fractional part of the number If you use a hidden form field with a name that...

Page 70: ...number or date time value which is stored as a number It then uses the number in the expression Short strings such as 1a and 2P can produce unexpected results ColdFusion can interpret a single a as A...

Page 71: ...to use based on the types of the parameters passed in the call Because ColdFusion does not use explicit types you cannot predict which version of the method the virtual machine will use The ColdFusion...

Page 72: ...in your code where they are meaningful and how long their values persist These considerations are generally referred to as a variable s scope Commonly used scopes include the Variables scope the defa...

Page 73: ...ts and indicate whether the tag has an end tag A nested custom tag can use the cfassociate tag to return values to the calling tag s ThisTag scope For more information see Accessing tag instance data...

Page 74: ...able to all your ColdFusion pages across multiple applications For more information see Chapter 15 Using Persistent Data and Locking on page 315 Flash Variables sent by a Macromedia Flash movie to Col...

Page 75: ...f the form field URL No On the target page of the URL The system Contains the parameters passed in the URL query string used to access the page Attributes Yes On the custom tag page The calling page p...

Page 76: ...the prefix Server when you create the variable Flash Yes A ColdFusion page or ColdFusion component called by a Flash client The ColdFusion Client access You assign a value to Flash You can assign valu...

Page 77: ...and Response interfaces or the C Request class to get and return data The Java setVariable Response interface method and C CCFX SetVariable method return data to the Variables scope of the calling pag...

Page 78: ...s works cffunction name TestFunction cfparam name This foo default Original This foo dumping This inside the function br cfdump var This cffunction First just call the function br cfset TestFunction R...

Page 79: ...pages Variable existence considerations If a variable is part of a scope that is available as a structure you might get a minor performance increase by testing the variable s existence using the Stru...

Page 80: ...y default ColdFusion displays an error message you can also handle the error as described in Chapter 14 Handling Errors on page 285 Example setting default values The following example uses the cfpara...

Page 81: ...pecify that the parameter type must be any of the following values For example you can use the following code to validate the variable BirthDate cfparam name BirthDate type date If the variable is not...

Page 82: ...age s data changes to the variable in the custom tag or function do not change the value of the variable on the calling page If the variable is passed by reference changes to the variable in the custo...

Page 83: ...te expressions It also describes the correct use of pound signs to indicate expressions in ColdFusion tags such as cfoutput in strings and in expressions Finally it describes how to use variables in v...

Page 84: ...erator is surrounded by expressions Each expression can be a simple operand variable or constant or a subexpression consisting of more operators and expressions Complex expressions are built up using...

Page 85: ...e For example True AND True is True but True AND False is False OR Return True if any of the arguments is True return False otherwise For example True OR False is True but False OR False is False XOR...

Page 86: ...aluates to True if B is a substring of A Therefore an expression such as the following evaluates as True 123 45 CONTAINS 3 4 When a ColdFusion decision operator compares strings it ignores the case As...

Page 87: ...r of evaluation you must 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 expr...

Page 88: ...explains why only the first occurrence of Eat was replaced with Drink in the first example In the second example a fourth argument causes the function to replace all occurrences of Eat with Drink Exp...

Page 89: ...n pound signs can contain nested functions such as Left trim myString position Do not put complex expressions such as 1 2 in pound signs Use pound signs only where necessary because unneeded pound sig...

Page 90: ...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 nk is Monk ColdFusion does not interpret the double poun...

Page 91: ...thout the nesting For example you can rewrite the preceding code example without the nested pound signs as follows cfset Sentence2 The length of the full name is Len FirstName LastName The following a...

Page 92: ...ic evaluation In a dynamic expression the actual expression not just its variable values is determined at execution time In other words in a dynamic expression the structure of the expression such as...

Page 93: ...opping cart on page 99 This does not mean that you must always avoid dynamic evaluation However given the substantial performance costs of dynamic evaluation you should first ensure that one of the fo...

Page 94: ...pression inside the index brackets For example if you have a productName structure with keys of the form product_1 product_2 and so on you can use the following code to display the value of productNam...

Page 95: ...e Evaluate function takes one or more string expressions dynamically evaluates their contents as expressions from left to right and returns the result of evaluating the rightmost argument The followin...

Page 96: ...t myVar2 myVar 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 Evaluat...

Page 97: ...e variable product_1 and generates an executable representation of the variable Because ColdFusion must invoke its parser this step requires substantial processing even for a simple variable 4 Evaluat...

Page 98: ...n requires the DE function to prevent ColdFusion from evaluating literal strings as the following example shows cfoutput IIf IsDefined LocalVar LocalVar DE The variable is not defined cfoutput If you...

Page 99: ...owing example shows the shopping cart contents and lets you edit your order and submit it To simplify things the example automatically generates the shopping cart contents using CFScript instead of ha...

Page 100: ...s 4 Cart ArrayNew 1 for i 1 i LE cartItems i i 1 Cart i StructNew Cart i ID i Cart i Name Product i Cart i SKU i 100 2 i 10 3 i Cart i Qty 3 i 2 cfscript Create a shopping cart as an array of structur...

Page 101: ...t i Name passThrough readonly True td td cfinput type text name skuName value Cart i SKU passThrough readonly True td td cfinput type text name qtyName value Cart i Qty td tr cfloop table Loop through...

Page 102: ...s br br cfloop index i list Form itemID ProductName Form product_ i br Product Code Form sku_ i br Quantity Form qty_ i br br cfloop cfoutput cfif Display the name SKU number and quantity for each ord...

Page 103: ...s structures for managing lists of key value pairs Because structures can contain other structures or complex data types as it values they provide a flexible and powerful tool for managing complex dat...

Page 104: ...ble name and a numerical index The index number references a single entry or cell in the array as the following figure shows Thus the following statement sets the value of the fifth entry in the one d...

Page 105: ...ay A ColdFusion 2D array is actually a one dimensional array that contains a series of additional 1D arrays Each of the arrays that make up a row can expand and contract independently of any other col...

Page 106: ...k and use a catch block to handle exceptions that arise if elements do not exist Creating arrays In ColdFusion you declare an array by assigning a variable name to the new array and specifying its dim...

Page 107: ...D array a 2D array and a 3D array cfset biggerarray 1 1 1 myarray cfset biggerarray 1 1 1 10 3 Make element 1 1 1 of the 3D biggerarray array be a copy of the 1D array Assign 3 to the 1 1 1 10 element...

Page 108: ...cfset myarray 4 4 cfoutput myarray4 myarray 4 br myarray3 myarray 3 br cfoutput Adding an array element with a function You can use the following array functions to add data to an array Because ColdF...

Page 109: ...able name You do not have to use ArrayNew to create the new array first When you assign the existing array to a new variable ColdFusion creates a new array and copies the old array s contents to the n...

Page 110: ...tag Populating an array from a query The following sections describe these techniques Populating an array with the ArraySet function You can use the ArraySet function to populate a 1D array or one di...

Page 111: ...et my2darray arraynew 2 cfloop index loopcount from 1 to 12 cfloop index loopcount2 from 1 to 2 cfset my2darray loopcount loopcount2 loopcount loopcount2 cfloop cfloop p The values in my2darray are cu...

Page 112: ...ex queryColumn row In the following example a cfloop tag places four columns of data from a sample data source into an array myarray Do the query cfquery name test datasource cfsnippets SELECT Emp_ID...

Page 113: ...ArrayDeleteAt Deletes an element from a specified array at the specified index and resizes the array ArrayInsertAt Inserts an element with data in a specified array at the specified index and resizes...

Page 114: ...lowing example shows various ways you can reference the contents of a complex structure cfset myArray ArrayNew 1 cfset myArray 1 2 cfset myArray 2 3 cfset myStruct2 StructNew cfset myStruct2 struct2ke...

Page 115: ...myArray ArrayNew 1 cfset myArray 1 2 cfset myArray 2 3 cfset myStruct2 StructNew cfset myStruct2 struct2key1 4 cfset myStruct2 struct2key2 5 cfset myStruct StructNew cfset myStruct key1 1 cfset myStr...

Page 116: ...to which you can add data Use this technique to create structures if your application must run on ColdFusion server versions 5 and earlier Value of the second entry in the key2 array br myStruct key2...

Page 117: ...Sales to Marketing It then uses associative array notation to change his department to Facilities Each time the department changes it displays the results cfset departments structnew cfset department...

Page 118: ...s a matching key it displays the Last Name from the query and the corresponding entry in the structure cfloop query GetEmployees cfif StructKeyExists myStruct LastName cfoutput LastName mystruct LastN...

Page 119: ...nges to one copy of the structure have no effect on the other structure This function is useful when you want to move a structure completely into a new scope In particular if a structure is created in...

Page 120: ...al structure br cfdump var myNewStructure br Copied structure br cfdump var CopiedStruct br Duplicated structure br cfdump var DupStruct br Structure reference cfdump var structRef br br Change a stri...

Page 121: ...ucture that has a multiple references the function deletes the contents of the structure and all references point to the empty structure as shown in the following example cfset myStruct Key1 Macromedi...

Page 122: ...m firstname default cfparam name Form lastname default cfparam name Form email default cfparam name Form phone default cfparam name Form department default If at least the firstname form field is pass...

Page 123: ...isplayed and can be tested cfif form firstname eq Please fill out the form br Test the value of the form s firstname field This field is required The test is False the first time the page displays If...

Page 124: ...te cfoutput cf_addemployee empinfo duplicate employee cfif Call the cf_addemployee custom tag and pass it a copy of the employee structure in the empinfo attribute The duplicate function ensures that...

Page 125: ...t support automatic generation of the Emp_ID key you must add an Emp_ID entry to the form and add it to the query cfoutput hr Employee Add Complete cfoutput Display a completion message This code does...

Page 126: ...e a direct assignment statement this function generates an error by default if the specified key exists in the structure StructIsEmpty Indicates whether the specified structure contains data Returns T...

Page 127: ...rol flow as ColdFusion but without tags You can also use CFScript to write user defined functions that you can use anywhere that a ColdFusion expression is allowed This chapter describes the CFScript...

Page 128: ...n tags ColdFusion 5 and later releases let you use CFScript to create user defined functions or UDFs also known as custom functions You call UDFs in the same manner that you call standard ColdFusion f...

Page 129: ...script Variables CFScript variables can be of any ColdFusion type such as numbers strings arrays queries and objects The CFScript code can read and write any variables that are available in the page t...

Page 130: ...t statements are executed if the score is greater than 0 If they were not in the code block only the first line would execute You do not have to put brace characters on their own lines in the code For...

Page 131: ...CFScript uses ColdFusion expressions which are neither a subset nor a superset of JavaScript expressions For example there is no operator in CFScript you use the LT operator instead Variable declarati...

Page 132: ...nt StructInsert employee lastname FORM lastname Using conditional processing statements CFScript includes the following conditional processing statements if and else statements which serve the same pu...

Page 133: ...r each condition as follows if score GT 1 result positive message The result was positive else result negative message The result was negative Note Often you can make your code clearer by using braces...

Page 134: ...efault block code with a break statement The default statement is not required However you should use one if the case constants do not include all possible values of the expression The default stateme...

Page 135: ...curly braces When ColdFusion executes a for loop it does the following 1 Evaluates the initial expression 2 Evaluates the test expression 3 If the test expression is False exits the loop and processi...

Page 136: ...initialize it to 0 so it becomes 1 in the first loop Using while loops The while loop has the following format while expression statement The while statement does the following 1 Evaluates the expres...

Page 137: ...hat the index is less than 10 a ArrayNew 1 loop 0 do loop loop 1 a loop loop 5 while loop LT 10 using for in loops The for in loop loops over the elements in a ColdFusion structure It has the followin...

Page 138: ...create an array a with 10 or more elements some of which are not empty strings In general the continue statement is particularly useful if you loop over arrays or structures and you want to skip proce...

Page 139: ...ry block This structure differs from that of the cftry tag which must include the cfcatch tags in its body When you have a try statement you must have a catch statement In the catch block the exceptio...

Page 140: ...pplicants 1 Cora Cardozo acceptedApplicants 2 Betty Bethone acceptedApplicants 3 Albert Albertson rejectedApplicants 1 Erma Erp rejectedApplicants 2 David Dalhousie rejectedApplicants 3 Franny Farkle...

Page 141: ...codes for rejected applicants The rejectedCode structure does not have entries for all rejected applicants and one of its values does not match a valid code The structure element references use associ...

Page 142: ...that examines the rejection code value If the rejection code value matches one of the known codes displays an expanded explanation of the meaning Otherwise the default case displays an indication tha...

Page 143: ...ly to regular expressions used in the cfinput and cftextinput tags These tags use JavaScript regular expressions which have a slightly different syntax than ColdFusion regular expressions For informat...

Page 144: ...the string BIG and any string of uppercase letters enclosed in spaces By default the matching of regular expressions is case sensitive You can use the case insensitive functions REFindNoCase and RERep...

Page 145: ...turns 0 for the regular expression meaning that it did not find a match You can construct very complicated regular expressions containing literal characters character sets and special characters Like...

Page 146: ...e unexpected The workarounds for these types of problems are specific to each case In some cases you can use T which requires at least one T instead of T Alternatively you can specify an additional pa...

Page 147: ...All other combinations of case Using subexpressions Parentheses group parts of regular expressions together into grouped subexpressions that you can treat as a single unit For example the regular exp...

Page 148: ...lar expression the matched string must be at the beginning of the string being searched For example the regular expression ColdFusion matches the string ColdFusion lets you use regular expressions but...

Page 149: ...he character m does not affect A or Z which always match the start or end of the string respectively For information on A and Z see Using escape sequences on page 150 i If at the beginning of a regula...

Page 150: ...ad as specified by except that it tests for the absence of a match Lookahead parentheses do not capture text so backreference numbering will skip over these groups For more information on backreferenc...

Page 151: ...ses match any Unicode character in the class not just ASCII or ISO 8859 characters Z Specifies an end of string anchor much like the special character However unlike you cannot combine Z with m to spe...

Page 152: ...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 subexpression A Za z to search for character st...

Page 153: ...d pears 2 and 1 ALL In this example you reference the subexpression apples as 1 and the subexpression pears as 2 The REReplace function returns the string pears and apples pears and apples pears and a...

Page 154: ...en Bonjour Hi Hello and Bond using a nested group for alternating between Hi Hello cfset regex Bonjour H i ello Bond cfset replaceString 1 Mr 2 cfset string Hello Bond reReplace string regex replaceSt...

Page 155: ...d string For this example the index of the first BIG string is 5 and its length is also 5 If there are no occurrences of the regular expression the pos and len arrays each contain one element with a v...

Page 156: ...and sLenPos len 1 contain information about the match of the entire regular expression The array elements sLenPos pos 2 and sLenPos len 2 contain information about the first subexpression is Because...

Page 157: ...ng that match the regular expression This behavior is called maximal matching For example you use the regular expression b b to search the string b one b b two b The regular expression b b matches bot...

Page 158: ...b one b Regular expression examples The following examples show some regular expressions and describe what they match Expression Description minimal matching version of minimal matching version of mi...

Page 159: ...d modifiers i etc always affect the entire expression even if they are inside a group Q and the combinations u L and l U are not supported in replacement strings 1 9 0 9 E 0 9 A real number in enginee...

Page 160: ...s The following Perl statements are not supported Lookbehind x hhhh N p C An excellent reference on regular expressions is Mastering Regular Expressions by Jeffrey E F Friedl O Reilly Associates Inc 1...

Page 161: ...e the cfinclude tag user defined functions custom tags ColdFusion components and ColdFusion Extension CFX tags The following chapters are included Chapter 8 Reusing Code in ColdFusion Pages 163 Chapte...

Page 162: ......

Page 163: ...opying it in many places This chapter describes the techniques and their features and provides advice on selecting among the techniques Contents About reusable CFML elements 164 Including pages with t...

Page 164: ...ts including objects in the Java runtime environment and JavaBeans For information on using Java objects see Chapter 33 Integrating J2EE and Java Elements in CFML Applications on page 735 Microsoft CO...

Page 165: ...open a cfoutput block in a ColdFusion page you must 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 f...

Page 166: ...t you cannot include CFML tags You use UDFs in your application pages as you use standard ColdFusion functions You can create a function for an algorithm or procedure that you use frequently and then...

Page 167: ...ter 10 Writing and Calling User Defined Functions on page 191 Using custom CFML tags Custom tags written in CFML behave like ColdFusion tags They can do all of the following Take arguments Have tag bo...

Page 168: ...w of ColdFusion processing the pages Calling custom CFML tags Unlike built in tags you can invoke custom CFML tags in the following three ways Call a tag directly Call a tag using the cfmodule tag Use...

Page 169: ...a convenient form to others If you can create either a UDF or a custom CFML tag for a purpose first consider creating a UDF because invoking it requires less system overhead than using a custom tag F...

Page 170: ...ge 251 Using ColdFusion components Unlike other Coldfusion reusable elements ColdFusion components encapsulate multiple related functions A ColdFusion component is essentially a set of related UDFs an...

Page 171: ...to consider for each purpose The letter P indicates that the method is preferred There can be more than one preferred method The letter A means that the method provides an alternative that might be u...

Page 172: ...accessibility from Flash clients A A P Use built in user security features A P Encapsulate multiple related functions and properties P Create web services P Implement object oriented coding methodolo...

Page 173: ...FML Tags This chapter describes how to create and use custom CFML tags that encapsulate common code Contents Creating custom tags 174 Passing data to custom tags 177 Managing custom tags 181 Executing...

Page 174: ...Cantor s Birthday Please wish him well A custom tag can also have a body and end tag for example cf_happybirthdayMessge name Ellen Smith birthDate June 8 1993 P Happy Birthday Ellen P P May you have m...

Page 175: ...g subdirectories until the custom tag is found You might have a situation where you have multiple custom tags with the same name To guarantee which tag ColdFusion calls copy it to the same directory a...

Page 176: ...mytags custom_tag_name ColdFusion calls the custom tag page twice for a tag that includes an end tag once for the start tag and once for the end tag For more information on how ColdFusion handles end...

Page 177: ...o them for processing This section describes how to write custom tags that take tag attributes and other data as input from a calling page Passing values to and from custom tags Because custom tags ar...

Page 178: ...s results using the following code cfset Caller Attributes resultName result Tip Be careful not to overwrite variables in the calling page from the custom tag You should adopt a naming convention to m...

Page 179: ...butes The example in this section creates a custom tag that uses an attribute that is passed to it to set the value of a variable called Doctor on the calling page To create a custom tag 1 Create a ne...

Page 180: ...ttributes Department_number Note You can use both tag attributes and attributecollections If you pass an attribute with the same name using both methods ColdFusion passes only the tag attribute to the...

Page 181: ...ond For example you call a custom tag with the following code cf_first attr1 foo attr2 bar To pass all the attributes of the first custom tag to the second you include the following statement in first...

Page 182: ...t filename a warning message asks if you want to continue and the encoded file will overwrite the source file r Recursive when used with wildcards recurses through subdirectories to encode files q Sup...

Page 183: ...on will also call the custom tag page twice if you use the shorthand form of an end tag cf_date You can also call a custom tag using the cfmodule tag as shown in the following example cfmodule cfmodul...

Page 184: ...h expression thisTag 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...

Page 185: ...the body of a custom tag This includes all text and HTML code in the body the results of evaluating ColdFusion variables expressions and functions and the results generated by descendant tags Any chan...

Page 186: ...ing table lists the terms that describe the relationships between nested tags You can create multiple levels of nested tags In this case the sub tag becomes the base tag for its own sub tags Any tag w...

Page 187: ...le developers to obtain maximum productivity in an environment with few restrictions CFML custom tags can expose all their data to collaborating tags When you develop custom tags you should document a...

Page 188: ...cestor tag such as cfhttp cfhttpparam and cftree cftreeitem You can use the cfassociate tag to encapsulate this processing The cfassociate tag has the following format cfassociate baseTag tagName data...

Page 189: ...is called for a top level tag it returns an empty string GetBaseTagData TagName InstanceNumber 1 Returns an object that contains all the variables not just the local variables of the nth ancestor with...

Page 190: ...Determine whether you are nested inside a custom tag Skip the first element of the ancestor list i e the name of the custom tag I m in cfset incustomtag cfloop index elem list listrest ancestorlist cf...

Page 191: ...ribes how to create and call user defined functions UDFs Contents About user defined functions 192 Calling user defined functions 192 Creating user defined functions 193 Calling functions and using va...

Page 192: ...w cflib org is an open source collection of CFML user defined functions To use a user defined function you define the function and then call it Typically you define the function on your ColdFusion pag...

Page 193: ...urn 2 exponent cfscript For more information on how to use CFScript to define a function see Defining functions in CFScript on page 198 Creating functions using tags You use the cffunction tag to defi...

Page 194: ...ons on a single page and place a cfinclude tag at the top of pages that use the functions On any page that puts the function name in a scope common with the page on which you call the function On the...

Page 195: ...pass the function a value for each argument declared in the function definition Therefore the Arguments scope for a CFScript call does not have empty slots The following example shows these rules Ass...

Page 196: ...this manner is not good programming practice because you cannot ensure that you always use the same optional argument names when calling the function To demonstrate these rules define a simple functi...

Page 197: ...cified in the function call For example if you have an unnamed optional argument and call the function using the name myOptArg for the argument you can refer to the argument as Arguments myOptArg in t...

Page 198: ...he number of arguments in the parentheses at the start of the function definition If the calling page omits any of the required arguments ColdFusion generates a mismatched argument count error Stateme...

Page 199: ...e the Arguments scope to retrieve the optional arguments For example the following SumN function adds two or more numbers together It requires two arguments and supports any number of additional optio...

Page 200: ...tionName returnType type roles roleList access accessType output Boolean cfargument name argumentName Type type required Boolean default defaultValue Function body code cfreturn expression cffunction...

Page 201: ...y True or yes the body of the function is processed as if it were in a cfoutput tag ColdFusion displays variable values and expression results if you surround the variables and expressions with pound...

Page 202: ...er to the arguments directly by name if all arguments are named in the cfargument tags If you do use the Arguments scope identifier follow the rules listed in About the Arguments scope on page 194 Cal...

Page 203: ...wing Use a shared scope variable such as an Application or Session scope counter variable Use the Request scope to store variables used in the function as shown in Using the Request scope for static v...

Page 204: ...hat using variables from other scopes directly in your code is often poor practice A User defined function example The following simple function takes a principal amount an annual percentage rate and...

Page 205: ...te and the loan duration in months Var years 0 Var interestRate 0 Var totalInterest 0 Declares intermediate variables used in the function and initializes them to 0 All var statements must precede the...

Page 206: ...inition page in any page that calls the UDFs The next section describes other techniques for making UDFs available to your ColdFusion pages Specifying the scope of a function User defined function nam...

Page 207: ...ions Application Makes the function available across all invocations of the application Unlike with functions defined in Application cfm or included from other ColdFusion pages all pages use the same...

Page 208: ...nction names as function arguments Because function names are ColdFusion variables you can pass a function s name as an argument to another function This technique allows a function to use another fun...

Page 209: ...n argument function UCaseColumn myquery colName var currentRow 1 for currentRow lte myquery RecordCount currentRow currentRow 1 myquery colName currentRow UCase myquery colName currentRow Return The f...

Page 210: ...t of calling readname with myname is readname myname br This one finds the name passed in The result of calling readname with Variables myname is readname Variables myname cfoutput Passing complex dat...

Page 211: ...function returns This is inefficient for large arrays and can reduce performance particularly if the function is called frequently You can use the return value of other purposes such as a status varia...

Page 212: ...e result Therefore the function keeps calling itself until the factor is reduced to 1 The final recursive call returns 1 and the preceding call returns 2 1 and so on until all the initial call returns...

Page 213: ...Submit name submit value OK cfform Creates a simple form requesting you to enter your name Uses the script_name CGI variable to post to this page without specifying a URL If you do not enter a name th...

Page 214: ...and each has advantages and disadvantages Which technique you use should depend on the type of function the application in which you use it and your coding style The following example which modifies t...

Page 215: ...The following table describes the code that has been changed or added Code Description function TotalInterest principal annualPercent months status The function now takes an additional argument a sta...

Page 216: ...plication data For example the application should prevent users from entering a zero value for a form field that is used to divide another number rather than handling exceptions generated by dividing...

Page 217: ...t name principal required Yes cfargument name annualPercent required Yes cfargument name months required Yes cfset principal trim principal cfset principal REReplace principal ALL cfset annualPercent...

Page 218: ...218 Chapter 10 Writing and Calling User Defined Functions...

Page 219: ...sh applications This chapter describes CFC concepts and elements and tells you how to use and create CFCs It provides you with all the tools required to create and use CFCs It does not discuss CFC met...

Page 220: ...oriented features and let you use object oriented concepts and structures in your programming CFC object oriented features are similar to some of the object oriented elements that are in Netscape Jav...

Page 221: ...CFCs automatically provide Later sections describe these features in detail The ability to group related functions into a single component and to group related components into a package Properties th...

Page 222: ...Clients can directly call CFC methods using a URL or by submitting form fields In these cases the CFC method is responsible for generating all HTML that is returned to the client ColdFusion component...

Page 223: ...ubject variable and one method helloSubject cfcomponent cfset subject world cffunction name helloSubject cfreturn Hello subject cffunction cfcomponent CFC invocation and instantiation There are two wa...

Page 224: ...omponent defined in myApp cfcs myComponent cfc ColdFusion uses the following rules to find the specified CFC If you use a cfinvoke or cfobject tag or the CreateObject function to access the CFC from a...

Page 225: ...s the cfobject tag to instantiate the same component in CFScript tellTimeComp CreateObject component tellTime CFC invocation techniques There are many ways to invoke or call CFC methods The following...

Page 226: ...nt method using the cfinvoke tag 1 Create the following component and save it as tellTime cfc cfcomponent cffunction name getLocalTime cfoutput TimeFormat now cfoutput cffunction cfcomponent The examp...

Page 227: ...llTime2 name tellTimeComp Invoke the methods cfinvoke component tellTimeComp method getLocalTime returnvariable localTime cfinvoke component tellTimeComp method getUTCTime returnvariable UTCTime Displ...

Page 228: ...ss parameters in the cfinvoke tag as tag attribute name value pairs as the following example shows cfinvoke component authQuery method getAuthSecure lastName session username password url password In...

Page 229: ...that you can use ColdFusion functions You can also access data in the component s This scope directly in CFScript and cfset assignment statements For example if a User data CFC has a This lastUpdated...

Page 230: ...orized securityCFC getAuth name Almonzo Password LauRa123 You can pass the parameters in an argumentsCollection structure The following code is equivalent to the previous example argsColl structNew ar...

Page 231: ...the client Invoking component methods using a form To invoke a method using a ColdFusion or HTML form the following must be true The form or cfform tag action attribute must specify the CFC filename o...

Page 232: ...emoting MX Flash applications that use Flash Remoting MX can access CFC methods by using the CFC path as the service name in a NetServices gatewayConnection getServices method You then call the CFC me...

Page 233: ...owser without specifying a component method the following chain of events occurs 1 The request is redirected to CFCExplorer cfc which is located in the webroot CFIDE componentutils directory 2 The CFC...

Page 234: ...access the component browser using a web server virtual directory the CFIDE virtual directory must be mapped to the same physical location in the web server and on the Mappings page in the ColdFusion...

Page 235: ...g how to use component tags and how to specify metadata only attributes see Documenting CFCs on page 240 Building ColdFusion components You use the cfcomponent and cffunction tags to create ColdFusion...

Page 236: ...parent component s constructor code executes before the child component s constructor code Note ColdFusion does not require you to put the initialization code at the top of the component definition ho...

Page 237: ...age that invokes it the cfreturn tag must be on the component definition page it cannot be on the included page To create component method using the cfinclude tag 1 Create a tellTime cfc file with the...

Page 238: ...ng practice to identify the scope Also you can use Array or structure like notation which lets you loop over multiple parameters For more information on the Arguments scope see The Arguments scope on...

Page 239: ...hat display output directly are designed as modular units for generating output and do not do business logic Displaying output If you do not specifically suppress output any text HTML code or output t...

Page 240: ...ttributes The displayname attribute is lets you provide a more descriptive name for a component attribute function or property When you use introspection this attribute appears in parentheses next to...

Page 241: ...d cfproperty tag attributes Note The cfproperty tag does not create a variable or assign it a value It is used for information purposes only You use a cfset tag or CFScript assignment statement to cre...

Page 242: ...on page that instantiates the CFC could refer to the component s color property as car color Variable values in the This scope last as long as the CFC instance exists and therefore can persist between...

Page 243: ...plays the value returned by the greetMe CFC 5 Displays the Variables MyName value The greetme cfc component does the following 1 Gets the calling page s Variables scope as the Vscope parameter 2 Chang...

Page 244: ...nd the function has data that must be freed when the function exits Local variables do not last between calls to CFC methods These variables are available to pages included by the method Other variabl...

Page 245: ...parent component CFC B is called the the sub or child component Note When you use a component that extends another component the This scope is not available in the base parent component Therefore any...

Page 246: ...extends CFC A and CFC B overrides some of the methods in CFC A CFC B can use the original versions of the overridden methods as defined in CFC A by prefixing the method name with Super For example as...

Page 247: ...me cfc and getUTCTime cfm files that you created in the Defining component methods section to the components directory 4 Create a ColdFusion page with the following content and save it in your web roo...

Page 248: ...er e mail address and billing and shipping addresses The CFC also includes methods for managing the user a login method a method that populates the object s properties from a database and so on Buildi...

Page 249: ...gged in with one of the specified roles can execute the function cffunction name foo roles admin moderator When a user tries to invoke a method that he or she is not authorized to invoke an exception...

Page 250: ...250 Chapter 11 Building and Using ColdFusion Components...

Page 251: ...ng Or you have existing code that 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 E...

Page 252: ...on page 163 Before you begin developing CFX tags in Java Before you begin developing CFX tags in Java you must configure your Java development environment Also you might want to take a look at some ex...

Page 253: ...pports a feature that reloads Java CFX tags located in the directory every time they are changed Although this is not the default behavior for other Java classes this behavior is very useful during an...

Page 254: ...compilation check the source code to make sure you entered it correctly If no errors occur you successfully wrote your first Java CFX tag For information on using your new tag in a ColdFusion page see...

Page 255: ...at need to work with ColdFusion queries also interface with the Query object The com allaire cfx package located in the lib cfx jar archive contains the Request Response and Query objects This section...

Page 256: ...the web server and other servlet engines and is required in order to implement automatic class reloading However this behavior can cause subtle problems when you are attempting to perform casts on ins...

Page 257: ...at all accesses to the data are thread safe ZipBrowser example The following example shows the use of the Request Response and Query objects The example uses the java util zip package to implement a J...

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

Page 259: ...nology to develop for the platform If you need to debug a Java CFX tag while running against a live production server this is the technique you must use In addition to outputting debugging text using...

Page 260: ...for your Java CFX class 2 Within the main method initialize a DebugRequest and DebugResponse and a DebugQuery Use the appropriate attributes and data for your test 3 Create an instance of your Java C...

Page 261: ...e as follows CFX_DIRECTORYLIST Queries a directory for the list of files it contains CFX_NTUSERDB Windows NT only Lets you add and delete Windows NT users On Windows NT these tags are located in the c...

Page 262: ...et the custom tag accomplish its work For information about the CFX API classes and members see Chapter 4 ColdFusion C CFX Reference in CFML Reference Debugging C CFX tags After you configure a debugg...

Page 263: ...er 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 performance when the tag is ready for pr...

Page 264: ...264 Chapter 12 Building Custom CFXAPI Tags...

Page 265: ...secure your application It also describes how to create a globalized application and debug and troubleshoot application problems The following chapters are included Chapter 13 Designing and Optimizin...

Page 266: ......

Page 267: ...application elements describes how you can structure an application on your server and provides detailed information on using the Application cfm file It also describes coding methods for optimizing a...

Page 268: ...share a common look and feel often enforced by using common code elements such as the same header and footer pages and a common error message template This chapter describes the tools that ColdFusion...

Page 269: ...stants and application specific custom error pages When defined and set on the Application cfm page they are available on all pages in the application ColdFusion applications can have application leve...

Page 270: ...an authentication login mechanism and a role based authorization mechanism to ensure that users can only access and use selected features of the application User security also incorporates a user ID...

Page 271: ...code on an application page an OnRequestEnd cfm page runs if it exists after each application page in the same application The OnRequestEnd cfm page must be in the same directory as the Application cf...

Page 272: ...cfm file installed in the application root directory to process all application page requests In the example on the right Bandwidth Associates uses the settings in individual Application cfm files to...

Page 273: ...on or Session scope data with existing JSP pages and servlets You cannot have more than one unnamed application on a server For more information on using unnamed applications see Chapter 33 Integratin...

Page 274: ...er logins see Chapter 16 Securing Applications on page 345 Handling errors You can use the cferror tag on your Application cfm page to specify application specific error handling pages for request val...

Page 275: ...ication cferror type request template requesterr cfm mailto admin company com cferror type validation template validationerr cfm Set the Application variables if they aren t defined Initialize local a...

Page 276: ...rr cfm Specifies custom error handlers for request and validation errors encountered in the application Specifies the mailing address for use in the request error handler cfset app_is_initialized Fals...

Page 277: ...age in the application it does all the business logic and display processing required to produce the report or generate and display the list If the results change infrequently this can be an inefficie...

Page 278: ...automatically flushes any cached page if you change the code on the page It also automatically flushes pages after the expiration timespan passes You can use the cfcache tag with the action flush attr...

Page 279: ...to the shared scope variable The following example shows this technique It has two parts The first part welcomes the user and prints out a random lucky number This part runs and produces a different n...

Page 280: ...cached in the Application scope and sets a boolean flag variable with the result cfif not IsCached cfsavecontent variable ProductCache If the flag is False uses a cfsavecontent tag to save output in a...

Page 281: ...result stored procedures are faster than cfquery tags You use the cfprocparam tag to send parameters to the stored procedure and the cfproresult tag to get the record sets that the stored procedure re...

Page 282: ...hr br Record Count RS3 recordCount br Columns RS3 columnList br hr The return code for the stored procedure is cfstoredproc statusCode br cfoutput Reviewing the code The following table describes the...

Page 283: ...rName param2 cfstoredproc Specifies two parameters for the stored procedure an input parameter and an output parameter Sets the input parameter to 1 and the ColdFusion variable that gets the output to...

Page 284: ...t is useful to provide visual feedback to indicate that something is happening so the user does not assume that there is a problem and request the page again Although doing this does not optimize your...

Page 285: ...does not discuss code debugging For information on user input validation see Chapter 26 Retrieving and Formatting Data on page 559 and Chapter 27 Building Dynamic Forms on page 583 For information on...

Page 286: ...sic building blocks for understating types of ColdFusion errors and how ColdFusion handles them How to use the cferror tag to specify error handling pages How to log errors How to handle ColdFusion ex...

Page 287: ...gram logic The ColdFusion compiler identifies and reports program syntax errors when it compiles CFML into Java classes Errors in your application logic are harder to locate For information on debuggi...

Page 288: ...Java code runs It is an event that disrupts the application s normal flow of instructions Exceptions can result from system errors or program logic errors Runtime exceptions include Error responses f...

Page 289: ...n error of the type specified in the tag occurs The MissingInclude error type is a subcategory of Template error If you do not specifically handle the MissingInclude error type but do handle the Templ...

Page 290: ...a page that the ColdFusion cannot find and the Administrator Server Settings Missing Template Handler field specifies a Missing Template Handler page ColdFusion uses that page to display error inform...

Page 291: ...exception type is specified in a cfcatch tag Executes the code in the cfcatch tag If the cftry block does not have a cfcatch tag for this error tests for an appropriate cferror handler or site wide e...

Page 292: ...you entered the page correctly br cfoutput In this code the Replace function removes the leading slash sign from the script name to make the display more friendly Handling form field validation errors...

Page 293: ...where a specific exception will not harm your application for example if a missing resource is not required For more information see Handling runtime exceptions with ColdFusion tags on page 299 cferro...

Page 294: ...errors The validation error page cannot include CFML tags but it can display error page variables You can use this attribute only on the Application cfm page It has no effect when used on any other pa...

Page 295: ...rror application pages Type Considerations Validation Cannot use CFML tags Can use HTML tags Can use the Error InvalidFields Error validationHeader and Error validationFooter variables by enclosing th...

Page 296: ...for the footer of the default validation message Exception and Request error browser Browser that was running when the error occurred error dateTime Date and time when the error occurred error diagno...

Page 297: ...ect the problem p body html Example of a validation error page The following example shows a simple custom error page for a validation error html head title Products Error title head body h2 Data Entr...

Page 298: ...or type Template error template Remote Address error remoteAddress HTTP Reference error HTTPReferer Diagnostics error diagnostics body html Reviewing the code The following table describes the highlig...

Page 299: ...e the ColdFusion exception handling tags to catch and process runtime exceptions directly in ColdFusion pages This ability to handle exceptions directly in your application pages enables your applicat...

Page 300: ...ication page in a cftry block You then follow the cftry block with cfcatch blocks which respond to potential errors When an exception occurs within the cftry block processing is thrown to the cfcatch...

Page 301: ...ly ignored use a cfcatch tag with no body for example cfcatch Type Database In particularly problematic cases you might enclose an exception prone tag in a specialized combination of cftry and cfcatch...

Page 302: ...cture containing information for each tag in the tag stack The tag stack consists of each tag that is currently open cfcatch Type The exception s type returned as a string Entry Description Column Obs...

Page 303: ...the cfcatch type Database handler completes Similarly the cfcatch type MissingInclude block handles exceptions raised by the cfinclude tag Wrap code you want to check in a cftry block cfset EmpID 3 c...

Page 304: ...File name b cfcatch MissingFileName ul cfoutput cfset errorCaught MissingInclude cfcatch Use cfcatch to test for database errors Print error messages Block executes only if a Database exception is th...

Page 305: ...Any block displays an error message indicating an expression error 5 Change DepartmentID back to Dept_ID and redisplay the page The page displays properly Open CFusion Log MyAppPage log in your text e...

Page 306: ...tified by the EmpID variable html head title Test cftry cfcatch title head body cfinclude template includeme cfm cfoutput query test p Department Dept_ID br Last Name LastName br First Name FirstName...

Page 307: ...error message Sets the errorCaught variable to indicate the error type cfcatch type Any cfoutput hr h1 Other Error cfcatch Type h1 ul li b Message b cfcatch message li b Detail b cfcatch Detail ul cfo...

Page 308: ...le cfthrow type com myCompany myApp Invalid_field codeValue errorcode Dodge14B This fully qualified naming method is not required you can use shorter naming rules for example just myApp Invalid_field...

Page 309: ...of type I can Handle Handle it cfelse cfrethrow cfif cfcatch cftry cfcatch Type Any General Error Handling code cfcatch cftry Although this example uses a Database error as an example you can use any...

Page 310: ...conditions For a full description see Reviewing the code following the example Save the following code as getEmps cfm in the same directory as the calling page If the tag didn t pass an attribute thr...

Page 311: ...turn to the calling page without setting the caller variable There is no cfcatch body This might not be appropriate in some cases The Calling page ends up handling this case as if a match was not foun...

Page 312: ...anyInfoBackup SELECT FROM Employee WHERE LastName attributes EmpName cfquery cfset caller getEmpsResult getuser If the query threw a Database error checks to see if the error was caused by an inabilit...

Page 313: ...ch cftry In the second try block catches any errors other exceptions and rethrows them up to the outermost try block Ends the second try block cfcatch Type Any h2 Sorry h2 p An unexpected error happen...

Page 314: ...314 Chapter 14 Handling Errors...

Page 315: ...ons of code to ensure that ColdFusion does not attempt to run the code or access the data that it uses simultaneously or in an unpredictable order This locking feature is important for ensuring the co...

Page 316: ...to use the Client scope prefix in the variable name code that uses the prefix is more efficient and easier to maintain Session Contains variables that are available for a single client browser for a...

Page 317: ...erally do not use Session Application or Server scope variables in clustered environment However you might use these scope variables in a clustered system in the following circumstances Many clusterin...

Page 318: ...he database and Registry data time outs in ColdFusion MX Administrator ColdFusion sets Cookie client variables to expire after approximately 10 years Data is stored on a per user and per application b...

Page 319: ...ookie For more information on using J2EE session management see ColdFusion and J2EE session management on page 327 Using client and session variables without cookies Often users disable cookies in the...

Page 320: ...the following cfform tag posts a request to another page and sends the client identification if required cfform method Post action URLSessionFormat MyActionPage cfm Tip If you use the same page URL in...

Page 321: ...oken variables used to identify the client to ColdFusion are stored at the domain level for example macromedia com If CFID and CFToken variable combinations already exist on each host in the cluster C...

Page 322: ...particular host ColdFusion uses two of these cookies for the CFID and CFToken identifiers and also creates a cookie named cfglobals to hold global data about the client such as HitCount TimeCreated a...

Page 323: ...is associated with a particular client Client variables must be simple data types strings numbers lists Booleans or date and time values They cannot be arrays record sets XML objects query objects or...

Page 324: ...ple use code such as the following cfset Client FavoriteColor Form FavoriteColor Standard client variables The Client scope has the following built in read only variables that your application can use...

Page 325: ...StructDelete function or the DeleteClientVariable function For example the following lines are equivalent cfset IsDeleteSuccessful DeleteClientVariable MyClientVariable cfset IsDeleteSuccessful Struct...

Page 326: ...ll the connections that a single client might make to a server in the course of viewing any pages associated with a given application Sessions are specific to both the individual user and the applicat...

Page 327: ...if you also use client variables You want to share session variables between ColdFusion pages and JSP pages or servlets in a single application You want to be able to manually terminate a session whil...

Page 328: ...on can initialize itself with user specific data the first time a user accesses one of the application s pages This information can remain available while that user continues to use that application F...

Page 329: ...tags Creating and deleting session variables Use a standard assignment statement to create a new session variable as follows cflock timeout 20 scope Session type Exclusive cfset Session ShoppingCartI...

Page 330: ...sion variables or you can clear the session scope as follows cfset StructClear Session If you use J2EE session management you can also invalidate the session as follows cfset getPageContext getSession...

Page 331: ...t place to store information that all pages of your application might need no matter which client is running that application Using application variables an application could for example initialize it...

Page 332: ...tly on page 339 Using server variables Server variables are associated with a single ColdFusion server They are available to all applications that run on the server Use server variables for data that...

Page 333: ...ot try to modify a variable simultaneously it does not ensure the correct order of access to information If multiple pages or multiple invocations of a page attempt to write data simultaneously or rea...

Page 334: ...n totalTicketsSold 6 Order 2 saves the value 163 to Application totalTicketsSold The application now has an inaccurate count of the tickets sold and is in danger of selling more tickets than the audit...

Page 335: ...second order For more examples of using locking in applications see Examples of cflock on page 340 Using the cflock tag with write once variables You do not need to use cflock when you read a variable...

Page 336: ...to another In other words do not nest an exclusive lock in a read only lock of the same name or scope the exclusive lock will always time out Also do not nest a read only lock inside an exclusive loc...

Page 337: ...e in seconds to wait to obtain the lock if it is not available By default if the lock does not become available within the time out period ColdFusion generates a Lock type exception error which you ca...

Page 338: ...protected section of the page are blocked until there is a time out The following table shows one scenario that would cause a deadlock Neither user s request can proceed because it is waiting for the...

Page 339: ...bles because you still must ensure the variable exists and possibly set the value before you can read it You can minimize this problem by using a technique such as the following to test for the existe...

Page 340: ...e sessiontimeout createtimespan 0 1 30 0 sessionmanagement yes Initialize the Session and Application variables that will be used by E Turtleneck Use the Session lock scope for the session variables c...

Page 341: ...urtleneck Today you have chosen a turtleneck in size b form size b and in the color b form color b Your order ID is Session sessionID cfoutput cflock Lock session variables to assign form values to th...

Page 342: ...ton does not include the new order One way you can resolve this problem is by using the OnRequestEnd cfm page to display the value at the bottom of each page in the application Example of synchronizin...

Page 343: ...tes to the non thread safe CFX tag that is used inside a cflock tag cfparam name Attributes AttributeOne default cfparam name Attributes AttributeTwo default cfparam name Attributes AttributeThree def...

Page 344: ...344 Chapter 15 Using Persistent Data and Locking...

Page 345: ...ght Directory Access Protocol discusses secure access to LDAP directories Similarly the section Chapter 20 Enhancing security with cfqueryparam on page 435 describes a method for preventing inappropri...

Page 346: ...at to do based on this information Note You can also use the cfencode utility located in the cf_root bin directory to obscure ColdFusion pages that you distribute Although this technique cannot preven...

Page 347: ...ory with access rules that enable most activities Employee pages go in another directory whose rules limit the files they can modify and the tags they can use Pages required for both HR and employee f...

Page 348: ...r company s intranet The Human Resources department maintains a page on the intranet on which all employees can access timely information about the company such as the latest company policies upcoming...

Page 349: ...About user security 349...

Page 350: ...wn user authentication mechanism 4 If the user logs in successfully the browser caches the authentication information and sends it in an HTTP Authorization header with every subsequent page request fr...

Page 351: ...that can be used to confirm that the current user is authenticated Normally this is done by using memory only cookies that are automatically destroyed when the user closes all open browser windows Th...

Page 352: ...security you put code in the body of the cflogin tag to check the user provided ID and password against a data source LDAP directory or other repository of login identification The body of the tag in...

Page 353: ...hines in the cluster For example to ensure that the cookie works for all servers in the acme com domain specify cookieDomain acme com To specify a domain name start the name with a period Getting the...

Page 354: ...id until any of the following happens The application uses a cflogout tag to log out the user usually in response to the user clicking a log out link or button If your application uses the Session sco...

Page 355: ...ws With Digest or NTLM web server authentication the cflogin password variable is the empty string a It checks the user s name against information it maintains about users and roles In a simple case t...

Page 356: ...de that must be available only to users in that role The application can use the GetAuthUser function to determine the user ID for example to display the ID for personalization It can also use the ID...

Page 357: ...Security scenarios 357...

Page 358: ...a sample application page It displays the logged in user s roles This simple example does not provide a user log out interface You can test the security behavior by adding your own pages to the same...

Page 359: ...br cfscript body html Code Description cfapplication name Orders Identifies the application The login information on this page only applies to this application cflogin cfif IsDefined cflogin cfif cflo...

Page 360: ...es to the same directory as the Application cfm page The example gets user information from the LoginInfo table of the CompanyInfo database that is installed with ColdFusion You can replace this datab...

Page 361: ...D Roles FROM LoginInfo WHERE UserID cflogin name AND Password cflogin password cfquery cfif loginQuery Roles NEQ cfloginuser name cflogin name Password cflogin password roles loginQuery Roles cfelse c...

Page 362: ...rt Executes if the user submitted a login form Tests to make sure that both name and password have data If either variable is empty displays a message followed by the login form The cfabort tag preven...

Page 363: ...cfif cfif cflogin Ends the loginquery Roles test code Ends the form entry empty value test Ends the form entry existence test Ends the cflogin tag body cfif GetAuthUser NEQ cfoutput form action MyApp...

Page 364: ...s message br br if IsUserInRole Sales WriteOutput Sales members see this message br br if IsUserInRole Manager WriteOutput Managers see this message br br if IsUserInRole Employee WriteOutput Employee...

Page 365: ...gged in cfscript if IsUserInRole Human Resources WriteOutput Human Resources members see this message br br if IsUserInRole Documentation WriteOutput Documentation members see this message br br if Is...

Page 366: ...ation uses the user s LDAP directory password as its own password For more information on using LDAP directories with ColdFusion see Chapter 23 Managing LDAP Directories on page 477 cfapplication name...

Page 367: ...ass groupOfUniqueNames uniquemember userSearch dn username userSearch dn password cflogin password cfcatch type any cfif FindNoCase Invalid credentials cfcatch detail cfoutput script alert User ID or...

Page 368: ...stinguished name dn for the user If the user ID is not in the directory returns an empty record set cfcatch type Any cfset UserSearchFailed true cfcatch cftry Catches any exception Sets a UserSearchFa...

Page 369: ...ntials which indicates that either the dn or password is invalid If so displays a dialog box with an error message indicating the problem Otherwise displays a general error message If an error is caug...

Page 370: ...370 Chapter 16 Securing Applications...

Page 371: ...at you must consider is the globalization of your application so that you can best serve customers in different areas This chapter contains information that you can use to develop applications that ca...

Page 372: ...text in languages other than English Defining globalization You will probably find several different definitions for globalization For this chapter globalization is defined as an architectural proces...

Page 373: ...ts control the output encoding of ColdFusion pages and perform other actions Character sets character encodings and locales When you discuss globalization issues two topics that you must consider are...

Page 374: ...racter set encoded in one byte per character such as ASCII or ISO 8859 1 DBCS Double byte character set a method of encoding a character set in no more than two bytes such as Shift JIS Many character...

Page 375: ...haracter encoding used to send the response to the client By default ColdFusion MX uses UTF 8 to represent text data sent to a browser UTF 8 represents the Unicode character set using a variable lengt...

Page 376: ...ocale set using the SetLocale function persists for the current request or until it is reset by another SetLocale function in the request If a request has multiple SetLocale functions the current loca...

Page 377: ...ion loop through list of locales show currency values for 100 000 units cfloop LIST Server Coldfusion SupportedLocales index locale delimiters cfset oldlocale SetLocale locale cfoutput p b I locale I...

Page 378: ...page easily your editor must support BOM characters Many web page development tools support insertion of these characters including Macromedia Dreamweaver MX which automatically sets the BOM based on...

Page 379: ...e the UTF 8 character set Use the cfcontent tag to set the output character set However within a ColdFusion page you can use the cfcontent tag to override the default character encoding of the respons...

Page 380: ...character encoding in which to encode the HTTP header value cfhttp charset Specifies the character encoding of the HTTP request cfhttpparam mimeType Specifies the MIME media type of a file can positi...

Page 381: ...n a locale specific date format LSEuroCurrencyFormat Converts a number into a string in a locale specific currency format Formats using the euro for all countries that use euro as the currency LSIsCur...

Page 382: ...lization tags and functions In addition to the tags and functions that are specifically for globalized applications you might find the following useful when writing a globalized application All string...

Page 383: ...o any single country or locale The LSCurrencyFormat and LSParseCurrency functions rely on the underlying JVM for their operations and the rules used for currencies depend on the JVM For Sun JVMs the 1...

Page 384: ...pecifies a variable scope and the second specifies the character encoding used by the scope Since ColdFusion writes URL parameters to the URL scope you specify URL as the scope parameter to the functi...

Page 385: ...ld of the ColdFusion MX Administrator Java and JVM Settings page Problems can arise if the file character encoding does not correspond to JVM character encoding particularly if the number of bytes use...

Page 386: ...tpparam tags and the GetHttpRequestData function The cfhttp tag supports making HTTP requests The cfhttp tag uses the Unicode UTF 8 encoding for passing data by default and you can use the charset att...

Page 387: ...te characters However if you are using a version of CORBA that does not support wchar and wstring the server uses char and string data types which assume a single byte representation of text Searching...

Page 388: ...388 Chapter 17 Developing Globalized Applications...

Page 389: ...itional information on tools for validating your code before you run it and techniques for troubleshooting particular problems Note Macromedia Dreamweaver MX provides integrated tools for displaying a...

Page 390: ...or more information see Debugging IP addresses page on page 392 Select Debugging Output Format Determines how to display debugging output The classic cfm template the default displays information as p...

Page 391: ...e ColdFusion scopes except Variables Attributes Caller and ThisTag To enhance security Application Server and Request variable display is disabled by default Enable Performance Monitoring Allows the s...

Page 392: ...t problem use the Debugging IP Addresses page to limit the output to your development systems and prevent clients from seeing the debugging information Using debugging information from browser pages T...

Page 393: ...n the classic output template view Name Description ColdFusion The ColdFusion MX version Template The requested template In the dockable cfm format this appears in the Page Overview section and is cal...

Page 394: ...for each ColdFusion page processed during the request If a page is processed multiple times it appears only once in the summary For example if a custom tag gets called three time in a request it appea...

Page 395: ...and all pages required to process the page that is all pages indented below the page in the tree By looking at this output in this figure you can determine the following information ColdFusion took 0...

Page 396: ...ed database query cfquery cfinsert cfgridupdate and cfupdate The section looks like the following figure in the dockable cfm output format The output displays the following information Page on which t...

Page 397: ...splaying the procedure parameters sent and received as specified in the cfprocparam tags including the ctype CFSQLType value variable and dbVarName attributes The variable information for OUT and INOU...

Page 398: ...ssing the request This section looks like the following figure when you use the classic cfm output format For more information on using the cftrace tag see Using the cftrace tag to trace execution on...

Page 399: ...s section The top of the debug pane displays the URL of the application page being debugged as identified by the cgi script_name variable Click this link to refresh the page and display the debugging...

Page 400: ...mation for queries in pages that call the tags You can also view stored procedure specific debugging information by specifying the debug attribute in the cfstoredproc tag Controlling debugging output...

Page 401: ...provide snapshots of specific information as your application runs About the cftrace tag The cftrace tag provides the following information A severity identifier specified by the cftrace tag type attr...

Page 402: ...ges look like the following The following table lists the displayed information ColdFusion logs all cftrace output to the file logs cftrace log in your ColdFusion installation directory A log file ent...

Page 403: ...all 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 you should use this techniq...

Page 404: ...pecifying a user defined trace type category This attribute lets you identify or process multiple trace lines by categories For example you could sort entries in a log according to the category The ca...

Page 405: ...ntly now than in previous releases For example the cfservlet tag is deprecated Modified behavior They might behave differently than in previous versions For example the StructKeyList function no longe...

Page 406: ...20 Encountered at line 24 column 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...

Page 407: ...Then retrieve and analyze the execution plan generated by the database server s query optimizer The method for doing this varies from dbms to dbms The most common cause of slow queries is the lack of...

Page 408: ...408 Chapter 18 Debugging and Troubleshooting Applications...

Page 409: ...ldFusion query of queries mechanism to manipulate record sets It also describes how to access and use LDAP directories and how to index and search collections of documents and data sources using the V...

Page 410: ......

Page 411: ...me basic concepts and techniques This chapter contains an overview of many important database and SQL concepts This chapter does not contain a complete description of database theory and SQL syntax Ea...

Page 412: ...itle and other information for individuals employed by a company Each row called a data record corresponds to one employee The value of a column within a record is referred to as a record field The fo...

Page 413: ...mn associates a row of the employees table with a row in the addresses table For example to obtain all information about an employee you request a row from the employees table and the row from the add...

Page 414: ...commits the change Rollback is the process of undoing a change to a database For example if you write a new row to a table you can rollback the write up to the point where you commit the write After t...

Page 415: ...rmation from the database write new data to the database update existing information in the database or delete records from the database Structured Query Language SQL is an ANSI ISO standard programmi...

Page 416: ...verbs Statement clauses Use the following keywords to refine SQL statements Operators The following basic operators specify conditions and perform logical and numeric functions Keyword Description SE...

Page 417: ...how your database handles case see the product documentation SQL notes and considerations When writing SQL in ColdFusion keep the following guidelines in mind There is a lot more to SQL than what is...

Page 418: ...LECT statement When the database processes a SELECT statement it returns a record set containing the requested data The format of a record set is a table with rows and columns For example if you write...

Page 419: ...ORDER BY LastName You can combine multiple fields in the ORDER BY clause to perform additional sorting SELECT FROM employees ORDER BY DepartmentID LastName This statement returns row ordered by depar...

Page 420: ...able You can use output such as this is to generate mailing addresses for an employee newsletter The results of a SELECT statement that references multiple tables is a single result table containing a...

Page 421: ...lls you must specify a value for the field as part of the INSERT statement otherwise the database issues an error The LastName and FirstName values in the query are contained within single quotes This...

Page 422: ...atements that can be rolled back or committed as a unit If any single statement in the transaction fails you can roll back the entire transaction cancelling any previous writes that occurred within th...

Page 423: ...add the record set to the list of available content sources in the Data bindings panel If you prefer to write your own SQL statements or need to create more complex queries then the Simple Recordset d...

Page 424: ...ings panel Writing queries using Macromedia HomeSite Macromedia HomeSite includes the combined features of HomeSite 5 and ColdFusion Studio 5 with additional support for new ColdFusion MX tags HomeSit...

Page 425: ...Select default Insert Update Delete Section Use Toolbar Contains buttons for SQL keywords and commands Table pane Provides a view of the tables in your query and allows you to create joins between tab...

Page 426: ...426 Chapter 19 Introduction to Databases and SQL...

Page 427: ...uery data This chapter also shows how to use the cfquery tag to query a data source and use the cfoutput tag to output the query results to a web page Contents Working with dynamic data 428 Retrieving...

Page 428: ...ert and update data in this database To query a database you must use ColdFusion data sources The cfquery tag SQL commands Retrieving data You can query databases to retrieve data at runtime The retri...

Page 429: ...fquery tag To tell the database what to process during the query place SQL statements inside the cfquery block When referencing text literals in SQL use single quotation marks For example SELECT FROM...

Page 430: ...n MX To query the table 1 Create a ColdFusion page with the following content html head title Employee List title head body h1 Employee List h1 cfquery name EmpList datasource CompanyInfo SELECT First...

Page 431: ...ding the cfoutput block to format the data on the page Although you do not have to specify the query name when you refer to a query column you should use the query name as a prefix for best practices...

Page 432: ...a database At present the output is raw and needs formatting For more information see Retrieving and Formatting Data on page 559 Reviewing the code The results of the query appear on the page The fol...

Page 433: ...und column names with pound signs to tell ColdFusion to output the column s current values Add a br tag to the end of the variable references so that ColdFusion starts a new line for each row that the...

Page 434: ...play the number of records retrieved in the query The following table describes the code and its function Query variable notes and considerations When using query variables keep the following guidelin...

Page 435: ...WHERE LastName Form LastName cfquery Someone could call this page with the following malicious URL http myserver page cfm Emp_ID 7 20DELETE 20FROM 20Employee The result is that ColdFusion tries to exe...

Page 436: ...ERE LastName cfqueryparam value LastName cfsqltype cf_sql_char maxLength 17 cfquery In this case cfqueryparam performs the following checks It ensures that LastName contains a string It ensures that t...

Page 437: ...dating Your Database This chapter describes how to use ColdFusion to insert update and delete information in a database Contents About updating your dataSbase 438 Inserting data 438 Updating data 442...

Page 438: ...QL knowledge Inserting data You usually use two application pages to insert data into a database An insert form An insert action page You can create an insert form with standard HTML form tags or with...

Page 439: ...h 50 td tr tr td Department Number td td input type Text name Dept_ID size 4 maxlength 4 td tr tr td Start Date td td input type Text name StartDate size 16 maxlength 16 td tr tr td Salary td td input...

Page 440: ...base Creating an insert action page with cfinsert The cfinsert tag is the easiest way to handle simple inserts from either a cfform or an HTML form This tag inserts data from all the form fields with...

Page 441: ...the cfinsert tag with the following highlighted cfquery code html head title Input form title head body If the Contractor check box is clear set the value of the Form Contract to No cfif not isdefined...

Page 442: ...e Emp_ID FirstName LastName Dept_ID Contract VALUES Form Emp_ID Form FirstName Form LastName Form Dept_ID Form Contract cfquery Updating data You usually use the following two application pages to upd...

Page 443: ...ColdFusion which record to update To create an update form 1 Create a ColdFusion page with the following content html head title Update Form title head body cfquery name GetRecordtoUpdate datasource C...

Page 444: ...data on page 445 Reviewing the code The following table describes the code and its function Code Description cfquery name GetRecordtoUpdate datasource CompanyInfo SELECT FROM Employee WHERE Emp_ID URL...

Page 445: ...ith the following content html head title Update Employee title head body cfif not isdefined Form Contract cfset form contract No cfelse cfset form contract Yes cfif First Name input type text name Fi...

Page 446: ...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 myapps update_form cfm Emp_...

Page 447: ...te to trim the 0 from the date when it first appears from the Access database cfquery name UpdateEmployee datasource CompanyInfo UPDATE Employee SET FirstName Form Firstname LastName Form LastName Dep...

Page 448: ...Deleting a single record To delete a single record use the table s primary key in the WHERE condition of a SQL DELETE statement In the following procedure Emp_ID is the primary key so the SQL Delete s...

Page 449: ...cfoutput body html 5 Save the page as delete_action cfm 6 View delete_form cfm in your web browser by specifying the page URL and an Employee ID for example enter the following http localhost myapps...

Page 450: ...mple deletes the records for everyone in the Sales department which has Dept_ID number 4 from the Employee table DELETE FROM Employee WHERE Dept_ID 4 To delete all the records from the Employee table...

Page 451: ...After you generate a record set you can interact with its results as if they were database tables by using Query of Queries This chapter describes the benefits and procedures for this feature Content...

Page 452: ...om and Subject Referencing queries as objects You can reference ColdFusion queries as objects by assigning a query to a variable as follows cfquery name query01 datasource myDNS SELECT FROM CUSTOMERS...

Page 453: ...mp querysetcell qInstruments years_playing 1000 1 cfset temp querysetcell qInstruments name Bjorn 2 cfset temp querysetcell qInstruments instrument sitar 2 cfset temp querysetcell qInstruments years_p...

Page 454: ...t in ways other than using the cfquery tag the term In Memory Query is sometimes used instead of Query of Queries Benefits of Query of Queries Performing a Query of Queries has many benefits including...

Page 455: ...fy a datasource attribute 4 If the database content does not change rapidly use the cachedwithin attribute of the master query to cache the query results between page requests This way ColdFusion acce...

Page 456: ...the master query p cfoutput master columnlist br cfoutput br p Columns in the detail query p cfoutput detail columnlist br cfoutput body 2 Save the page as query_of_query cfm in the myapps directory...

Page 457: ...ail query In a complete application this information comes from user interaction cfquery datasource CompanyInfo name master cachedwithin CreateTimeSpan 0 1 0 0 SELECT from Employee cfquery Queries the...

Page 458: ...Name i b td td bgcolor f0f0f0 b i LastName i b td td bgcolor f0f0f0 b i Salary i b td tr Output the query and define the startrow and maxrows parameters Use the query variable currentRow to keep track...

Page 459: ...lowing format cfdump var query_name For more information on the cfdump tag see CFML Reference Using Query of Queries with non SQL record sets A Query of Queries can operate on any CFML tag or function...

Page 460: ...ry dump h3 cfdump var quick detail query retrieve from the master query only those documents with a score greater than a criterion here 0 7743 cfquery name qoq dbtype query SELECT from quick WHERE qui...

Page 461: ...ry cfset dir C pix retrieve all GIFs cfdirectory name GetGIF action list directory dir filter gif retrieve all JPGs cfdirectory name GetJPG action list directory dir filter jpg join the queries with a...

Page 462: ...ains a table named Products you can refer to the table with dot notation as follows SELECT tape_ID length FROM A B Products Using joins A join operation uses a single SELECT statement to return a resu...

Page 463: ...pes if they meet one of the following conditions The same data type for example both Tinyint Both Numeric for example Tinyint Smallint Integer Bigint Double Float Real Decimal or Numeric Both Characte...

Page 464: ...oves duplicate rows from the result table If you use the keyword ALL then duplicates are included You can combine an unlimited number of tables using the UNION operator for example Select from Table1...

Page 465: ...E clauses You can only have one ORDER BY or COMPUTE clause after the last SELECT statement this clause is applied to the final combined result set You can only specify GROUP BY and HAVING expressions...

Page 466: ...a comparison against a range of values Therefore its syntax requires two values which are inclusive a minimum and a maximum You must separate these values with the AND keyword Syntax between_cond expr...

Page 467: ...presents zero or more characters Square brackets represents any character in the range Square brackets with a caret represent any character not in the range All other characters represent themselves N...

Page 468: ...ELECT emp_discount FROM Benefits WHERE emp_discount LIKE 10 ESCAPE Using aggregate functions Aggregate functions operate on a set of data and return a single value Use these functions for retrieving s...

Page 469: ...y arbitrary arithmetic expression as long as it is referenced by an alias Examples The following code is correct SELECT lorange hirange 2 AS midrange COUNT FROM roysched GROUP BY midrange The followin...

Page 470: ...catenate a first name and a last name to create the value fullname Because the new value does not exist in a database you refer to it by its alias The AS keyword assigns the alias in the SELECT statem...

Page 471: ...oid this limitation you can add an explicit rule to the conditionals and rewrite them in the following forms WHERE breed IS NOT NULL AND breed A WHERE breed IS NOT NULL AND not breed A Escaping reserv...

Page 472: ...E DAY DEALLOCATE DEC DECIMAL DECLARE DEFAULT DEFERRABLE DEFERRED DELETE DESC DESCRIBE DESCRIPTOR DIAGNOSTICS DISCONNECT DISTINCT DOMAIN DOUBLE DROP ELSE END END EXEC ESCAPE EXCEPT EXCEPTION EXEC EXECU...

Page 473: ...cfquery Query object date after q of q br cfoutput q1 col2 1 cfoutput br br Now reformat it cfoutput dateFormat q1 col2 1 mm dd yy cfoutput Understanding Query of Queries performance Query of Queries...

Page 474: ...ct_expression ORDER BY order_by_list select_expression OPENPAREN select_expression CLOSEPAREN select_specification UNION ALL select_expression select_specification SELECT ALL DISTINCT select_list FROM...

Page 475: ...on_list expression COMMA expression expression STRING_LITERAL OPENPAREN STRING_LITERAL CLOSEPAREN numeric_exp numeric_exp numeric_term PLUS MINUS numeric_exp numeric_term numeric_factor ASTERISK SLASH...

Page 476: ...476 Chapter 22 Using Query of Queries...

Page 477: ...ies and the LDAP protocol However it does assume that you have information on your LDAP database s structure and attributes and it does not explain how to create an LDAP directory or manage a director...

Page 478: ...as iPlanet Server have been developed that are native LDAP directory servers Several companies now provide LDAP access to their directory servers including Novell NDS Microsoft Active Directory Servi...

Page 479: ...rganizational structure LDAP offers performance advantages over conventional databases for accessing hierarchical directory like information that is read frequently and changed infrequently Although L...

Page 480: ...d so you can store multiple e mail addresses for one person Some commonly used attribute types have short keyword type names Often these correspond to longer type names and the two names can be used i...

Page 481: ...ap tag effectively A directory schema is a set of rules that determines what can be stored in a directory It defines at a minimum the following two basic directory characteristics The object classes t...

Page 482: ...eate Internet White Pages so users can locate people and resources and get information about them Provide a front end to manage and update directory entries Build applications that incorporate data fr...

Page 483: ...s returns all entries in the scope The following table lists the filter operators modifyDN server dn attributes port username password timeout secure rebind referral delete server dn port username pas...

Page 484: ...lter 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 inetorgperson To specify how query res...

Page 485: ...btree start o airius com sort sn cn This tag returns entries for all the people in the organization and entries for all the groups The group entries have a different object class and therefore differe...

Page 486: ...ius com scope onelevel filter cn form Name l Santa Clara attributes cn sn ou mail telephonenumber sort ou sn maxrows 100 timeout 20 Display results table border 0 cellspacing 2 cellpadding 2 tr th col...

Page 487: ...ectory level immediately below this entry Requests records for entries that contain the location l attribute value Santa Clara and the entered text in the common name attribute Gets the common name su...

Page 488: ...ow how to build a ColdFusion page that lets you manage an LDAP directory Adding a directory entry on page 489 Deleting a directory entry on page 493 Updating a directory entry on page 495 The form dis...

Page 489: ...name uidValue default When the form is submitted add the LDAP entry cfif isdefined Form action AND Trim Form uid IS NOT cfif Form action is add cfif Trim Form fullName is OR Trim Form surname is OR Tr...

Page 490: ...td cfinput type Text name email value emailValue size 20 maxlength 20 tabindex 3 td tr tr td Telephone Number td td cfinput type Text name phone value phoneValue size 20 maxlength 20 tabindex 4 td tr...

Page 491: ...set myServer ldap myco com cfset myUserName cn Directory Manager cfset myPassword password Initializes the LDAP connection information variables Uses variables for all connection information so that a...

Page 492: ...onal unit in this case Human Resources The Trim function removes leading or trailing spaces from the user data cfldap action add attributes attributeList dn uid Trim Form uid ou People o Airius com se...

Page 493: ...tEntry uid 1 cfelseif Form action is Delete cfldap action delete dn uid Trim Form UID ou People o Airius com server myServer cfldap name GetList server myServer action query attributes cn sn mail tele...

Page 494: ...1 cfset surnameValue GetEntry sn 1 cfset emailValue GetEntry mail 1 cfset phoneValue GetEntry telephonenumber 1 cfset uidValue GetEntry uid 1 If the user clicks Retrieve queries the directory and gets...

Page 495: ...seif Form action is Retrieve block and the cfif tag add the following code cfelseif Form action is Update cfset attributelist cn Trim form FullName sn Trim Form surname mail Trim Form email telephonen...

Page 496: ...lass Code Description cfelseif Form action is Update cfset attributelist cn Trim form FullName sn Trim Form surname mail Trim Form email telephonenumber Trim Form phone cfldap action modify modifytype...

Page 497: ...le you to use LDAP directories more effectively Specifying an attribute that includes a comma or semicolon LDAP attribute values can contain commas The cfldap tag normally uses commas to separate attr...

Page 498: ...ypes For attribute types it displays the type name type description and whether the type is single or multivalued The example does not display all the information in the schema For example it does not...

Page 499: ...td cfoutput Mid thisElement suploc 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 Re...

Page 500: ...he template as ldapschema cfm in myapps under your web root directory and view it in your browser Reviewing the code The following table describes the code and its function Code Description cfldap nam...

Page 501: ...e 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 Mid thisElement suploc 5 mustloc s...

Page 502: ...ute specifies whether ColdFusion uses the cfldap tag login information in the request to the new server The default No sends an anonymous login to the server h2 Attribute Types h2 table border 1 tr th...

Page 503: ...ColdFusion determines whether to trust the server by comparing the server s certificate with the information in the jre lib security cacerts keystore of the JRE used by ColdFusion MX The ColdFusion M...

Page 504: ...ault nonsecure LDAP port 389 Application security To ensure application security you must prevent outsiders from gaining access to the passwords that you use in cfldap tags The best way to do this is...

Page 505: ...ch engine This chapter describes how to build a Verity search interface with which users can perform powerful searches on your application It also describes how to index your documents and data source...

Page 506: ...each of which can focus on a specific group of documents or queries according to subject document type location or any other logical grouping Because you can perform searches against multiple collect...

Page 507: ...list When Verity indexes web pages it can return the URL for each document This is a valuable document management feature Supported file types The ColdFusion Verity implementation supports a wide arr...

Page 508: ...Works spreadsheet v1 0 2 0 3 0 4 0 Presentation formats Applix Presents v4 3 4 4 Corel Presentations v7 0 8 0 Lotus Freelance v96 97 R9 Microsoft PowerPoint v4 0 95 97 2000 Microsoft PowerPoint Mac 98...

Page 509: ...it from the drop down list when you create a collection with the ColdFusion MX Administrator In CFML the cfcollection cfindex and cfsearch tags have an optional language attribute that you use to spe...

Page 510: ...ss you specify it in the language attribute for the cfindex and cfsearch tags for that collection Dutch dutch LinguistX English english LinguistX Finnish finnish LinguistX French french LinguistX Germ...

Page 511: ...pages that index the collection and design a search interface The following table summarizes the steps and available methods for creating the search tool This chapter presents the non code methods for...

Page 512: ...ame for the collection for example DemoDocs 3 Enter a path for the directory location of the new collection for example C cfusionmx verity collections By default ColdFusion stores collections in cf_ro...

Page 513: ...x and cfsearch Use the following guidelines to determine which method to use The cfcollection tag has the following action attribute values that can fix or improve your index repair Repairs the intern...

Page 514: ...text word processing spreadsheet and HTML If this directory is within your web_root then you can view the files from the web browser Some of these files contain a search target word s There is an ava...

Page 515: ...e following information 7 Click Next The Indexing Settings window appears Field Description Example Collection Name The name of the collection you created in the ColdFusion MX Administrator or by usin...

Page 516: ...b browser if you do so enter an HTTP URL that corresponds to your SearchForm such as http 127 0 0 1 8500 vw_generated SearchCFDocumentation_VSearchForm cfm 12 Click the Index link at the bottom of the...

Page 517: ...precede the hexadecimal color codes The correct code is TR bgcolor IIf CurrentRow Mod 2 DE FFFFFF DE FFFFCF c Save the file d Browse the SearchForm page and enter the search target Your search result...

Page 518: ...or optimize The default value for the action attribute is list For more information see cfcollection in CFML Reference collection The name of the new collection or the name of a collection upon which...

Page 519: ...ent html head title cfcollection title head body h2 Collection creation h2 cfoutput cfswitch expression Form collectionaction cfcase value Create cfcollection action Create collection Form CollectionN...

Page 520: ...ction in CFML using the cfindex tag which eliminates the need to use the ColdFusion MX Administrator When using this tag the following attributes correspond to values entered in the ColdFusion MX Admi...

Page 521: ...input type submit name submit value Index form body html 2 Save the file as collection_index_form cfm in the myapps directory under the web_root Note The form will not work until you write an action p...

Page 522: ...ect a collection name for example CodeColl 2 Click Index to open the index page 3 For File Extensions enter the type s of files to index Use a comma to separate multiple file types for example htm htm...

Page 523: ...rdCount The total number of records returned by the search CurrentRow The current row of the record set being processed by cfoutput RecordsSearched The total number of records in the index that were s...

Page 524: ...this as the variable criteria to the action page which displays the search results To create the results page 1 Create a ColdFusion page with the following content html head title Search Results title...

Page 525: ...of the indexing process Verity automatically produces a summary of every document file or every query record set that gets indexed The default summary selects the best sentences based on internal rul...

Page 526: ...m a ColdFusion query involves an extra step not required when you index documents You must code the query and output parameters and then use the cfindex tag to index the record set from a cfquery cfld...

Page 527: ...on with the above query results cfindex query getEmps collection CodeColl action Update type Custom key Emp_ID title Emp_ID body Emp_ID FirstName LastName Salary h2 Indexing Complete h2 output the rec...

Page 528: ...rch and display database records 1 Create a ColdFusion page with the following content html head title Searching a collection title head body h2 Searching a collection h2 form method post action colle...

Page 529: ...riteria Form Criteria output the record set cfoutput Your search returned getEmps RecordCount file s cfoutput cfoutput query getEmps p table tr td Title td td Title td tr tr td Score td td Score td tr...

Page 530: ...onsiderations Because LDAP structures vary greatly you must know the server s directory schema and the exact name of every LDAP attribute that you intend to use in a query The records on an LDAP serve...

Page 531: ...ly the message number is reset as messages are added and deleted To avoid mismatches between the unique message number identifiers on the server and in the Verity collection you must re index the coll...

Page 532: ...e which can have custom file or path as its value When type custom ColdFusion populates a collection with the contents of the record set When type file or type custom the record set becomes the input...

Page 533: ...arch collection snippets criteria cfdump var mySearch The following code shows how to populate the snippets collection with paths that are specified in the description column of the database html cfqu...

Page 534: ...534 Chapter 24 Building a Search Interface...

Page 535: ...Verity search expressions and how you can refine your searches to yield the most accurate results Contents About Verity query types 536 Using simple queries 536 Using explicit queries 539 Composing se...

Page 536: ...eb search engines assume a logical AND for multiple word searches and search for a phrase only if you use quotation marks Because Verity treats multiple word searches differently it might help your us...

Page 537: ...instrumentation whereas a search for instru does not A wildcard search for instru returns documents with these words and also those with instruct instructional and so on Note The MANY modifier present...

Page 538: ...g stemming When entering text on a search form you can prevent Verity from implicitly adding the STEM operator by doing one of the following Perform an explicit query For more information see the next...

Page 539: ...e Operators and modifiers on page 543 However users might only use the most basic operators AND and OR and the modifier NOT The following are a few important points You can type operators in uppercase...

Page 540: ...ND nausea masters or the combination of doctorate and nausea masters OR doctorate AND nausea either masters or doctorate and nausea masters OR doctorate NOT nausea either masters or doctorate but not...

Page 541: ...he following nonalphanumeric characters with a backslash character in a search string comma left parenthesis right parenthesis double quotation mark backslash left curly brace left bracket less than s...

Page 542: ...dence is implicit in the expression for example the AND operator takes precedence over the OR operator You can use prefix notation with any operator except an evidence operator typically STEM WILDCARD...

Page 543: ...results in other ways For example you can construct an HTML form for conducting searches In the form you can search for a single term You can refine the search by limiting the search scope in a numbe...

Page 544: ...vidence Specifies basic and intelligent word searches Proximity Specifies the relative location of words in a document Score Manipulates the score returned by a search element You can set the score pe...

Page 545: ...ined you can search for documents that are 5 pages or less by entering PAGES 5 in your search Similarly if a document field named DATE is defined you can search for documents dated prior to and includ...

Page 546: ...tored in a specific document field Documents are selected only if the search elements specified match the field value exactly If a partial match is found a document is not selected When you use the MA...

Page 547: ...collection that contains the TEXT column and then narrows further by searching for the string Utah in the CF_TITLE document field Document fields are defaults defined in every collection correspondin...

Page 548: ...and spamming WORD Performs a basic word search selecting documents that include one or more instances of the specific word that you enter The WORD operator is automatically implied in any SIMPLE quer...

Page 549: ...of each other where N is an integer between 1 and 1024 NEAR 1 searches for two words that are next to each other The closer the search terms are within a document the higher the document s score You...

Page 550: ...ocument retrieved for example cfoutput a href Search1 URL Search1 Title a br Document Score Search1 SCORE BR cfoutput The following table describes the score operators Operator Description Example YES...

Page 551: ...and produces a relevance ranked score for retrieved documents Use with the following operators WORD WILDCARD STEM PHRASE SENTENCE PARAGRAPH PARAGRAPH MANY javascript AND vbscript You cannot use the MA...

Page 552: ...r includes built in support for HTML and several file formats for a list of supported file formats see Building a Search Interface on page 505 Verity searches XML files by treating the XML tags as zon...

Page 553: ...ction my_collection type explicit criteria Pete in Lead_Guitar To retrieve files in which Pete plays either lead or rhythm guitar use the following explicit search Pete in Lead_Guitar Rhythm_Guitar Th...

Page 554: ...blem description These are the requirements to run this procedure Create and populate the Calls table in a database of your choice Create a collection named Training you can do this in CFML or in the...

Page 555: ...perform the refined search for HomeSite problems with the word certain in the problem description the cfsearch tag uses the CONTAINS operator in its criteria attribute cfsearch collection training na...

Page 556: ...556 Chapter 25 Using Verity Search Expressions...

Page 557: ...request data from users how to use the cfchart tag to graphically display data and how to use the Flash Remoting service to provide information to Macromedia Flash applications for display The follow...

Page 558: ......

Page 559: ...ble with query results and how to use ColdFusion functions to format and manipulate data Contents Using forms to specify the data to retrieve 560 Working with action pages 564 Working with queries and...

Page 560: ...standard HTML the syntax and examples that follow provide you with just enough detail to begin using ColdFusion For information on using ColdFusion forms defined by the cfform tag see Chapter 27 Build...

Page 561: ...1 Create a ColdFusion page with the following content html head title Input form title head body Control Code Text control input type Text name ControlName size Value maxlength Value Radio buttons inp...

Page 562: ...le Seattle select p radio buttons p Department br input type radio name Department value Training Training br input type radio name Department value Sales Sales br input type radio name Department val...

Page 563: ...to 35 characters input type Text name LastName size 20 maxlength 35 Creates a text box called LastName where users can enter their first name Makes it 20 characters wide but allows input of up to 35 c...

Page 564: ...gs functions and other expressions on an action page Because form variables extend beyond the local page their scope is the action page prefix them with Form to explicitly tell ColdFusion that you are...

Page 565: ...le Retrieving Employee Data Based on Criteria from Form title head body cfquery name GetEmployees datasource CompanyInfo SELECT FirstName LastName Salary FROM Employee WHERE LastName cfqueryparam valu...

Page 566: ...g users to enter values in form fields One of the limitations of HTML forms is the inability to define input fields as required Because this is a particularly important requirement for database applic...

Page 567: ...ction page if you select an option Text boxes passwords and textareas pass an empty string if you do not enter text An error occurs if the action page tries to use a variable that was not passed If mu...

Page 568: ...e text box and submit the form 6 The records that match the criteria specified in the form appear in a table Reviewing the code The following table describes the highlighted code and its function Code...

Page 569: ...g action page allows users to search for employees by department last name or both Note ColdFusion MX provides the Verity search utility that you can also use to perform a search For more information...

Page 570: ...SELECT Departmt Dept_Name Employee FirstName Employee LastName Employee StartDate Employee Salary FROM Departmt Employee WHERE Departmt Dept_ID Employee Dept_ID Retrieves the fields listed from the D...

Page 571: ...lays 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 the end of the conditional code To return search...

Page 572: ...y data that is already available when you make this call You can use the cfflush tag in a cfloop to incrementally flush data as it becomes available This format is particularly useful when a query res...

Page 573: ...seem harder cfloop index randomindex from 1 to 200000 step 1 cfset random rand cfloop Now slowly output 10 random numbers cfloop index Myindex from 1 to 10 step 1 cfloop index randomindex from 1 to 10...

Page 574: ...partments datasource CompanyInfo SELECT DISTINCT Location FROM Departmt cfquery Define the action page in the form tag The form variables will pass to this page when the form is submitted form action...

Page 575: ...e Submit form body html 3 Save the page as formpage cfm 4 View formpage cfm in a browser The changes that you just made appear in the form Remember that you need an action page to submit values Review...

Page 576: ...elimited list of values The values can be either numeric values or alphanumeric strings These two types of values are treated slightly differently Handling numeric values Suppose you want a user to se...

Page 577: ...ckbox name SelectedDepts value Training Training br input type checkbox name SelectedDepts value Marketing Marketing br input type checkbox name SelectedDepts value HR HR br input type checkbox name S...

Page 578: ...pts multiple option value 1 Training option value 2 Marketing option value 3 HR option value 4 Sales select If the user selects the Marketing and Sales items the value of the SelectDepts form field is...

Page 579: ...le page for both the form and action provides the opportunity to show the use of the IsDefined function to check that data exists This way the form does not show any results until you submit the input...

Page 580: ...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 isdefined Form StartDate cfoutput Start Dat...

Page 581: ...name Salary_required value You must enter a salary input type hidden name Salary_float value The salary must be a number Require input into the Salary input field If there is no input display the err...

Page 582: ...582 Chapter 26 Retrieving and Formatting Data...

Page 583: ...ols You can use these controls without writing a line of Java code Contents Creating forms with the cfform tag 584 Building tree controls with cftree 586 Building drop down list boxes 593 Building tex...

Page 584: ...attributes that are not explicitly allowed in these tags The attribute values are passed through to the HTML generated by these form tags You can replace your existing HTML form tags with cfform and...

Page 585: ...no effect on cfgrid If you populate the control from a query you must update the data source with the new data typically by using cfgridupdate before redisplaying the grid The grid then displays the...

Page 586: ...to populate the control You can specify one of six built in icons to represent individual items in the tree control or supply a file path or URL to your GIF image Note The cftree tag requires the clie...

Page 587: ...and name it tree1 required Yes Specifies that a user must select an item in the tree hscroll No Does not allow horizontal scrolling cftreeitem value FullName query engquery Creates an item in the tree...

Page 588: ...uery datasource CompanyInfo SELECT Dept_ID FirstName LastName AS FullName FROM Employee ORDER BY Dept_ID cfquery Build the tree control cfform name form1 action submit cfm cftree name tree1 hscroll No...

Page 589: ...oot 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 as the root In the pre...

Page 590: ...DER BY Dept_ID cfquery cfform name form1 action submit cfm cftree name tree1 cftreeitem value FullName query deptquery queryasroot Department cftree br input type submit value Submit cfform Creating a...

Page 591: ...item value Product Two parent Support cftreeitem value Sales parent Divisions img cd cftreeitem value Marketing parent Divisions img document cftreeitem value Finance parent Divisions img element cftr...

Page 592: ...relative URL or an absolute URL as in the following examples To embed links in a cftree 1 Create a ColdFusion page named tree3 cfm with the following contents cfform action submit cfm cftree name oak...

Page 593: ...e control over user inputs provides error handling and most importantly allows you to automatically populate the selection list from a query You can populate the drop down list box from a query or usi...

Page 594: ...tag or the CFML cfinput type text tag With cftextinput however you can also specify font and alignment options use the validate attribute to enable input validation using ColdFusion validation methods...

Page 595: ...lues To create a slider control 1 Create a ColdFusion page with the following content cfform name Form1 action submit cfm cfslider name myslider bgcolor cyan bold Yes range 0 1000 scale 100 value 600...

Page 596: ...mn with a grid column Use the cfgridrow tag to define a grid that does not use a query as the source for row data If a query attribute is specified in cfgrid the cfgridrow tags are ignored The cfgrid...

Page 597: ...o attribute to hide columns that you want to include in the grid but not expose to an end user You typically use this attribute to include columns such as the table s primary key column in the results...

Page 598: ...o corresponding cfgridcolumn attributes the grid contains all the columns in the query selectmode single Allow the user to select only one cell Other modes are row column and edit cfgridcolumn name Em...

Page 599: ...ver interactions with your data source The cfgridupdate tag provides a much simpler interface for operations that do not require the same level of control Controlling cell contents The value valuesDis...

Page 600: ...data or inserts or deletes rows the action page gets one array for each changed column and the RowStatus Action array The action page does not get arrays for unchanged columns If the user makes a cha...

Page 601: ...nts of the Emp_ID column and automatically generating its value for new records and displaying the Department name from the Departmt table in place of the Department ID To make the grid editable 1 Cre...

Page 602: ...headeralign center headerbold Yes select No Creates a 50 pixel wide column for the data in the Emp_ID column of the data source Center a header named Emp ID and make it bold Does not allow users to s...

Page 603: ...are made but the tag does not provide any information on them To update the data source with cfgridupdate 1 Create a file ColdFusion page with the following contents html head title Update grid value...

Page 604: ...ExistingEmployee datasource CompanyInfo DELETE FROM Employee WHERE Emp_ID cfqueryparam value Form employee_grid original Emp_ID Counter CFSQLType CF_SQL_INTEGER cfquery cfelseif Form employee_grid row...

Page 605: ...to be changed Counter is the common index into the arrays of change information for the row being changed cfoutput The row action for Counter is Form employee_grid rowstatus action Counter br cfoutpu...

Page 606: ...form variable name cfapplet appletsource Calculator name calc_value By contrast with the HTML applet tag you must declare all the applet s parameters every time you want to use it in a ColdFusion page...

Page 607: ...plet width in pixels VSpace Measurement in pixels for the space above and below the applet HSpace Measurement in pixels for the space on each side of the applet Align Applet alignment Not Supported Me...

Page 608: ...tor by providing new values for any parameter In order to override a parameter you must have already defined the parameter and a default value for it in the ColdFusion MX Administrator Applets page as...

Page 609: ...ecified If you do not specify a method ColdFusion does not create a form variable Input validation with cfform controls The cfinput and cftextinput tags include the validate attributes which lets you...

Page 610: ...cftextinput tags only These rules differ from those used by the ColdFusion functions REFind REReplace REFindNoCase and REReplaceNoCase For information on regular expressions used in ColdFusion functio...

Page 611: ...acter regular expression or grouped subexpression followed by a question mark matches zero or one occurrences of the regular expression For example xy z matches either xyz or xz The carat at the begin...

Page 612: ...p to three pairs of the expression ba The form m requires at least m occurrences of the preceding regular expression The form m requires exactly m occurrences of the preceding regular expression The s...

Page 613: ...ng Regular Expressions by Jeffrey E F Friedl published by O Reilly Associates Inc Input validation with JavaScript In addition to native ColdFusion input validation using the validate attribute of the...

Page 614: ...ndling failed validation The onerror attribute lets you specify a JavaScript function to execute if a validation fails For example if you use the onvalidate attribute to specify a JavaScript function...

Page 615: ...e form data 1 Create a ColdFusion page with the following content html head title JavaScript Validation title script function testbox form ctrl value if value value indexOf 1 1 value indexOf 3 1 retur...

Page 616: ...return true script JavaScript code that tests for valid entry in the text box The if statement checks to making sure that the field is not empty and contains an at sign that at least the second charac...

Page 617: ...e cfchart tag to display charts and graphs It describes ways that you can chart data and gives you the tools you need to create effective charts Contents Creating a chart 618 Administering charts 620...

Page 618: ...cfchart tag along with the tags cfchartseries and cfchartdata provide many different chart types The attributes to these tags let you customize your chart appearance Chart types You can create 11 type...

Page 619: ...ColdFusion query If you have a query that contains average salary information by department the following code displays a bar chart that shows the data in the query cfchart xAxisTitle Department yAxi...

Page 620: ...reference a cached chart Whenever you use the cfchart tag ColdFusion inspects the cache to see if the chart has already been rendered If so ColdFusion loads the chart from the cache The following tab...

Page 621: ...as the item label by each bar You use the following attributes of the cfchartseries tag when working with queries Using queries of queries provides significant power in generating the data for the ch...

Page 622: ...AvgByDept FROM GetSalaries GROUP BY Dept_Name cfquery Reformat the generated numbers to show only thousands cfloop index i from 1 to DeptSalaries RecordCount cfset DeptSalaries AvgByDept i Round DeptS...

Page 623: ...le describes the code and its function Code Description cfquery name GetSalaries datasource CompanyInfo SELECT Departmt Dept_Name Employee Salary FROM Departmt Employee WHERE Departmt Dept_ID Employee...

Page 624: ...pie chart displays four types of revenue for a car dealership Each cfchartdata tag specifies a department s income and description for the legend Note If two data points have the same item name ColdF...

Page 625: ...000 cfchartseries cfchart Charting multiple data collections Sometimes you might have more than one series of data to display on a single chart or you want to compare two sets of data on the same char...

Page 626: ...ple series depends on the order that you specify the cfchartseries tags For example if a bar chart is specified first and a line chart second the bar chart appears in front of the line chart in the fi...

Page 627: ...ning a chart You use the name attribute of the cfchart tag to write a chart to a variable If you specify the name attribute the chart is not rendered in the browser but is written to the variable You...

Page 628: ...he chart is saved to disk as c inetpub wwwroot charts vehicle jpg Reviewing the code The following table describes the highlighted code and its function Code Description cfchart name myChart format jp...

Page 629: ...g and Administering ColdFusion MX Border showBorder Specifies to draw a border around the chart The border color is the same as specified by the foregroundColor attribute Default is no Labels font fon...

Page 630: ...showMarkers specifies to show markers at the data points for 2D line curve and scatter charts Default is yes markerSize specifies an integer number of pixels for the marker size ColdFusion determines...

Page 631: ...XAxisType sortXAxis Specify whether the X axis corresponds to a numeric scale or identifies different categories and how to sort the items on the axis If the XAxisType attribute value is scale the X...

Page 632: ...pt AVG Salary AS AvgByDept FROM GetSalaries Code Description scaleTo 100000 Set the maximum value of the vertical axis to 100000 The minimum value is the default 0 fontSize 16 Make the point size of t...

Page 633: ...ByDept i 1000 1000 cfloop 3 Add the following cfchart tag Pie chart from DeptSalaries Query of Queries cfchart tipStyle mousedown font Times fontsize 14 fontBold yes backgroundColor CCFFFF show3D yes...

Page 634: ...floop index i from 1 to GetSalaries RecordCount cfset GetSalaries StartDate i NumberFormat DatePart yyyy GetSalaries StartDate i 9999 cfloop Code Description SUM Salary AS SumByDept In the DeptSalarie...

Page 635: ...StartDate cfchart br 5 Save the page 6 Return to your browser and enter the following URL to view chartdata cfm http 127 0 0 1 myapps chartdata cfm Reviewing the code The following table describes th...

Page 636: ...chart For example define a chart that opens the page moreinfo cfm when a user clicks on the chart using the following code cfchart xAxisTitle Department yAxisTitle Salary Average url moreinfo cfm cfch...

Page 637: ...tion for the departments represented by the wedge The example is divided into two parts creating the detail page and making the pie chart dynamic Part 1 creating the detail page This page displays sal...

Page 638: ...WHERE Departmt Dept_Name URL Item AND Departmt Dept_ID Employee Dept_ID ORDER BY Employee LastName Employee Firstname cfquery Get the salary data for the department whose name was passed in the URL p...

Page 639: ...department name of the wedge you clicked The salary information for that department appears Reviewing the code The following table describes the highlighted code and its function Linking to JavaScrip...

Page 640: ...cfchartData item Finance value 75000 cfchartData item Sales value 120000 cfchartData item IT value 83000 cfchartData item Facilities value 45000 cfchartseries cfchart 2 Save the page as chartdata_with...

Page 641: ...ynamic Flash user interfaces for ColdFusion applications Contents About using the Flash Remoting service with ColdFusion 642 Using the Flash Remoting service with ColdFusion pages 643 Using Flash with...

Page 642: ...h multiple client types such as Flash movies web browsers and web services Building ColdFusion applications for multiple clients means that your ColdFusion pages and components return common data type...

Page 643: ...lash scope In addition the following table compares the ColdFusion data types and their ActionScript equivalents Variable Description For more information Flash Params A structure containing the param...

Page 644: ...ems WHERE ItemName EQ Flash paramName cfquery Collection ActionScript example Notes Strict array var myArray new Array myArray 1 one myArray 2 two myService myMethod myArray The Flash Remoting service...

Page 645: ...elloWorld cfm so that the CFML code appears as follows cfset tempStruct StructNew cfset tempStruct timeVar DateFormat Now cfset tempStruct helloMessage Hello World 4 In the example two string variable...

Page 646: ...records the record set becomes pageable and returns the number of records specified in the Flash Pagesize For example include NetServices as NetServices setDefaultGatewayUrl http localhost 8500 flash...

Page 647: ...ashExamples flashComponent this CFCService helloWorld In this example the getService references the flashComponent component in the flashExamples directory You can now call the CFCService object sayHe...

Page 648: ...server side ActionScript provides a familiar way for Flash developers to access ColdFusion query and HTTP features without learning CFML You can place ActionScript files asr on the server that you wa...

Page 649: ...m field 4 Click Submit Changes 5 Restart ColdFusion When you place your Java files in the classpath the public methods of the class instance are available to your Flash movie For example assume the Ja...

Page 650: ...e Flash Player as in the following example cftry cfset Flash Result undefinedVar cfcatch cfset Flash Result Failed cfcatch cftry In this example the first cfset tag fails to assign the value into Flas...

Page 651: ...cess Macromedia ColdFusion MX query and HTTP features through two new ActionScript functions CF query and CF http Contents About server side ActionScript 652 Connecting to the Flash Remoting service 6...

Page 652: ...uirements On the client side you only need a small piece of code that establishes a connection to the Flash Remoting service and references the server side ActionScript you want to use For example not...

Page 653: ...t to the client as a RecordSet object Software requirements To use server side ActionScript files you must have the following software installed Macromedia Flash MX Macromedia ColdFusion MX Flash Remo...

Page 654: ...you only need to know a few things to get started How to establish a connection with the Flash Remoting service using client side ActionScript See Connecting to the Flash Remoting service on page 654...

Page 655: ...object Use dot notation to specify the object name followed by the function name for example albumService getAlbum The Color And The Shape 1999 Where albumService is the instance of the server side A...

Page 656: ...le HTTP status codes the MIME type of the returned file and so on On the client side you create return functions to handle data returned by the CF http function You write these functions to handle sim...

Page 657: ...in the server side ActionScript file using the CF query ActionScript function See Using the CF query function on page 658 Reference the server side ActionScript file in your Flash MX movie See Connect...

Page 658: ...losely to the cfquery CFML tag although it currently supports a subset of the cfquery attributes Use the CF query function to do the following Identify the data source you want to query Pass SQL state...

Page 659: ...the end of the specified RecordSet addItemAt Inserts a record at the specified index addView Requests notification of changes in a RecordSet object s state filter Creates a new RecordSet object that...

Page 660: ...ActionScript retrieves data from a ColdFusion MX data source and returns the results to the Flash movie as a RecordSet object Note The server side ActionScript application that you create provides th...

Page 661: ...LECT from personnel WHERE fname firstName AND lname lastName if searchdata return searchdata else return null 2 Save the file as personneldirectory asr Creating the Flash movie interface The Flash mov...

Page 662: ...on Capturing Flash Remoting service results When you create a function that calls a server side ActionScript function you must also create a function to handle the data returned by server side ActionS...

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

Page 664: ...text data Charset The charset used by the document specified in the URL HTTP servers normally provide this information or the charset is specified in the charset parameter of the Content Type header...

Page 665: ...CF http post url params karl salsa return result get Filecontent Using the CF http Post method You use the Post method to send cookie form field CGI URL and file variables to a specified ColdFusion p...

Page 666: ...calhost 8500 Invoke CF http with the method url and params result CF http post url params return result get Filecontent Using the CF http Get method You use the Get method to retrieve files including...

Page 667: ...escribes how to use external objects including Java Component Object Model COM and Common Object Request Broker Architecture CORBA objects in CFML applications The following chapters are included Chap...

Page 668: ......

Page 669: ...nd JavaScript This chapter does not present XML concepts Before you read this chapter you should become familiar with XML Contents About XML and ColdFusion 670 The XML document object 671 ColdFusion X...

Page 670: ...order fulfilment component inventory management component and billing component can all share information with each other in XML format They could use a common XML DTD of different components could c...

Page 671: ...ed units as the node view ColdFusion can access XML document contents using either view A simple XML document The next sections describe the basic and node views of the following simple XML document T...

Page 672: ...tree of nodes Each node has a DOM node type a node name and a node value Node types include Element Comment Text and so on The DOM structures the document object and each of the elements it contains i...

Page 673: ...a section of the cfdump tag output for the document object for the XML in A simple XML document on page 671 This figure shows the long version of the dump which provides complete details about the do...

Page 674: ...y does not appear when cfdump displays an XML element structure Entry name Type Description XmlName String The name of the element XmlNsPrefix String The prefix of the Namespace XmlNsURI String The UR...

Page 675: ...rence nodes in the DOM tree created from the XML example in A simple XML document on page 671 mydoc XmlName mydoc XmlValue mydoc XmlRoot XmlName mydoc employee XmlType mydoc employee XmlNodes 1 XmlTyp...

Page 676: ...cument object If you specify the optional argument as True the case of names of elements and attributes in the document is meaningful The default is False For more information on using the XmlNew func...

Page 677: ...nment or as a function argument By default ColdFusion ignores element name case As a result it considers the element name MyElement and the element name myELement to be equivalent To make element name...

Page 678: ...ast element in the reference string For example the rules in Referencing the contents of an XML object on page 677 apply to mydoc employee name 1 first in the following expression mydoc employee name...

Page 679: ...DATA start and end marker information items assign the text to the XmlCdata element not the XmlText element You must do this because ColdFusion escapes the and symbols in the element text when you ass...

Page 680: ...4 childNode This is Child node cfoutput LoopCount cfoutput childNode cfloop MyDoc cfxml cfdump var MyDoc This example creates a document object with a root element MyDoc which includes text that disp...

Page 681: ...ile tag charset attribute to specify the file s character set For example if the file is encoded in UTF specify charset UTF 8 Saving and exporting an XML document object The ToString function converts...

Page 682: ...pend Adds a new element at the end or beginning of an element s XmlChildren array ArraySwap Swaps the children in the XmlChildren array at the specified position ArraySet Sets a range of entries in an...

Page 683: ...ing tables provide a quick reference to the ways you can modify the contents of an XML document object The sections that follow describe in detail how to modify XML contents StructAppend Appends a doc...

Page 684: ...ElemPath newChildName newElem where newChildName must be the same as newElem XmlName and cannot be an indexed name such as name 3 Type Using a function Using an assignment statement Property StructDel...

Page 685: ...s describe how to get this information Counting child elements The following user defined function determines the number of child elements with a specific name in an element cfscript function NodeCoun...

Page 686: ...ct elementName where docObject is the name of the XML document object in which you are creating the element and elementName is the name you are giving the new element Use an assignment statement with...

Page 687: ...ents of mydoc employee cfset mydoc employee XmlChildren 9 XmlElemNew mydoc name If the parent element does not have any children with the same name as the new child you can specify the name of the new...

Page 688: ...fy the element position either among the elements of the same name or among all child elements Fore example you can use the following line to delete the second name element in mydoc employee cfset Arr...

Page 689: ...must create a new element with the new name insert it into the XML document object before or after the original element copy all the original element s contents to the new element and then delete the...

Page 690: ...o a query object and then performs a query of queries on the object to extract selected data Read the file and convert it to an XML document object cffile action read file C Neo wwwroot myexamples emp...

Page 691: ...verting XML data to another format such as converting XML in a vocabulary used by an order entry application into a vocabulary used by an order fulfillment application XSLT transforms an XML document...

Page 692: ...c XmlParse myxml selectedElements XmlSearch myxmldoc employee name last for i 1 i LTE ArrayLen selectedElements i i 1 writeoutput selectedElements i XmlText br cfscript XPath is specified by the World...

Page 693: ...has an id attribute and contains a name quantity and unitprice element The name quantity and unitprice elements contain their value as body text The following order xml document works correctly with...

Page 694: ...qty unitPrice cfset temp QueryAddRow orderquery numItems cfloop index i from 1 to numItems cfset temp QuerySetCell orderquery item_Id mydoc order items item i XmlAttributes id i cfset temp QuerySetCe...

Page 695: ...riceQuery totalPrice br b 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...

Page 696: ...orderquery name mydoc order items item i name XmlText i cfset temp QuerySetCell orderquery qty mydoc order items item i quantity XmlText i cfset temp QuerySetCell orderquery unitPrice mydoc order item...

Page 697: ...ation is located at www openwddx org downloads dtd wddx_dtd_10 txt While WDDX is a valuable tool for ColdFusion developers its usefulness is not limited to CFML If you serialize a common programming d...

Page 698: ...cfwddx to convert a purchase order structure to WDDX It could then use cfhttp to send the WDDX to a supplier running a CGI based system The supplier could then deserialize the WDDX to its native data...

Page 699: ...eated by either of the following scripts Conversely when you serialize the variable x produced by either of these scripts into WDDX you generate the XML listed above ColdFusion provides a tag and Java...

Page 700: ...t not contain embedded nulls Strings can be encoded using double byte characters Data type Description Array Arrays are integer indexed collections of objects of arbitrary type Because most languages...

Page 701: ...an hour minute offset from Coordinated Universal Time UTC for example 2002 9 8T12 6 26 4 0 When the cfwddx tag deserializes WDDX to CFML it automatically uses available time zone information and conv...

Page 702: ...the WDDX data before deserializing it If the WDDX is not valid ColdFusion generates an error By default ColdFusion does not validate WDDX data before trying to convert it to ColdFusion or JavaScript...

Page 703: ...as reached the client successfully document write qj dump true script Note To see how cfwddx Action cfml2js works save this code under your webroot directory for example in wwwroot myapps wddxjavascri...

Page 704: ...Couldn t serialize data Person info recordset with columns firstName and lastName Make sure the case of field names is preserved var personInfo new WddxRecordset new Array firstName lastName true Add...

Page 705: ...ize 5 select br This is where the WDDX packet will be stored In a real application this would be a hidden input field br WDDX packet display br textarea name wddxPacket rows 10 cols 80 wrap Virtual te...

Page 706: ...d a complex data structure cfscript relatives structNew relatives father Bob relatives mother Mary relatives sisters arrayNew 1 arrayAppend relatives sisters Joan relatives brothers arrayNew 1 arrayAp...

Page 707: ...nctionality to perform an application task When you publish a web service you let remote users access your application functionality to build it into their own applications This chapter describes how...

Page 708: ...mplemented in ColdFusion MX or by any application that recognizes the web service standard Accessing a web service In its simplest form an access to a web service is similar to a function call Instead...

Page 709: ...lowing simple figure shows how the ColdFusion MX implementation of web services work The following sections describe the components shown in this figure Supporting web services with SOAP SOAP provides...

Page 710: ...b service Although ColdFusion MX does not directly support UDDI you can manually register or find a web service using a public UDDI registry such as the IBM UDDI Business Registry at the following URL...

Page 711: ...ialog box appears 4 Specify the URL of the WSDL file For more information on using Dreamweaver MX see its online Help system Reading a WSDL file A WSDL file takes practice to read You can view the WSD...

Page 712: ...ollowing are the major components of the WSDL file For additional descriptions of the contents of this WSDL file see Consuming web services on page 713 Component Definition definitions The root elemen...

Page 713: ...rvice in Reading a WSDL file on page 711 If you add the BabelFish web service in Dreamweaver MX you see the following description of it in the Application panel For information on adding a web service...

Page 714: ...weaver MX you see that the data type of the return value is string The following example shows a portion of the WSDL file for the BabelFish web service message name BabelFishRequest part name translat...

Page 715: ...he cfinvokeargument tag and the argumentCollection attribute of the cfinvoke tag To pass parameters using the cfinvokeargument tag you write your call to the web service as the following code shows cf...

Page 716: ...alues from web services by writing them to a variable as the following example shows resultVar webServiceName operationName inputVal1 inputVal2 Or you can pass the return values directly to a function...

Page 717: ...e it uses rpc as the binding style and encoding as the encodingStyle Calling web services from a Flash client The Flash Remoting service lets you call ColdFusion pages from a Flash client but it does...

Page 718: ...guring web services in the ColdFusion MX Administrator The ColdFusion MX Administrator lets you register web services so that you do not have to specify the entire WSDL URL when you reference the web...

Page 719: ...ure For more information on handling complex data types see Handling complex data types on page 728 Consuming ColdFusion web services Your application might consume web services created in ColdFusion...

Page 720: ...es cfc component you see the following definitions that specify the type of the function s input and output as QueryBean wsdl message name echoQueryRequest wsdl part name input type tns1 QueryBean wsd...

Page 721: ...the WSDL file Only those functions marked as remote are accessible as a web service The following list defines the requirements for how to create web services for publication 1 The value of the access...

Page 722: ...nent definition For more information on using components to specify a data type see Using ColdFusion components to define data types for web services on page 724 Producing WSDL files ColdFusion automa...

Page 723: ...eterOrder in0 wsdl input message intf echoStringRequest wsdl output message intf echoStringResponse wsdl operation wsdl portType wsdl binding name echo cfcSoapBinding type intf echo wsdlsoap binding s...

Page 724: ...ce defined you can use components to define data types for web services The following code defines a component in the file address cfc cfcomponent cfproperty name Number type numeric cfproperty name S...

Page 725: ...of the Application panel as the following figure shows The WSDL file for the web service contains data definitions for the complex types name and address Each definition consists of the elements that...

Page 726: ...opens a login prompt containing a username and password field When the user submits this information the browser sends it back to the web server If authentication passes the web server allows access t...

Page 727: ...username password cfheader statuscode 401 cfheader name WWW Authenticate value Basic realm Test cfabort cfif cfsilent This example does not show how to perform user verification For more information...

Page 728: ...s query and struct in the web services you create for publication These types require consumers especially those consuming the web service using a technology other than ColdFusion to create special da...

Page 729: ...ccurs 1 maxOccurs 1 name fname type s string s element minOccurs 1 maxOccurs 1 name lname type s string s element minOccurs 1 maxOccurs 1 name active type s boolean s element minOccurs 1 maxOccurs 1 n...

Page 730: ...hat returned value directly to a ColdFusion variable The previous section used a complex data type named Employee to define an input parameter to an operation A WSDL file can also define a return valu...

Page 731: ...t fname myReturnVar fname realStruct lname myReturnVar lname realStruct age myReturnVar age realStruct hiredate myReturnVar hiredate realStruct number myReturnVar number cfscript Calling IsStruct on r...

Page 732: ...lexType This complex type defines a representation of a structure where the structure keys and values can be any type If you register the component in Dreamweaver MX it appears in the Components tab o...

Page 733: ...AP ENC Array attribute ref SOAP ENC arrayType wsdl arrayType SOAP ENC Array restriction complexContent complexType complexType name ArrayOf_SOAP ENC_string complexContent restriction base SOAP ENC Arr...

Page 734: ...734 Chapter 32 Using Web Services...

Page 735: ...ages and servlets JSP tags Java objects including Enterprise JavaBeans EJBs It does not explain J2EE concepts or how to program using Java or JSP It does explain how to use existing Java and JSP eleme...

Page 736: ...usion MX Administrator For example ColdFusion includes a Copytext sample applet that copies text from one text box to another The ColdFusion Setup automatically registers the applet in the Administrat...

Page 737: ...r ColdFusion MX About ColdFusion and Java objects Java objects include the following Standard Java classes and methods that make up the J2EE API Custom written Java objects including the following Cus...

Page 738: ...iables Because ColdFusion variables are case independent and Java variables are case dependent you must be careful about variable names Use the following rules and guidelines when sharing data between...

Page 739: ...ly However two standard JSP tags provide functionality that is useful in ColdFusion pages the forward and include tags invoke JSP pages and Java servlets The PageContext object described in About GetP...

Page 740: ...es and servlets can share data in three scopes The following sections show how you can use these techniques Integrating JSP and servlets in a ColdFusion application You can integrate JSP pages and ser...

Page 741: ...g table lists the ways that you can access JSP pages with which you want to share the scope data Note When you share data between ColdFusion pages and JSP pages you must be careful about data type con...

Page 742: ...by the tags share the single unnamed application Scope This scope maps directly to the J2EE application scope Similarly all sessions of unnamed applications correspond directly to the J2EE application...

Page 743: ...me name myVariable for each variable GetPageContext include hello jsp name Bobby cfscript Uses the GetPageContext function to get the current servlet page context for the ColdFusion page Uses the incl...

Page 744: ...ll receive the value from the ColdFusion page For example instead of myVariable you could use MYVARIABLE or myvariable on this line br Application myVariable Map application getAttribute m yApp get my...

Page 745: ...s the getAttribute method of the JSP application object to get myApp object the Application scope and casts it to a Map object It then sets the value of myVariable in the myApp application scope objec...

Page 746: ...t is available on the JVM classpath or in either of the following locations In a Java archive jar file in web_root WEB INF lib In a class class file in web_root WEB INF classes For example cfobject ty...

Page 747: ...ty parentheses as in the following cfset tag cfset retVal obj Method1 If the method has one or more arguments put the arguments in parentheses separated by commas as in the following example which has...

Page 748: ...ode the ColdFusion GetPageContext function returns a Java PageContext object and the line invokes the PageContext object s include method Creating and using a simple Java class Java is a strongly type...

Page 749: ...else if Grade equals MANAGER JobGrade 2 else if Grade equals DEVELOPER JobGrade 1 public int GetJobGrade return JobGrade A CFML page that uses the Employee class Save the following text as JEmployee...

Page 750: ...alternate constructor The following ColdFusion page explicitly calls one of the alternate constructors for the Employee object html body cfobject action create type java class Employee name emp cfset...

Page 751: ...des you with the tools to handle ambiguous ones Default data type conversion Whenever possible ColdFusion automatically matches Java types to ColdFusion types The following table lists how ColdFusion...

Page 752: ...es a string variable the other an integer If you write code such as the following which implementation to use is ambiguous cfset emp SetJobGrade 1 The 1 could be interpreted as a string or as a number...

Page 753: ...atch any Throwable errors specify java lang Throwable in the cfcatch tag type attribute The following sections show an example of throwing and handling a Java exception For more information on excepti...

Page 754: ...Fs from the Common Function Library Project http www cflib org It uses the InetAddress class from the standard Java 2 java net package to get the Internet address of a specified host cfscript function...

Page 755: ...itial JNDI naming context These include the INITIAL_CONTEXT_FACTORY and PROVIDER_URL properties You might also need to provide SECURITY_PRINCIPAL and SECURITY_CREDENTIALS values required for secure ac...

Page 756: ...n create name initContext type JAVA class javax naming InitialContext Call the init method provided through cfobject to pass the properties to the InitialContext constructor cfset initContext init pro...

Page 757: ...i arr length i ret arr length i 1 arr i return ret public int Add int a int b return a b public float Add float a float b return a b public Example Add Example a Example b return new Example a mPublic...

Page 758: ...e uses the Example class to manipulate numbers strings Booleans and Example objects The JavaCast CFML function ensures that CFML variables convert into the appropriate Java data types html head title...

Page 759: ...et intarray ArrayNew 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 r...

Page 760: ...760 Chapter 33 Integrating J2EE and Java Elements in CFML Applications...

Page 761: ...Component Object Model or DCOM Distributed Component Object Model and CORBA Common Object Request Broker objects Contents About COM and CORBA 762 Creating and using objects 763 Getting started with CO...

Page 762: ...d by Microsoft to enable component portability reusability and versioning DCOM Distributed Component Object Model is an implementation of COM for distributed services which allows access to components...

Page 763: ...COM and CORBA objects The examples assume a sample object named obj and that the object has a property called Property and methods called Method1 Method2 and Method3 Creating objects You create or in...

Page 764: ...e object changes the value of x it now contains a value other than 23 Calling nested objects ColdFusion supports nested scoped object calls For example if an object method returns another object and y...

Page 765: ...thers require manual registration You can register Inproc object servers dll or ocx files manually by running the regsvr32 exe utility using the following form regsvr32 c path servername dll You typic...

Page 766: ...ed in Registering the object on page 765 The Object Viewer retrieves all COM objects and controls from the Registry and presents the information in a simple format sorted into groups for easy viewing...

Page 767: ...ses the cfobject tag to create the Windows CDO Collaborative Data Objects for NTS NewMail object to send mail cfobject type COM action Create name Mailer class CDONTS NewMail The following line shows...

Page 768: ...t is already running on the server You can use the optional cfobject context attribute to specify the object context If you do not specify a context ColdFusion uses the setting in the Registry The fol...

Page 769: ...ion to release COM objects that are launched as an external process such as Microsoft Excel The garbage collector might not clean these processes in a short time resulting in multiple external process...

Page 770: ...pen the OLE COM Object Viewer 2 Select All Objects under Object Classes in the left pane 3 Locate your COM object The left pane lists these by name 4 Select your object 5 Select the Implementation tab...

Page 771: ...X ships with pregenerated stubs for the Windows XP Windows 2000 and Windows 97 editions of Microsoft Excel Microsoft Word and Microsoft Access ColdFusion MX is configured to automatically use these st...

Page 772: ...bject Note Macromedia uses a package name that starts with coldfusion runtime com com2java for the packages that contain the preinstalled Java stubs for Microsoft Excel Microsoft Word and Microsoft Ac...

Page 773: ...bject definition to the list The object definition consists of the following lines var name progID string PackageName mainClass string var Use the following values in these lines ProgID The COM object...

Page 774: ...k tags in the application that use an Application scope lock share one lock Therefore code that accesses a frequently used COM object inside an Application scope lock can become a bottleneck and reduc...

Page 775: ...ter for the struct key cfset driveSpace curDrive DriveLetter curDrive availablespace cfif cfloop cfreturn driveSpace cffunction Test the function Get the execution time for running the function cfset...

Page 776: ...ch cftry cfset Application mywordobj visible False cfif cflock cfif convert a Word document in temp doc to an HTML file in temp htm Because this example uses a fixed filename multiple pages might try...

Page 777: ...s that you invoke in ColdFusion applications on the server Creating and using CORBA objects The following sections describe how to create or instantiate a CORBA object and how to use it in your ColdFu...

Page 778: ...on the object using the syntax described in Creating and using objects on page 763 The following sections describe the rules for using CORBA objects in ColdFusion pages They include information on usi...

Page 779: ...by reference As a result if the CORBA object modifies the value of the variable that you pass when you invoke the method your ColdFusion page gets the modified value To pass a parameter by reference...

Page 780: ...ypes 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 cfoutpu...

Page 781: ...er string short Integer long Integer float Real number double Real number unsigned short Integer unsigned long Integer void Not applicable returned as an empty string struct Structure enum Integer whe...

Page 782: ...so on In the following example the IDL enumerator a corresponds to 0 b to 1 and c to 2 True yes true or 1 False no false or 0 IDL module Tester interface TManager void testBoolean in boolean a void te...

Page 783: ...and cfcatch tags to catch CORBA object method exceptions thrown by the remote server as follows 1 Specify type coldfusion runtime corba CorbaUserException in the cfcatch tag to catch CORBA exceptions...

Page 784: ...ues of the ColdFusion variables that are used in the object method In a more complete example the information would come from a form query or both The code for the Person and Account structs is straig...

Page 785: ...et p StructNew cfif IsStruct p cfset p pid 1003232 cfset p name Eduardo cfset p middle R cfset p last_name Doe cfif Declare an Account struct cfset a StructNew cfif IsStruct a cfset a person p cfset a...

Page 786: ...786 Chapter 34 Integrating COM and CORBA Objects in CFML Applications...

Page 787: ...s and use the following external services mail servers remote HTTP and FTP servers and files and directories The following chapters are included Chapter 35 Sending and Receiving E Mail 789 Chapter 36...

Page 788: ......

Page 789: ...lete two way interface to mail servers makes the ColdFusion e mail capability a vital link to your users Contents Using ColdFusion with mail servers 790 Sending e mail messages 790 Sample uses of cfma...

Page 790: ...il respectively The following sections describe how to use the ColdFusion e mail features and show examples of these tags Sending e mail messages Before you configure ColdFusion to send e mail message...

Page 791: ...ry 3 Open your browser and enter the following URL http localhost 8500 myapps send_mail cfm email myname mycompany com Replace myname mycompany com with your e mail address The page sends the e mail m...

Page 792: ...the customer inquiry into the database You include the following code on your form so that it executes when users enter their information and submit the form cfmail from Form EMailAddress to marketin...

Page 793: ...le TesterEMail which refers to the TesterEmail column in the Betas table in the to attribute enables the dynamic list cfquery name BetaTesters datasource myDSN SELECT FROM BETAS cfquery cfmail query B...

Page 794: ...rification Dear GetCustomers FirstName We d like to verify that our customer database has the most up to date contact information for your firm Our current information is as follows Company Name GetCu...

Page 795: ...l network not the browser machine Code Description cfquery name GetCustomers datasource myDSN SELECT FROM Customers cfquery Retrieves all data from the Customers table into a query named GetCustomers...

Page 796: ...y are spooled to disk and processed in the background This architecture has two advantages End users of your application are not required to wait for SMTP processing to complete before a page returns...

Page 797: ...geted mail clients to suit the specific needs of a wide range of applications The cfpop tag does not work with the other major e mail protocol Internet Mail Access Protocol IMAP Here are three instanc...

Page 798: ...rd number information RecordCount The total number of records returned by the query CurrentRow The current row of the query being processed by cfoutput or cfloop in a query driven loop You can referen...

Page 799: ...HeaderOnly name Sample cfoutput query Sample MessageNumber HTMLEditFormat Sample messageNumber br To HTMLEditFormat Sample to br From HTMLEditFormat Sample from br Subject HTMLEditFormat Sample subjec...

Page 800: ...rs that have meaning in HTML such as the less than and greater than signs that can surround detailed e mail address information with escaped characters such as lt and gt In addition you can process th...

Page 801: ...com username myusername password mypassword action GetAll name Sample cfoutput query Sample MessageNumber HTMLEditFormat Sample messageNumber br To Sample to br From HTMLEditFormat Sample from br Sub...

Page 802: ...to store attachments ColdFusion retrieves any attachment files from the POP server and saves them in the specified directory The cfpop tag also adds the following two columns to the query it creates...

Page 803: ...r HTMLEditFormat Sample MessageNumber br To HTMLEditFormat Sample to br From HTMLEditFormat Sample from br Subject HTMLEditFormat Sample subject br Date HTMLEditFormat Sample date br Cc HTMLEditFormat...

Page 804: ...fpop to delete a message permanently removes it from the server If the messagenumber does not correspond to a message on the server ColdFusion generates an error Note Message numbers are reassigned at...

Page 805: ...server username and password cfpop server mail company com username username password password 3 Save the file as message_delete cfm in the myapps directory under your web_root and view the file in y...

Page 806: ...806 Chapter 35 Sending and Receiving E Mail...

Page 807: ...nd File Transfer Protocol FTP communications in a simplified tag syntax that lets you extend your site s offerings across the web Contents About interacting with remote servers 808 Using cfhttp to int...

Page 808: ...ing cfhttp to interact with the web The cfhttp tag which lets you retrieve information from a remote server is one of the more powerful tags in the CFML tag set You can use one of two methods Get or P...

Page 809: ...ith another URL and change the filename 3 Optional Change the path from C temp to a path on your hard drive 4 Save the page as save_webpage cfm in the myapps directory under your web_root directory 5...

Page 810: ...to view the MIME type 5 Optional Verify that the binary file now exists at the location you specified in the path attribute Reviewing the code The following table describes the code and its function...

Page 811: ...ifier is use to include a quotation mark in the field The first row of text is always interpreted as column headings so that row is skipped You can override the file s column heading names by specifyi...

Page 812: ...eturns data For example when you build an HTML form using the Post method you specify the name of the page to which form data is passed You use the Post method in cfhttp in a similar way However with...

Page 813: ...file was uploaded to File ServerDirectory File ServerFile cfoutput body html Code Description cfhttp method Post url http 127 0 0 1 8500 myapps post_test_server cfm Post an HTTP request to the specif...

Page 814: ...nation C temp nameconflict Overwrite filefield Form myfile action Upload attributes Normal Write the transferred document to a file on the server You send the file using the cfhttpparam type File attr...

Page 815: ...rt FTP operations and additional details on using the cfftp tag see CFML Reference To open an FTP connection and retrieve a file listing 1 Create a ColdFusion page with the following content html head...

Page 816: ...f an error occurs stop processing and display an error You can use this connection in other cfftp tags by specifying the Myftp connection cfftp connection Myftp action GetCurrentDir stoponerror Yes cf...

Page 817: ...t the same time Creating a session variable for a cfftp connection makes more sense because the connection is available to only one client and does not last past the end of the session Example caching...

Page 818: ...specify an existing connection name you must specify the username password and server attributes Action Attributes Action Attributes Open none Rename existing new Close none Remove server item Change...

Page 819: ...ing files from a client to the web server viewing directory information and changing the content type that is sent to the web browser To perform server to server operations use the cfftp tag described...

Page 820: ...a text file Note 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 MX Administrator Also t...

Page 821: ...file as uploadfileaction cfm in the myapps directory under your web_root 4 View uploadfileform cfm in the browser enter a file to upload and submit the form The file you specified uploads Code Descrip...

Page 822: ...not resemble the attempted name For more information on file upload status variables see Evaluating the results of a file upload on page 824 Controlling the type of file uploaded For some application...

Page 823: ...egardless of the format cffile action Upload fileField Form FiletoUpload destination c uploads nameConflict Overwrite accept image Setting file and directory attributes In Windows you specify file att...

Page 824: ...ffile operation The following table describes the file upload status variables that are available after an upload Variable Description attemptedServerFile Initial name that ColdFusion uses when attemp...

Page 825: ...oldFusion saved the uploaded file oldFileSize Size of the file that was overwritten in the file upload operation Empty if no file was overwritten serverDirectory Directory where the file was saved on...

Page 826: ...he string replacement functions to modify the contents To read a text file 1 Create a ColdFusion page with the following content html head title Read a Text File title head body Ready to read the file...

Page 827: ...Name Form Message body html 2 Modify the path C inetpub wwwroot mine to point to a path on your server 3 Save the file as writetextfileaction cfm in the myapps directory under your web_root 4 View th...

Page 828: ...Directory entry size type File type File or Dir dateLastModified Date an entry was last modified attributes Windows only File attributes if applicable mode UNIX only The octal value representing the p...

Page 829: ...y size td td mydirectory type td td mydirectory dateLastModified td td mydirectory attributes td td mydirectory mode td tr cfoutput table body html 2 Modify the path C inetpub wwwroot mine so that it...

Page 830: ...file A MIME content type consists of type subtype format The following are common MIME content types text html image gif application pdf Changing the MIME content type with cfcontent You use the cfco...

Page 831: ...ur web_root and view it in the browser The text of the called file cfcontent_message htm displays as normal HTML as shown in the following figure 6 In cfcontent cfm change type text html to type text...

Page 832: ...bChar Chr 9 cfset NewLine Chr 13 Chr 10 set content type to invoke Excel cfcontent type application msexcel suggest default name for XLS file use Content Disposition in cfheader for Internet Explorer...

Page 833: ...variables configuring 330 description 270 316 listing 332 usage tips 331 using 330 application defined exception 289 application level settings 269 Application cfm file application level settings 272...

Page 834: ...110 ArraySort CFML function 118 ASCII 374 assignment CFScript statements 132 attributecollection reserved attribute 180 attributes for custom tags 178 passing values 177 178 Attributes scope 44 73 au...

Page 835: ...t 50 OnRequestEnd cfm 271 cfapplet tag description 585 using 606 608 cfapplication tag 319 cfassociate tag 188 cfbreak tag 48 cfcache tag 277 cfcache tag location of tag 278 cfcase tag 48 cfcatch tag...

Page 836: ...data 438 cfinvoke tag example 715 invoking component methods 226 passing parameters with 228 web services consuming 713 714 within a component definition 228 cfinvokeargument tag 715 cfldap tag about...

Page 837: ...Locale 376 SetVariable 97 StructClear 121 StructCount 117 StructDelete 121 StructIsEmpty 118 StructKeyExists 118 StructKeyList 118 StructNew 116 syntax 88 URLEncodedFormat 407 XmlChildPos 676 XmlElemN...

Page 838: ...ing 391 Windows NT and 391 cfstoredproc tag 281 cfswitch tag 48 cftextinput tag browser considerations 585 handling failed validation 614 validating with JavaScript 613 cfthrow tag nesting 309 using 3...

Page 839: ...s errors 565 lists of values 576 multiple 576 child tags 186 class loading Java 256 mechanism 737 class reloading automatic 257 classes debugging 260 classpath configuring 253 Java objects and 737 cli...

Page 840: ...g started 764 requirements 765 setting properties 768 threading 770 using properties and methods 768 viewing objects 766 WDDX and 697 COM objects Application scope using 774 calling 764 connecting to...

Page 841: ...case considerations 779 character encodings 386 description 762 double byte characters 783 example 784 exception handling 783 getting started 777 interface 763 interface methods 778 naming services 7...

Page 842: ...bleshooting 407 types of 428 657 data types about 44 binary 46 55 complex 45 55 considerations 56 conversions 67 default conversion 751 in CFML 45 object 46 55 simple 45 55 validating 80 81 variables...

Page 843: ...391 output format 390 programmatic control of 400 SQL queries 396 stored procedures 397 debugging output cfquery tag 400 cfsetting tag 400 classic 390 database activity 396 dockable 390 399 exception...

Page 844: ...ays and 94 example 99 limitations 94 pound signs in 93 selecting 93 structures and 94 using 94 E e mail adding custom header 796 attachments 795 802 character encodings 386 checking for spooled 796 cu...

Page 845: ...dation error page 297 variable locking 340 web server based authentication 358 web services consuming 715 web services publishing 723 Excel spreadsheet from cfcontent tag 832 exception handling cfcatc...

Page 846: ...rview 642 Flash scope 45 74 Flash ColdFusion connectivity and 32 flow control tags 47 for loop CFScript 135 for in loop CFScript 137 form controls cfform 584 description 561 form fields required 579 v...

Page 847: ...vigating 596 See also cfgrid tag GROUP BY SQL clause 416 H handling applet form variables 609 exceptions 299 failed validation 614 POP Mail 798 hidden fields 579 horizontal bar charts 631 HTML using t...

Page 848: ...ML function 677 IsXmlElem CFML function 677 IsXMLRoot CFML function 677 J J2EE application server benefits 33 ColdFusion MX and 33 GetPageContext 738 infrastructure 33 introduction 33 PageContext 738...

Page 849: ...496 directory DN 497 distinguished name 480 DN 497 entry 480 object classes 481 querying directories 483 referrals 502 schema 481 schema attribute type 482 scope 483 search filters 483 security 366 sy...

Page 850: ...ode Compatibility Analyzer 405 MIME type 830 missing files exceptions 303 missing template errors 290 modifiers explicit queries 539 searching 551 MonthAsString CFML function 110 moving data across th...

Page 851: ...arent tags 186 passing arguments 202 arrays to user defined functions 210 custom tag attributes 177 178 custom tag data 187 queries to user defined functions 208 passthrough attribute 584 password get...

Page 852: ...reserved words 471 syntax 474 unions 463 user guide 462 using 452 Query CFX object 256 query columns 64 query functions 452 Query object 256 query objects 62 452 query properties guidelines for 434 q...

Page 853: ...pages servlets 741 user defined functions and 208 requests globalization and 377 requiring form entries 566 reserved words in CFML 51 list of 51 reserved words CFScript 131 reset buttons 561 resolving...

Page 854: ...ldcards 540 searching case sensitivity 542 cfsearch tag 523 character encodings 387 collections 506 collections creating 511 creating index summaries 525 database records 526 external Verity collectio...

Page 855: ...efaults 274 bar chart characteristics 631 client variable options 321 file and directory attributes 823 pie chart characteristics 632 setting up C development environment 261 Java development environm...

Page 856: ...pying 119 creating 116 custom tag 178 declaring 778 deleting 121 example 122 finding keys 118 functions 125 getting information on 117 in dynamic expressions 94 listing keys in 118 looping through 121...

Page 857: ...ncodedFormat CFML function 407 URLs character sets 384 encoding 383 384 invoking components with 230 user edits returning 600 user ID getting 353 356 user roles 348 user security See security user def...

Page 858: ...6 kinds of 44 lists 58 locking example 340 naming 178 naming rules 54 numeric 56 objects 55 passing 663 808 persistent 316 processing 560 queries 62 real numbers 57 Request scope 187 scopes 44 63 75 s...

Page 859: ...19 UDDI and 709 WSDL file Web Services Description Language file about 708 See also WSDL web services consuming about 708 cfinvoke tag 713 714 CFScript for 716 ColdFusion MX 719 ColdFusion MX Administ...

Page 860: ...ncing 677 transforming XSLT 691 using 677 XmlComment 674 XmlDocType 674 XmlRoot 674 XPath 692 XSLT 691 XML elements adding 686 attributes 689 child elements 685 children of 683 copying 687 counting 68...

Reviews: