Session 2: ColdFusion MX
ColdFusion Markup Language
The CFML is the tool by which we express our ideas, conditions and goals for the applications in this course. CFML is a tag based scripting language . As any other programming language, CFML has its own syntax, but can be intermixed with HTML . As a scripting language, it has borrowed a number of concepts from PERL and other programming languages.
A CFMX script are stored in one or more files with the extension .cfm . These files are referred to as CFML templates. The extension makes it possible for the web server to identify which requests it should pass on to the CFMX applications server. No harm is done if a usual HTML page are named with the .cfm extension, but a CFML template with a .htm or .html will not work. In this course, we use the .cfm extension for all templates.
The first difference you will observe between HTML pages and a CFML templates, is the CF tags permitted in the latter. All CFML tags starts with the 2 letters CF . Most CF tags come in pairs with a starting and an ending tag with the form <CF..> and </CF..> , respectively.
When you try to view the source of a page generated by a CFML templates clicking the View/Source option in your browser, you will only see the HTML source sent for display. The .cfm template, which generated the HTML display, will not be available for the client.
CFML has the following components:
- Data types
- Variables
- Expressions
- Control statements
- Other components
In this session, we shall review each component. This session is a brief summary of CFML . For more details and precise description, you are referred to RBB . Special topics will be discussed in each session and illustrated by implemented examples which you can run, copy, modify and try on your own PC .
Data types
As any language, CFML supports a set of different data types :
- Boolean
- Strings
- Numbers
- Date/time
- Lists
- Arrays
- Structures
- Query objects
- Component objects
Any data type variable can be assign a value directly or by special functions in a CF tag.
Variables
There are 3 aspects associated with a variable which you should keep in mind:
- Name
- Value
- Scope
The variable name identifies the variable, and must begin with a letter, contain no spaces or special characters and should not be identical to reserved names in CFML or SQL . The value is either numeric, logical or string. A string is enclosed by single or double quotes . The CFML variables are all type less which means that you can assign a value of any type to any variable. However, the use of a variable can be restricted by the data type of its value.
A variable is most frequently defined by the CFSET tag:
<CFSET variable_name="xxx">
The value you substitute for xxx in the tag is the assigned value of the variable here symbolized by variable _name
The value of a defined variable can be obtained by surrounding the variable name with # , i.e. #variable_name# . This can be used in another set tag, for example for counting:
<CFSET new_ variable=#variable _name# + 1>
The scope of a variable is in general limited to the template in which it is set. As we shall se later, the variables are frequently given wider scopes.
Expressions
In CF , an expression is a construct in which data are acted on by different operators. By means of an expression, the result of operators acting on variables can be evaluated. There are 2 categories of operators:
- Basic operators
- Functions
The basic operators are of four types:
- Arithmetic
- Comparison
- String
- Boolean
Well known arithmetic operators are + , - , / and * , exemplified by:
<CFSET evaluation _variable=(#new_variable# +2)/5>
where new_variable has already been assigned some value by previous operations.. The result of an arithmetic expression is a new value assigned to a numeric variable named in this example evaluation _variable with value #evaluation _variable# .
The comparison operators require 2 values and give a Boolean result, 0 (false) or 1 (true). Some of the most frequently used comparison operators are EQ , NEQ , GT , GTE , LT and LTE . The following expression illustrates use of a comparison operator:
<CFSET x=#new_ variable# EQ 3>
where #x# will be a Boolean variable assigned the value false (0) if # new_variable# NOT EQ 3, or true (1) if # new_variable# EQ 3 .
A string is a sequence of symbols. The concatenation operator, & , is used for concatenating 2 strings. There are also 2 operators for string comparison , CONTAIN and DOES NOT CONTAIN , by which 2 strings can be compared. The result of the concatenation is a string, while the 2 comparison operators result in Boolean values.
In the group of Boolean operators , the usual logical operators NOT , AND , OR , XOR , EQ and IMP , are available. An expression with logical operators gives a Boolean result.
Functions are advanced operators with pre-defined actions on data values. There are a number of different types of functions built into ColdFusion:
- Array functions
- Date/time function
- Decision/evaluation functions
- Encoding /encryption functions
- File/directory functions
- Formatting functions
- International functions
- List functions
- Mathematical functions
- Miscellaneous functions
- Query functions
- Security functions
- String functions
- Structure functions
- Undocumented functions
You are referred to RBB , Appendix B, and the literature for details about the individual functions available in CFMX .
Flow control statements
Flow control and decision making , requires control statements. CFMX has 3 different types of conditional control statements:
- If/else statements
- Switch statements
- Loop statements
The syntax for the two-way branching if/else statements is:
<CFIF "logical_expression EQ True">
execute block 1
<CFELSE>
execute block 2
</CFIF>
The logical expression can for example be #y# GT #x# .
The multi-way branching switch statement complex has the following syntax:
<CFSWITCH EXPRESSION="expression">
<CFCASE VALUE="value1">
execute block1
</CFCASE>
<CFCASE VALUE="value2">
execute block 2
</CFCASE>
<CFCASE VALUE="value3">
execute block 3
</CFCASE>
....
</CFSWITCH>
The expression is assumed to be valid, possible to evaluate and producing a value compatible with the values in the CFCASE tags..
There are several types of loops . We illustrate the loop statements with the simplest, often referred to as the FOR loop:
<CFLOOP INDEX="LoopCount" FROM="start_no" TO="end_no">
execute block
</CFLOOP>
#LoopCOUNT# will be incremented by 1 for each loop started. It starts with the value assigned to start_no and end with the value specified for end_no .
Other components
There are other language components in CFML the most common of which are:
- Output
- Include
- Comments
The output tag permits displays of the results from CFMX operations, for example the results from a database query:
<CFOUTPUT QUERY="query_name" MAXROWS="max" GROUP="group" STARTROW="row">
Text
</CFOUTPUT>
where query_name is a name given in a previous query tag, max is the maximum number of rows wanted, and row specifies the row from which to start output. This tag generates a display of the content of a collected query object.
The CFINCLUDE tag permits reference to another CF template. The syntax is simple:
<CFINCLUDE TEMPLATE="template_name">
where template_name is the absolute URL or the relative address to the template. This tag functions similar to a call to a subroutine.
CFML also includes a tag for non-executive remarks . It is similar but not identical to the HTML remark tag:
<!--- text --->
The three dashes and a blank before, and a blank and three dashes following the text are required, in contrast to the HTML remarks with two dashes before and after the text.
Guessing game example
This example, as all examples in this course, is implemented for you to try out. For running the example, a link is provided at the end of the session. The example is a simple guessing game. You will be asked to guess the sum of all integers from 1 and up to a number which is generated randomly. When you submit your answer, you will either get a feedback confirming a correct guess , or a message that your guess was wrong together with the correct answer. I recommend that you start by running the example a couple of times (use Back button to return to the start and refresh the display). When you feel acquainted with the game, then proceed to the study of the templates below.
All applications must have an Application.cfm template. The purpose of this template is to specify properties, which are valid for all other templates of the application. The application name is a typical example. All Application.cfm must include the CFAPPLICATION tag, but can include also other tags. The Application.cfm of the guessing example is very simple:
1. <!--- Application.cfm --->
2. <CFAPPLICATION NAME="Guess"
SESSIONMANAGEMENT="YES"
SESSIONTIMEOUT=#CreateTimeSpan(0,0,30,0)#>The first statement is giving the template name within a comment tag. Note that the comment is different from the comment you may know from HTML . The second statement is the CFAPPLICATION tag which in our present example has only 3 attributes, the NAME which specifies the name of the application, the SESSIONMANAGEMENT which says that the application must remember session variables, and finally, SESSIONTIMEOUT , which specifies the length of the time in days, hours, minutes and seconds the system must remember these variables if the user is inactive. This template can also include other tags as we shall see in later sessions.
The game problem itself is a very simple dynamic application containing only 2 display templates of which the second depends on the information submitted from the first and makes the application dynamic. The first template is named index.cfm , which eliminates the possibility that uninvited visitors are browsing the content of our folder.
The task to be solved by this template is to present the game for the user and collect his/her name and guess by means of a form. An important parameter is the random upper limit for the integers to be summed. The task for the second template, response.cfm , is to calculate the correct answer to the problem, decide whether the guess submitted is correct or not, and present the conclusion for the user.
Template index.cfm looks like this (the numbers to the left are not part of the script, but placed there to make it easier to refer to the different parts of the template):
1. <!--- index.cfm --->
2. <CFSET temp=Randomize(second(Now()))>
3. <CFSET session.target=#RandRange(50,100)#>
4. <h2><font color="Red">Guess!</font></h2>
5. <form action="response.cfm">
6 . <cfoutput>
7. <p>My name is <input type="text" name="name"></p>
8. <p>I guess the sum of all integers from <b>1</b> to <b>#session.target#</b> is <input type="text" name="guess"></p>
9. </cfoutput>
10. <p><input type="submit" value="Submit"></p>
11. </form>
Figure 1 shows the invitation to submit a guess for evaluation.Lines 2-3 illustrate the CFSET tag. The first command defines a variable called temp and give it a value computed by the CF function Randomize(second(Now())) . The purpose of this is to get a random seed for the next line. This is obtained by using the second at the moment of execution as an argument. If you look carefully at the expression, you will see that there are in fact 3 nested functions . The innermost Now() gets the time (year, data,hour,minute, second) from the internal clock of the computer, the intermediate Second(Now()) extract the seconds from the time object, while the outer function uses the seconds to generate a random seed .
Line 3 defines a variable session.target and assigns to the variable a random integer value in the range from 50-100. This is done by the CF function RandRange(50,100) . Note that the expression is enclosed by # before and after the function. This simply means that the function value is assigned to the variable session.target . By qualifying a variable by session. , the variable is made persistent , i.e. the variable session.target retains its value for use in other templates called by the same user within the same session. The detailed explanation is postponed to the next session.
Following a usual heading in Line 4, a FORM tag block is the remaining of the template. It is as ordinary FORM tag as described in the HTML texts with one exception : The text and input tags in Lines 7-8 are enclosed in CFOUTPUT tags. This is required to get the correct interpretation of the CF variable value #session.target# .
When the form generated by index.cfm is submitted by the user, the 2 variables, name and guess , followed with assigned values are sent with the request to the server. The second template response.cfm , controls the processing of the transferred variables and the returned response to the client.
1. <!--- response.cfm --->
2. <CFSET sum="0">
3. <CFLOOP INDEX="count" FROM="1" TO="#session.target#" >
4. <CFSET sum=#sum#+#count#>
5. </cfloop>
6 . <CFIF #sum# EQ #guess#>
7. <cfoutput>
8. <h3><font color="Blue">#name#,your guess was correct!</font></h3>
9. </cfoutput>
10. <CFELSE>
11. <cfoutput>
12. <h3><font color="Red">Sorry,#name#, the sum is <b>#sum#</b>.</font></h3>
13. </cfoutput>
14. </cfif>
Line 2 assigns value "0" to the variable sum . By means of CFLOOP , Lines 3-5 add the integers from 1 to #session.target# and save the results in the variable sum . In Line 42773 , a CFIF tag instructs the server to test if the guess is correct, and Lines 7 to 9 inform the user about a correct guess.
If the sum is not equal to the guess, the CFELSE is selected and the page sent to the user informing that the guess was not correct as well giving the correct answer.
Figure 2 demonstrates the answer to an incorrect guess.
Exercises
a. Read Chapter 2 in RBB carefully, you will get repaid for the knowledge very soon.
b. The guessing example consists of 3 templates, Application.cfm , index.cfm and response.cfm . Establish a CFMX script folder on your computer with sub folders for each example. The folder must be within the document root defined for your web server. Copy the templates from the browser display to your script folder. Delete the line numbers, save the files with extension .cfm and run the example.
c. Consider how to modify your template index.cfm to generate also a random upper limit between 100 and 200 for the range. Give the new template the name game_modified.cfm . Try it out.
Link to the session example.
Link to the session test.
Steve McKean
UH-Email
CT FORUM CF
user - enter
Steve McKean
UH-Email
CT FORUM CF
user - enter
CFMX HISTORY RESOURCES
OBJECTIVES
Implementation aspects: