This chapter on Adobe ColdFusion, elaborates on the basics of this HTML-like language. It starts with the by introducing the viewer/reader with the variables, comments and the tags that are behaves like HTML, yet can alternatively be made to syntactically look like other programming languages like PHP. Then, it moves onto examples that demonstrates the ability of structures, lists, variables, loops, conditionals and finally the switch-case statement. This presentation concisely attempts to show the prospective CF programmer that how a old code can be recycled, reinvented, innovated and at the same time made as safe as possible, after all, security is a major concern in today's world.
2. Overview : What is ColdFusion
•An application server that uses the CFML language
•CFML = ColdFusion Markup Language
•CFML uses tags and attributes that appear similar to html
•CFML in simple term is the marriage between static markup and programming language
•CFML helps to turn static HTML pages into dynamic page
•Every script written in CFML need to end with .cfmextension
3. Communication in HTML styleReceive Request+ Retrieve HTML page for directory+ Send back staticHTML page
Client Request HTML page
Server
User browserSend request
Return HTML
HTML way of client-server interaction
Get / HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0 (Windows …
Connection: Keep-Alive
request -line
header
HTTP/1.1 200 OK
Date: 1/1/11 09:44
Content-type: text/hml; charset=ISO-8859- 1
Content-length: 122
<html>
<head><title>Google</title></head>
<body></body>
</html>
status- line
response- body
blank line
Request
Response
blank line
4. Receive Request
+
Get file from server
+
Process ColdFusion page code
+
Send back DynamicHTML pageReceive Request+ Request coldfusionpage+ Generate static HTML + Send HTML pageSend page request
Send request
Server
ColdFusion
Return HTML
Return HTML
Send request
Communication in CFML style
CFML way of client-server interaction
User browser
6. TIME TO LEARN THE BASICS!
Variables & Comments, Arrays, Conditionals, Switch-case statements, Lists & Loops, Structures
7. Variable rules
•Creating a variable using <cfset> or <cfscript></cfscript> tag:
–<cfset variable_name= “anything string”>
Or
<cfscript>
myvariable= “anything”
</cfscript>
–Referring a CF variable anywhere else requires to be wrapped in pound(#) sign like:
<html>
<cfoutput>
<body> #myvariable# </body>
</cfoutput>
</html>
•CF comment is quite similar to HTML comment
―<!---This is a CF comment ---> |
―<!--This is an HTML comment -->
•Variables have 4 types:
—String
—Numeric
—Boolean &
—Date or time
•Variables can’t have spaces and are not case sensitive in CF
•Strings can have
—Single or double quotation marks
—Case sensitive
•In numeric classes two types will be covered
—No quotation marks
—Integer (range:
-2,147,483,648 to 2,147,483,647)
—Decimal
8. Example Time!
<!---Writing my name --->
<cfset myName= "Nafis Ahmed" />
<!---Writing my age --->
<cfscript>
myAge= 19;
</cfscript>
<html>
<body>
<cfoutput>
<h3>My name is #myName#</h3>
<p>My age is #myAge#</p>
</cfoutput>
</body>
</html>
Ex:1
<cfscript>
myQuestion= "What's your name and age?";
myAge= 19;
myAge+=1;
myQuestion= myQuestion& "You'll find it out soon.";
</cfscript>
<html>
<body>
<cfoutput>
my question was #myQuestion#. <br/>
my age was #myAge#.
</cfoutput>
</body>
</html>
Ex:2
Strings & Integers
9. <cfscript>
myAge= 19;
halfAge= myAge/2;
</cfscript>
<html>
<body>
<cfoutput>
my age is #myAge#
<br/>
my half age is #halfAge#
<br/>
rounding 1.1 = #round(1.1)#
<br/>
ceiling 1.1 = #ceiling(1.1)#
</cfoutput>
</body>
</html>
Strings &Decimals
Ex:3
<cfscript>
myLocation= "Dhaka City";
locationDescrip= "Capital of Bangladesh";
addStrings= myLocation& locationDescrip;
searchWord= Find(“capital", addStrings);
</cfscript>
<!---You can also use if you want it to be non case sensitive - -->
<cfscript>
searchWord2 = FindNoCase("Capital", addStrings);
</cfscript>
<html>
<body>
<cfoutput>
<p>I live in #myLocation# which is the #searchWord#thcity of Bangladesh. I guess....</p>
<p>I live in #myLocation# which is the #searchWord2#th city of Bangladesh. I guess....</p>
</cfoutput>
</body>
</html>
Ex:4
10. Structures
•Structures are another type of variables that work like hierarchies of file systems in a computer
•Structures can either be empty or can contain additional nested structures or variables
•All structures have their own base/foundation structure onto which other variables and nested structures are built
–The nested variables and structures are called by their name using a dot(.) notation like: base_structure_name.nested_structure
–Ex: The built-in CGI structure can be used as an example, which is generally used as a debugging tool in Coldfusion. The variables in the CGI are called using the dot notation: cgi.server_name
–The attribute cgi.server_nameis used inside the tag <cfdump>to view server, port, current request and other server-side information
<cfdumpvar=“#cgi.server_name#”>
–<cfdump>tag is used to show complex data types in simple grid forms
–Besides <cfdump> tag, the CGI structures and variables can be called inside a <cfscript> tag
11. Using Structures 1
•Using the CGI variables inside a <cfscript> tag
<cfscript>
domainName= cgi.server_name;
securePort= cgi.server_port_name;
</cfscript>
<cfoutput>
The domain name #domainName# and is it using secure port(0=No/1=Yes)? #securePort#
</cfoutput>
13. Query String with Structures
•A query string is used to pass information directly into the script through the URL (uniform resource locator).
–Usually this done by declaring a variable and initializing it with data/information/value
–A query string starts with question mark(?) symbol and it must be placed after the web address
–Ex: www.anything.com/script.cfm?name=Nafis
–Additional variables can be declared using the ampersand(&) symbol like: ?name=Nafis&age=199
–The script, on which the query string is called, need to output the value in order for the web page to print the data/value on the browser for the user
•Variables inside structures or structures themselves can be called through query strings
•URL variables can be used for error/exception handling, in which a missing variable is grabbed and outputted on the browser
14. URL-Page Default & Exception Handling with Structure
•Exception handling uses the try-catch block, that implements <cftry> & <cfcatch> tags, to catch errors and display them in an organized manner defined by the programmers
–The debugging tools provide a detailed reporting on errors that occur due to programming flaws
•Page defaults act as an aspect of error/exception handling
–Exception Handling is the way a bug(programming glitch)/error is handled neatly and shown on the screen in an organized manner, rather then the computer whining about it in a disconcerted manner!!
•Example code demonstrating a default name if a name has not been set
<cfparamname=“url.name” default=“Who are you DUDE?”>
<cftry>
<cfoutput>
Your are logged in as: #url.name#
</cfoutput>
<cfcatch>
<cfdumpvar=“#cfcatch#”>
</cfcatch>
</cftry>
15. URL-Page Default with Structure: Demonstration
Passing A Query String
URL without a query string
16. Connecting Query String with Static Links
•This static link points back to the dynamic page
–<cfparamname=‘url.name’ default=‘Who are you DUDE?’>
<cftry>
<cfoutput>
You are logged in as: #url.name#
<a href=‘?name=Nafis’>Click this link to view your name as Nafis</a>
<a href=‘?name=Ahmed’>Click this link to view your name as Ahmed</a>
</cfoutput>
<cfcatch>
<cfdumpvar=‘#cfcatch#’>
</cfcatch>
</cftry>
–Clicking each of the links will connect back to the <cfparam> tag and the name attribute will hold the value (Nafis or Ahmed) and print it on the browser
18. Creating Custom Structures with Query String
•A new structure is declared by calling the function structNew()
•The structNew() function must be called as a value during a variable declaration
–Ex: myHouse= structNew();
•The new structure can be used to create and organize nested variables
–Ex: myHouse.description= ‘My house is in a lonely place’;
•Entire script on declaring a custom structure and passing it onto a query string
–<cfparamname="url.windows" default=5>
<cfparamname="url.doors" default=12>
<cfscript>
myHouse= structNew();
myHouse.description= "My house is in a lonely place";
myHouse.windows= url.windows;
myHouse.windows+= url.doors;
</cfscript>
<cfoutput>
#myHouse.description#
<a href="?doors=-1&windows=#myHouse.windows#">Click this to remove a window</a>
<a href="?doors=1&windows=#myHouse.windows#">Click this to add a window</a>
<cfdumpvar="#myHouse#" label="My House">
</cfoutput>
20. Understanding Lists
•Lists are variable values that uses delimiter/separator to separate each value from the other
•Lists are generally stored inside variables as string variables
•In Coldfusion, lists come with their own built-in functions that help with searching, parsing, appending, which extends to support other additional features
–Ex: listGetAt(variable_to_look_from, numeric_position_of_list_item)
•An example of using list:
–<cfparamname=“url.speed” default=“10”>
<cfparamname=“url.acceleration” default=“0”>
<cfscript>
questions = “What is the speed limit in your area?,who’sthe manufacturer of your car?,Whatis the price tag?”
</cfscript>
<cfoutput>
The third question is : #listGetAt(questions, 3)#
</cfoutput>
21. Understanding Loops with Lists
•Loops are used to repeat/iteratea code as many times as required, saving the programmer from typing the same code again and again
–Ex: if a programmer wants to print all the odd numbers, rather than typing them manually, a loop can be used to do the task, saving him from endless typing
•Lists, in Coldfusion, can be linked with loops. A loop can iterate through a list and print/show them in an organized fashion
•A loop starts with the <cfloop>tag and ends with </cfloop>element and takes several attributes, such as list and index
•In CF 10, traditional while-loop, for-loop and do-while loop can be used in the same way
•Extending the previous code with <cfloop>
<cfscript>
paramname = "url.question" type="any" default="what is the speed limit in your area?";
questions = "what is the speed limit in your area?, who's the manufacturer?, what is the price tag?";
answers = "30 maybe, Toyota, Don't know";
fromUrl= ListContains(questions, url.question);
</cfscript>
<cfoutput>
<strong>Questions:</strong>
#ListGetAt(questions, fromUrl)#<br>
<strong>Answers:</strong>
#ListGetAt(answers, fromUrl)#<br>
</cfoutput>
<cfloopindex="iQuestion" list="#questions#">
<cfoutput>
<a href="?question=#iQuestion#">
#iQuestion#
</a><br>
</cfoutput>
</cfloop>
22. Demo For Lists
•Clicking each of the links changes the query string in the URL and replaces the old question and answer with the new clicked question and answer in the Questions & Answers part
23. Organizing Code with Arrays
•Alien Language: Arrays are variable constructs that organize variables with index/numerical sets
•Human Language: Arrays are lists too. In an array, each list item/element is assigned a numerical value/index by theprogrammer not by the compiler
•Arrays have dimensions and the maximum dimension is 3
•To remove or add or insert a value in a array, the built-in CFML functions must be used
–Ex: ArrayInsertAt(), ArrayDelete(), ArrayClear()
•Re-creating the previous code with a 1-dimensional/1D array
<cfscript>
paramname = "url.questions" default="1" type="any";
questions = ArrayNew(1);
questions[1] = StructNew();
questions[1].question = "what is the speed limit in your area?";
questions[1].answer = "30 maybe";
questions[2] = StructNew();
questions[2].question = "who's the manufacturer?";
questions[2].answer = "Toyota";
questions[3] = StructNew();
questions[3].question = "what is the price tag";
questions[3].answer = "Don't Know";
</cfscript>
<cfoutput>
<strong>Questions</strong>
#questions[url.questions].question#<br>
<strong>Answer</strong>
#questions[url.questions].answer#<br>
</cfoutput>
<cfloopfrom="1" to="#ArrayLen(questions)#" index="questionArray">
<cfoutput>
<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>
</cfoutput>
</cfloop>
<cfdumpvar="#questions#">
24. Same Thing Man!
•It’s just the same thing but, although the code is more elaborate than the code written with list, it is more organized and easily accessible
•As the blue-links are clicked, the query string holds the index number of the question & answer, keeping the URL cleaner
25. Playing with ifconditioning
•Seriously, if you’re familiar with other programming languages, then you should feel sad by knowing that in CFML conditionals does the same thing but they don’t have symbols for logic(=, <, >, >=)but words (EQ, LT, GT, GTE)
•If you don’t have any idea about conditional statements, then remember that, in any programming language, conditional statements are used to tell the program what to do if a certain situation is met and what to do in case if the situation is not met
•Ex: Suppose a user comes to your site and wants a picture of an ice-cream, your program should display the image as requested. Behind the scenes, your program should read like: ‘ifice-cream is requested then display ice-cream image, elsedon’t display anything’
•In CFML, <cfif></cfif> tag pairs are used to start and end a conditional block.
–Additionally, for programming geeks, if you want to look mature then you can go on using the theif block inside a <cfscript>. Be professional!
26. From Symbols to Words: Comparison Operators
•To compare between to values CFML uses short-hand Uppercase words not symbols
Comparisonwords (Alien-Form)
Meaning
(Human-Form)
Equivalentsymbols in other languages
ET/IS
Equal to
==
GT
Greater
>
GTE
Greater thanequal to
>=
LT
Less than
<
LTE
Less thanequal to
<=
NOT
Negating/makingthe statements meaning opposite
!
27. Reinventing the Questionnaire: Mature Way
<cfscript>
paramname = "url.questions" default="1" type="any";
questions = ArrayNew(1);
questions[1] = StructNew();
questions[1].question = "what is the speed limit in your area?";
questions[1].answer = "30 maybe";
questions[2] = StructNew();
questions[2].question = "who's the manufacturer?";
questions[2].answer = "Toyota";
questions[3] = StructNew();
questions[3].question = "what is the price tag";
questions[3].answer = "Don't Know";
if(! isNumeric(url.questions)) {
url.questions= 1;
}else {
url.questions= Round(url.questions);
if(url.questions< 1) {
url.questions= 1;
}else if(url.questions> ArrayLen(questions)) {
url.questions= 1;
}
}
</cfscript>
<cfoutput>
<strong>Questions</strong>
#questions[url.questions].question#<br>
<strong>Answer</strong>
#questions[url.questions].answer#<br>
</cfoutput>
<cfloopfrom="1" to="#ArrayLen(questions)#" index="questionArray">
<cfoutput>
<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>
</cfoutput>
</cfloop>
Using if conditional inside <cfscript> tag-the mature way:
28. Reinventing the Questionnaire: Amateur Way
•Using the <cfif> <cfelse> </cfif> tags as conditionals
<cfscript>
paramname = "url.questions" default="1" type="any";
questions = ArrayNew(1);
questions[1] = StructNew();
questions[1].question = "what is the speed limit in your area?";
questions[1].answer = "30 maybe";
questions[2] = StructNew();
questions[2].question = "who's the manufacturer?";
questions[2].answer = "Toyota";
questions[3] = StructNew();
questions[3].question = "what is the price tag";
questions[3].answer = "Don't Know";
</cfscript>
<cfifNOT isNumeric(url.questions)>
<cfset url.questions= 1>
<cfelse>
<cfset url.questions= round(url.questions)>
<cfifurl.questionsLT 1>
<cfset url.questions=1>
<cfelseifurl.questionsGT ArrayLen(questions)>
<cfset url.questions= 1>
</cfif>
</cfif>
<cfoutput>
<strong>Questions</strong>
#questions[url.questions].question#<br>
<strong>Answer</strong>
#questions[url.questions].answer#<br>
</cfoutput>
<cfloopfrom="1" to="#ArrayLen(questions)#" index="questionArray">
<cfoutput>
<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>
</cfoutput>
</cfloop>
29. No Change BUT Safe!
•The page to the user remains as it was but behind the scene codes did change which will stop cyber marauders from tampering the URL
–The query string (underlined in red) has a variable questions with a value of 9 but the page is only displaying the default question and answer, that is the first question and its corresponding answer
30. Conditional with Switch-Case Statements
•If you want to output something when your given condition is met, then switch-case has got the answer
–Ex: A code can be written in which, if suppose a user wants the second question then the program displays the second question. If the user wants the third question, then the program prints out the third question and if the request is for the first question, then the first question is printed out but if none of the above specified, then the program asks the user which question does he/she wants
•Switch-case statements have similar syntaxes like other languages when written inside the <cfscript></cfscript> tag pair
switch(expression) {
case “condition-1”:
//perform something if this condition is met
break;
case “condition-2”:
//perform something if this condition is met
break;
default:
//perform something if this condition is met
}
•Switch-case statements have their own tags, which are also applicable in CF 9+
<cfswitchexpression=“any_expression_that_will_be_matched”>
<cfcasevalue=“any_value_that_is_valid_to_match”>
<!---Any applicable code for execution --->
</cfcase>
<cfdefaultcase> <!---If none of the above conditions are executed, then execute this---></cfdefaultcase>
</cfswitch>
31. Switch-Case in Code: Mature Way
<cfscript>
paramname = "url.questions" default="1" type="any";
questions = ArrayNew(1);
questions[1] = StructNew();
questions[1].id = "a";
questions[1].question = "what is the speed limit in your area?";
questions[1].answer = "30 maybe";
questions[2] = StructNew();
questions[2].id = "b";
questions[2].question = "who's the manufacturer?";
questions[2].answer = "Toyota";
questions[3] = StructNew();
questions[3].id = "c";
questions[3].question = "what is the price tag";
questions[3].answer = "Don't Know";
switch(url.questions) {
case "a":
questions[1].question;
questions[1].answer;
break;
case "b":
questions[2].question;
questions[2].answer;
break;
case "c":
questions[3].question;
questions[3].answer;
break;
default:
questions[1].question;
questions[1].answer;
}//end switch
</cfscript>
<cfoutput>
<strong>Questions</strong>
#questions[url.questions].question#<br>
<strong>Answer</strong>
#questions[url.questions].answer#<br>
</cfoutput>
<cfloopfrom="1" to="#ArrayLen(questions)#" index="questionArray">
<cfoutput>
<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>
</cfoutput>
</cfloop>
33. Uh-Ah, Not Again..!
•Just the same ol’ picture but there is a change inside the code.
•You can use as many casestatements for any number of possibilities as you want in a switch-casestatement
•In the image below, as there is query string, the defaultclause has been executed: