Language Basics | Coldfusion primer | Chap-1

34

Transcript of Language Basics | Coldfusion primer | Chap-1

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 .cfm extension

Communication in HTML style

Receive Request+

Retrieve HTML page for directory+

Send back static HTML page

Client Request HTML page

ServerUser browser

Send request

Return HTML

HTML way of client-server interaction

Get / HTTP/1.1Host: www.google.com

User-Agent: Mozilla/5.0 (Windows …Connection: Keep-Alive

request -line

header

HTTP/1.1 200 OKDate: 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

Responseblank line

Receive Request+

Get file from server+

Process ColdFusion page code+

Send back Dynamic HTML page

Receive Request+

Request coldfusionpage

+Generate static HTML

+Send HTML page

Send page request

Send request

ServerColdFusion

Return HTML

Return HTML

Send request

Communication in CFML styleCFML way of client-server

interaction

User browser

Looks similar but WAIT!....

TIME TO LEARN THE BASICS!

Variables & Comments, Arrays, Conditionals, Switch-case statements, Lists & Loops, Structures

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

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

<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#th city 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

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_name is used inside the tag <cfdump> to view server, port, current request and other server-side information

<cfdump var=“#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

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>

Using Structures 2

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

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<cfparam name=“url.name” default=“Who are you DUDE?”><cftry>

<cfoutput>Your are logged in as: #url.name#

</cfoutput><cfcatch>

<cfdump var=“#cfcatch#”></cfcatch>

</cftry>

URL-Page Default with Structure:

Demonstration

Passing A Query String

URL without a query string

Connecting Query String with Static

Links

• This static link points back to the dynamic page

– <cfparam name=‘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>

<cfdump var=‘#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

Connecting Query String with Static

Links: Demonstration

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– <cfparam name="url.windows" default=5>

<cfparam name="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>

<cfdump var="#myHouse#" label="My House">

</cfoutput>

Creating Custom Structures with Query

String : Demonstration

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:– <cfparam name=“url.speed” default=“10”>

<cfparam name=“url.acceleration” default=“0”><cfscript>

questions = “What is the speed limit in your area?,who’s the manufacturer of your car?,What is the price tag?”</cfscript><cfoutput>

The third question is : #listGetAt(questions, 3)#</cfoutput>

Understanding Loops with Lists

• Loops are used to repeat/iterate a 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>

param name = "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><cfloop index="iQuestion" list="#questions#">

<cfoutput><a href="?question=#iQuestion#">

#iQuestion#</a><br>

</cfoutput></cfloop>

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

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>

param name = "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>

<cfloop from="1" to="#ArrayLen(questions)#" index="questionArray">

<cfoutput>

<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>

</cfoutput>

</cfloop>

<cfdump var="#questions#">

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

Playing with if conditioning

• 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: ‘if ice-cream is requested then display ice-cream image, else don’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 the if block inside a <cfscript>. Be professional!

From Symbols to Words:

Comparison Operators

• To compare between to values CFML uses short-hand Uppercase words not symbols

Comparison words (Alien-Form)

Meaning (Human-Form)

Equivalent symbols in other languages

ET/IS Equal to ==

GT Greater >

GTE Greater than equal to

>=

LT Less than <

LTE Less than equal to <=

NOT Negating/makingthe statements

meaning opposite

!

Reinventing the Questionnaire:

Mature Way

<cfscript>param name = "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><cfloop from="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:

Reinventing the Questionnaire:

Amateur Way

• Using the <cfif> <cfelse> </cfif> tags as conditionals

<cfscript>

param name = "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>

<cfif NOT isNumeric(url.questions)>

<cfset url.questions = 1>

<cfelse>

<cfset url.questions = round(url.questions)>

<cfif url.questions LT 1>

<cfset url.questions =1>

<cfelseif url.questions GT 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>

<cfloop from="1" to="#ArrayLen(questions)#" index="questionArray">

<cfoutput>

<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>

</cfoutput>

</cfloop>

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

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 metbreak;

case “condition-2”:

//perform something if this condition is metbreak;default:

//perform something if this condition is met}

• Switch-case statements have their own tags, which are also applicable in CF 9+<cfswitch expression=“any_expression_that_will_be_matched”>

<cfcase value=“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>

Switch-Case in Code:

Mature Way<cfscript>

param name = "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>

<cfloop from="1" to="#ArrayLen(questions)#" index="questionArray">

<cfoutput>

<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>

</cfoutput>

</cfloop>

Switch-Case in Code:

Amateur Way<cfscript>

param name = "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";

</cfscript>

<cfswitch expression="#url.questions#">

<cfcase value="a">

<cfset question = questions[1].question>

<cfset answer = questions[1].answer>

</cfcase>

<cfcase value="b">

<cfset question = questions[2].question>

<cfset answer = questions[2].answer>

</cfcase>

<cfcase value="c">

<cfset question = questions[3].question>

<cfset answer = questions[3].answer>

</cfcase>

<cfdefaultcase>

<cfset question = questions[1].question>

<cfset answer = questions[1].answer>

</cfdefaultcase>

</cfswitch>

<cfoutput>

<strong>Questions</strong>

#questions[url.questions].question#<br>

<strong>Answer</strong>

#questions[url.questions].answer#<br>

</cfoutput>

<cfloop from="1" to="#ArrayLen(questions)#" index="questionArray">

<cfoutput>

<a href=?questions=#questionArray#>#questions[questionArray].question#</a><br>

</cfoutput>

</cfloop>

Uh-Ah, Not Again..!

• Just the same ol’ picture but there is a change inside the code.

• You can use as many case statements for any number of possibilities as you want in a switch-case statement

• In the image below, as there is query string, the default clause has been executed:

Subscribe