Thursday, 9 April 2015

Basic ColdFusion

1. Introduction:
What Is ColdFusion?
ColdFusion is one of the easiest programming environments to use, and enables you to create powerful server-side web applications very quickly, with much less code than other technologies such as ASP, PHP etc.
ColdFusion integrates many Internet technologies such as XML, Java, web services etc, and as such, your applications can be as small or complex as required.
ColdFusion consists of two main elements:
  • A ColdFusion server (which runs on top of your web server),
  • ColdFusion templates (or files), which you write using ColdFusion Markup Language (CFML).
That's probably a very simplistic way of putting it, as there are many elements that make up a ColdFusion environment, but these two are essential if you want to build a ColdFusion application/website.

What Can ColdFusion Do?
ColdFusion enables you to build large, complex, and dynamic websites. ColdFusion can also increase your productivity enormously, both in development time and maintenance time.
With ColdFusion, you can build websites that do things such as:
  • Query a database
  • Allow users to upload files
  • Create/read files on the server (for example, the files that your users upload)
  • Have a "member's area" (i.e. via a login page)
  • Have a shopping cart
  • Present a customized experience (for example, based on users' browsing history)
  • Create a "member's area" (i.e. via a login page)
  • Send emails (for example, newsletters to a mailing list)
  • Schedule tasks to run automatically (for example, your email newsletters)
  • FTP files to/from another server
  • Publish web services
  • Much, much more
OK, I'm Sold. How Do I Get Started?
To build ColdFusion applications, you first need to install the ColdFusion server. Don't worry if that sounds like too much work - it's very straight forward. Installing ColdFusion is just like installing any other piece of software - you simply click your way through the installation wizard, configuring it as you go. This tutorial will point you in the right direction.
Once you've installed ColdFusion server, you can write code using the ColdFusion Markup Language (CFML). CFML uses a syntax that closely resembles HTML and XML. This makes it easy to learn if you're familiar with HTML or XML. CFML however, is more powerful than HTML - it is basically a programming language. You can write conditional statements, loops, query a database, send bulk emails, publish web services and much more.
ColdFusion also provides an administration interface (the ColdFusion Administrator), which enables you to customize your ColdFusion environment.





2. Syntax:
The term ColdFusion Syntax refers to a set of rules that determine how the ColdFusion application will be written by the programmer, and interpreted by the ColdFusion Server.
These rules are referred to as the ColdFusion Markup Language (CFML). CFML is, as the name would suggest, a markup language that programmers need to use when they create a ColdFusion application. It consists of a number of tags. Similar to HTML, these usually consists of an opening tag and a closing tag, and are surrounded by greater than and less than symbols. Closing tags have a forward slash after the less than symbol. ColdFusion tags can also contain one or more attributes.
Tag Syntax
ColdFusion tags use the following format.


<tagname attribute="value">
  Code/text that is affected by the surrounding tags.
</tagname>
Code Example
ColdFusion code:


<cfoutput query="myQuery">
  #firstname#<br />.
</cfoutput>


3. Include tag:
If you've used other scripting environments such as ASP or even .shtml files, you would be familiar with the concept of "includes".
An "include" is a file that is embedded, or "included" within another file. This can be very useful when you want multiple ColdFusion templates to share the same block of code. A typical example might be your website's header and footer. If your website has a consistent header and footer on every page, you could use an include file for each of these.
ColdFusion provides the cfinclude tag for specifying included files.
Tag Syntax
You'll notice that the cfinclude tag doesn't have a closing tag - it just accepts an attribute value (the included filename).

<cfinclude template="included_filename">
Code Example
A common use of ColdFusion includes is to output a consistent header and footer throughout each page of a website. In this example, we're going to create a basic ColdFusion template which uses the cfinclude tag to include two other files.
File 1: index.cfm

<cfinclude template="header.cfm">

<p>Welcome to my website on ColdFusion cfinclude usage!</p>

<cfinclude template="footer.cfm">
File 2: header.cfm

<h1>This is the header</h1>
File 3: footer.cfm

<h1>This is the footer</h1>
Once you've created all of the above files, open index.cfm in your browser. The page should contain the contents of header.cfm at the top, and footer.cfm at the bottom.
Now create a fourth ColdFusion template as follows and open it in your browser.
File 4: about.cfm

<cfinclude template="header.cfm">

<p>Who are we? We are ColdFusion cfinclude enthusiasts of course!</p>

<cfinclude template="footer.cfm">
Because this template includes the same header and footer file, you will see the same header and footer when displayed in a browser.


4. Variable:

Variables are a standard part of any programming language. A variable can be visualised as a container that stores a value.
We can use variables in many circumstances. For example, we could store the user's name inside a variable. We could then present the user's on the web page they're visiting. We could also perform a test against the variable to see what the value is. The application could then perform a different action depending on the value of the variable.
Using cfset
Syntax
To set a ColdFusion variable, use the cfset tag. To output the variable, you need to surround the variable name with hash (#) symbols and enclose it within cfoutput tags.

<cfset variablename="value">
<cfoutput>
#variablename#
</cfoutput>
Example of Usage
This example uses the cfset tag to declare a variable called "firstname" and assign a value of "bono" to it. It then outputs the contents of the variable.
ColdFusion code:

<cfset firstname="Bono">
<cfoutput>
Hello #firstname#.
</cfoutput>
Display in browser:
Hello Bono.
Using cfparam
The cfparam tag creates a variable if it doesn't already exist. You can assign a default value using thedefault attribute. This can be handy if you want to create a variable, but don't want to overwrite it if it has already been created elsewhere.
Example 1
In this example, the variable hasn't been set previously, so it will be assigned with the cfparam tag.

<cfparam name="firstName" default="Ozzy">
<cfoutput>
Hello #firstName#
</cfoutput>
This results in the following:
Hello Ozzy
Example 2
In this example, the variable has already been assigned (using the cfset tag), so this value will override the default value in the cfparam tag.

<cfset firstname="Barney">
<cfparam name="firstName" default="Ozzy">
<cfoutput>
Hello #firstName#
</cfoutput>
This results in the following:
Hello Barney
Checking if a Variable Exists
You can check if a variable has been defined or not by using ColdFusion's built in IsDefined() function. This can be used inside a cfif tag to prevent nasty error messages in the event you attempt to refer to a variable that doesn't exists. You could also use this function to determine whether a user has performed a certain action or not.

<cfif IsDefined("firstName")>
  Hello #firstname#!
<cfelse>
  Hello stranger!
</cfif>








5. Variable Types
e available scopes for ColdFusion variables:
Scope
Description
Variables
This scope refers to local variables that are not specifically reserved for use in custom tags. If you set a variable without specifying a scope (i.e. <cfset variableName = "">, it will automatically belong to the variables scope.
Attributes
This scope is used within a custom tag. When you pass an attribute to a custom tag, it becomes available in the custom tag within the attributes scope.
Caller
Used within a custom tag to set or read variables within the template that called it.
Arguments
Used within a function to refer to arguments that were passed in by the calling template.
This
Used within a component to store its own properties.
Request
The Request scope is used for the current request. These variables are non-persistent global variables.
CGI
CGI variables describe the current requests environment, are created automatically, and are read-only. You can't modify a CGI variable, only read it.
Form
Variables submitted from a form using the "Post" method become part of the Form scope.
URL
Variables passed through the URL are part of the URL scope.
Server
Server scope variables are available to all applications on the current server.
Application
Application scope variables are available to a whole application (as defined in the<cfapplication name=""... tag within the Application.cfm file).
Session
The Session scope is available for the life of a user's session. The length of the lifespan can be determined by a given period of inactivity. This period can be determined in the cfapplication tag. For example, to set a timeout after 20 minutes of inactivity: <cfapplication ... sessiontimeout = "#CreateTimeSpan(0,0,20,0)#"
Client
Client variables are stored on the server, either in the registry or a database (but can also be stored in a cookie on the client machine).
Cookie
Cookie variables are global, and persistent, variables stored on the user's machine.
"Scoping" your Variables
When you set or read a variable, it is good practice to tell ColdFusion which scope it belongs to. Although this is not required, it will avoid any confusion around whether the correct variable is being used or not. You may occasionally encounter two or more variables with the same name, but belonging to a different scope. To avoid the wrong one being used, you should scope your variables.
You scope a variable simply by prefixing the variable name with the name of the scope (and separating them with a dot).
<cfset scope.variablename="value">
<cfoutput>
  #scope.variablename#
</cfoutput>
For example, to scope a session variable, you would do something like this:
<cfset Session.BodyType = "Perfect">
<cfoutput>
  Body Type: #Session.BodyType#
</cfoutput>
Variable Persistence
The following chart outlines the different variable scopes, whether they're local or global, and indicates whether they are persistent variables or non-persistent.

Non-Persistent
Persistent
Local Variables
  • Variables
  • Attributes
  • Caller
  • Arguments
  • This
(none)
Global Variables
  • Request
  • CGI
  • Form
  • URL
  • Server
  • Application
  • Session
  • Client
  • Cookie




6. If statements

As a programmer, you will often need to use conditional statements.
A conditional statement is a piece of code that does one thing based on one condition, and another based on another condition. In fact, you could have as many conditions as you like.
ColdFusion If statements are an example of conditional statements. With If statements, you can tell the ColdFusion server to execute a piece of code only if a given condition is true.
Example If Statement
In this example, the text "Still haven't found what I'm looking for." only gets displayed if the condition is met (that the value of the variable "firstName" equals "Bono".
The letters eq are used with cfif to test that a something is equal to something.
<cfset firstName = "Bono">
<cfif firstName eq "Bono">
  Still haven't found what I'm looking for.
</cfif>
Display in browser:
Still haven't found what I'm looking for.
"If Else" Statement
You can use the cfelse tag to do something if the condition is not met.
<cfset firstName = "Ozzy">
<cfif firstName eq "Bono">
  Still haven't found what I'm looking for.
<cfelse>
  Choose your own song then...
</cfif>
Display in browser:
Choose your own song then...
Example "If Else If" Statement
You can use the cfelseif tag to perform another test (only if the preceeding condition/s is/are not met).
<cfset firstName = "Ozzy">
<cfif firstName eq "Bono">
  Still haven't found what I'm looking for.
<cfelseif firstName eq "Ozzy">
  Crazy Train!
<cfelse>
  Choose your own song then...
</cfif>
Display in browser:
Crazy Train!
NOT Equal To?
Just as eq stands for equal toneq stands for not equal to.
<cfset firstName = "Ozzy">
<cfif firstName neq "Bono">
  Crazy Train!
</cfif>
Display in browser:
Crazy Train!
Less Than?
You can use lt to test that a value is less than another.
<cfset albumSales = 10>
<cfif albumSales lt 100>
  Don't give up your day job!
</cfif>
Display in browser:
Don't give up your day job!
Greater Than?
You can use gt to test that a value is greater than another.
<cfset albumSales = 150000000>
<cfif albumSales gt 1000000>
  Give up your day job!
</cfif>
Display in browser:
Give up your day job!
Greater Than Or Equal To/Less Than Or Equal To?
You can use gte to test that a value is greater than or equal to another.
You can use lte to test that a value is less than or equal to another.
<cfset age = 80>
<cfif age gte 80>
  Give up your day job!
</cfif>
Display in browser:
Give up your day job!











7. Loop

A ColdFusion loop is a block of code that executes continuously either a secified number of times, once for each element in an object, or while a condition is true.
In ColdFusion, you use the cfloop tag to perform a loop. The cfloop tag has a number of different attributes. The attributes used depends on the type of loop you're performing.
Syntax
<cfloop attribute1="" attribute2="">
  Do something for each iteration of the loop.
</cfloop>
The Index Loop
An index loop is a loop that continues for a specified number of times.
You use the from and to attributes to specify how many iterations should occur. The index attribute holds the counter - it starts with the value of the to attribute and is incremented for each iteration of the loop (until it reaches the value of the from attribute).
ColdFusion code:
<cfloop from="1" to="5" index="i">
  <cfoutput>
  #i#<br />
  </cfoutput>
</cfloop>
Display in browser:
1
2
3
4
5
The (optional) step attribute allows you to determine how big the increments will be.
ColdFusion code:
<cfloop from="1" to="10" index="i" step="2">
  <cfoutput>
  #i#<br />
  </cfoutput>
</cfloop>
Display in browser:
1
3
5
7
9
The Conditional Loop
conditional loop is a loop that executes while a condition is true.
You use the condition attribute to specify the condtion to use.
The following example uses a variable to determine whether to reiterate the loop or not. If the value of the variable is equal to false, the loop will continue to iterate. If it is set to true, it will exit the loop and continue the rest of the code.
In this example, we use ColdFusion's RandRange() function to pick a random number between 1 and 10. If the number is 10, the myVar variable is set to true.
ColdFusion code:
<cfset myVar=false>
<cfloop condition="myVar eq false">
  <cfoutput>
  myVar = <b>#myVar#</b>  (still in loop)<br />
 </cfoutput>
  <cfif RandRange(1,10) eq 10>
    <cfset myVar="true">
  </cfif>
</cfloop>
<cfoutput>
myVar = <b>#myVar#</b> (loop has finished)
</cfoutput>
Display in browser:
Tip: Refresh this page a few times and you should see the number of lines change (due to a different random number being generated within the loop).
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = false (still in loop)
myVar = true (loop has finished)
The Query Loop
You can loop over the results of a ColdFusion query (i.e. using the cfquery tag). Don't worry - if you don't know what I mean by that, we will be learning about ColdFusion queries soon.
ColdFusion code:
<cfquery name="getMovies" datasource="Entertainment">
  select top 4 movieName
  from Movies
</cfquery>
<cfloop query="getMovies">
   #movieName#
</cfloop>
Display in browser:
Borat
Crocodile Dundee
Lord of the Rings
Last Samurai
The List Loop
You can loop over a list.
You can use the (optional) "delimter" attribute to specify which characters are used as separators in the list.
<cfloop list="ColdFusion,HTML;XML" index="ListItem" delimiters=",;">
  <cfoutput>
   #ListItem#<br />
 </cfoutput>
</cfloop>
Display in browser:
ColdFusion
HTML
XML
The File Loop
You can loop over a file. To do this, you use the same attributes as you would for a list.
<cfloop list="#myFile#" index="FileItem" delimiters="#chr(10)##chr(13)#">
  <cfoutput>
   #FileItem#<br />
 </cfoutput>
</cfloop>
COM Collection/Structure Loops
You can loop over a Structure or COM collection.
<cfset myBooks = StructNew()>
<cfset myVariable = StructInsert(myBooks,"ColdFusion","ColdFusion MX Bible")>
<cfset myVariable = StructInsert(myBooks,"HTML","HTML Visual QuickStart")>
<cfset myVariable = StructInsert(myBooks,"XML","Inside XML")>
<cfloop collection="#myBooks#" item="subject">
  <cfoutput>
 <b>#subject#:</b> #StructFind(myBooks,subject)#<br />
 </cfoutput>
</cfloop>
Display in browser:
HTML: HTML Visual QuickStart
ColdFusion: ColdFusion MX Bible
XML: Inside XML

 

 

 

 

8. Datasource

oldFusion is a great environment for connecting to, and performing queries against a database. Reasons for using a database could include authentication to a members' area, serving up content from a content management system, logging user feedback, and more.
Any website that uses a database, needs a way to connect to the database and a way to query the database (i.e. using SQL Statements).
Create a ColdFusion Datasource
To allow ColdFusion to connect to a database, you first need to create a datasource. A datasource provides the connection between Coldfusion and the database. Another way of looking at it is that the datasource provides the link between your CFML code and the actual database.
You create datasources via the ColdFusion Administrator.
Follow the steps below to create a ColdFusion data source.
  1. Log in to the ColdFusion Administrator (usually at http://{ website_url }/cfide/administrator)
  2. Click on "Data Sources". You should see something like this:

  1. Under "Add New Data Source", enter a data source name and driver type (i.e. Microsoft Access, or Microsoft SQL Server). The driver type will depend on your database type.
  2. Click "Add"
  3. Click "Show Advanced Settings" (optional)
  4. Enter the details of your database. This screen should look something like this (although will differ depending on the driver you user):

  1. Click "Submit"
Once you click submit, ColdFusion will verify the connection to the database. If there are any problems, you should check that the details you entered here match the details of the database (for example, usernames/passwords, server name etc).


9. Database Queries - CFQUERY 

In the previous lesson we have created data source,  so that it could be used by ColdFusion to connect to a database.
Now that we have the datasource, we can perform a query against the database that the datasource is linking to.
To perform a database query in ColdFusion, you use the cfquery tag.
Basic CFQUERY Example
This code is all you need to do in order to query a database in ColdFusion. The cfquery tag connects to and opens the database for you, all you need to do is supply it with the name of the datasource.
<cfquery datasource="Entertainment">
  select *
  from Movies
</cfquery>
Authentication
Many database configurations require authentication (in the form of a username and password) before you can query the database. You can supply these using the username and passwordattributes.
Note that the username and password can also be configured against the datasource in the ColdFusion Administrator. Supplying these details in your query overrides the username and password in the ColdFusion Administrator.
<cfquery datasource="Entertainment" username="webuser" password="letmein">
  select *
  from Movies
</cfquery>
Cached Queries
If you have a lot of traffic, you may find that performance of your website/application is affected. If so, you will need to look at ways of improving performance. One effective technique you can use is to cache some of your database queries.
cached query is a query that has its results stored in the server's memory. The results are stored when the query is first run. From then on, whenever that query is requested again, ColdFusion will retrieve the results from memory.
For ColdFusion, it's much faster retrieving the results from memory than to perform another query from the database. When you query a database, ColdFusion has to wait whilst the database connection (often on another server) is established, the database is opened, the query is run, and the results are returned to ColdFusion. All this takes time, and it can impact on other ColdFusion requests occurring at the same time.
You can cache a query using the cachedAfter attribute. If the query was last run after the supplied date, cached data is used. Otherwise the query is re-run.
<cfquery datasource="Entertainment" cachedAfter="November 20, 2006">
  select *
  from Movies
</cfquery>
You can also cache a query using the cachedWithin attribute in conjunction with the CreateTimeSpanfunction.
In the following example, if the query's cached data is older than 1 hour, the query is re-run. Otherwise, cached data is used.
<cfquery datasource="Entertainment" cachedwithin="#CreateTimeSpan(0,1,0,0)#">
  select *
  from Movies
</cfquery>
Limiting the Number of Records Returned
You can limit the number of rows to be returned by using the maxrows attribute.
<cfquery datasource="Entertainment" maxrows="50">
  select *
  from Movies
</cfquery>
Timeouts
You can set a timeout limit using the timeout attribute. This can be useful in preventing requests running far longer than they should and impacting on the whole application as a result.
The timeout attribute sets the maximum number of seconds that each action of a query is allowed to execute before returning an error.
<cfquery datasource="Entertainment" timeout="30">
  select *
  from Movies
</cfquery>





















10. Lists in ColdFusion

A Coldfusion list (or any list for that matter) is simply a string. The thing that makes this string different (to any other string) is that it contains "delimiters'. Delimiters (sometimes referred to as "separators") are used to separate each item in the list.
For example: ColdFusion Lists,ColdFusion Arrays,ColdFusion Structures could be a "comma delimited", or "comma separated" list.
Although commas are the most common delimiter for lists, any character (or set of characters) can be used. For example, ColdFusion Lists:ColdFusion Arrays:ColdFusion Structures is no less a list than the comma delimited list.
Creating Lists in ColdFusion
This is easy. You can create a list in ColdFusion just the same you would create any other variable. Just remember to throw in a delimiter:
<cfset coldfusion_list = "ColdFusion Lists,ColdFusion Arrays,ColdFusion Structures">
In reality, you would probably create the list dynamically by looping through a set of items. You will often need to convert an array into a list or a list to an array (see below).
ColdFusion List Functions
Once you have your list, you can use ColdFusion to work with it. ColdFusion provides many functions for working with lists. Some of the common things you might need to do are listed below.
Find out the list length:
listLen(coldfusion_list)
Loop through the list:
<cfloop list="#coldfusion_list#" index="i">
   <cfoutput> #i# <br /></cfoutput>
  </cfloop>
Add items to the list:
·                     Add an item to the end of the list. The following adds "ColdFusion Functions" to the end of the list:
listAppend(coldfusion_list, "ColdFusion Functions")
·                     Add an item to the beginning of the list. The following adds "ColdFusion Functions" to the beginning of the list:
listPrepend(coldfusion_list, "ColdFusion Functions")
·                     Add an item somewhere in the middle of the list. The following adds "ColdFusion Functions" to position 2 of the list:
listInsertAt(coldfusion_list, "2", "ColdFusion Functions")
The above functions also accept an optional "delimiter" field, which, if needed, you place at the end. For example: listAppend(coldfusion_list, "ColdFusion Functions", ":")
Find out if the list contains a given string:
listContains(coldfusion_list, "ColdFusion")
...or if you don't want it to be case sensitive:
listContainsNoCase(coldfusion_list, "ColdFusion")
Convert a list into an array:
ListToArray(coldfusion_list)
Convert an array into a list:
ArrayToList(array_name)
















11. Arrays in ColdFusion

ColdFusion arrays (or any array) are a fundamental part of most programming languages and scripts.
An array is simply an ordered stack of data items with the same data type. Using an array, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.
For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:
<cfset faqQuestion1 = "What is an array?">
<cfset faqQuestion2 = "How to create a ColdFusion array?">
<cfset faqQuestion3 = "What are two dimensional arrays?">
This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do stuff like loop through all your variables. That's where arrays come into play. You could put all your questions into one array.
Visualizing Arrays
Arrays can be visualized as a stack of elements.
Array
0
What are ColdFusion arrays?
1
How to create a ColdFusion array?
2
What are two dimensional arrays?
Note: Some languages start arrays at zero, others start at 1. ColdFusion arrays start at 1.
Creating Arrays in ColdFusion
Most languages use similar syntax to create arrays. A ColdFusion array is created by first assigning an array object to a variable name...
<cfset array_name = ArrayNew(1)>
then by assigning values to the array...
<cfset ArrayAppend(array_name, {value})>
So, using our prior example, we could write:
<cfset faq = ArrayNew(1)>
<cfset ArrayAppend(faq, "What are ColdFusion arrays")>
<cfset ArrayAppend(faq, "How to create a ColdFusion array?")>
<cfset ArrayAppend(faq, "What are two dimensional arrays?")>
Accessing Arrays in ColdFusion
You can access an array element by referring to the name of the array and the element's index number.
Displaying Array Elements
The following code displays the second element of the array named faq. In this case, the value would be How to create a ColdFusion array?
<cfoutput>#faq[2]#</cfoutput>
Modifying the Contents of an Array
To add an item to the end of an array, use the ArrayAppend() function:
<cfset ArrayAppend(faq, "How to modify an array?")>
To add an item to the beginning of the array, use the ArrayPrepend() function:
<cfset ArrayPrepend(faq, "How to modify an array?")>
To insert an item in a specific position in the array, use the ArrayInsertAt() function (in this case, the new value is added before position 3):
<cfset ArrayInsertAt(faq, ,3, "How to modify an array?")>












13. Temporary Redirects

If you're familiar with HTML, you may have learned how to perform a URL redirection using the meta tag. If not, you can learn how to do that in 30 seconds on this HTML redirect page.
In ColdFusion, redirects can be done via one of two methods. The method you use will depend on the reason for the redirect.
Temporary Redirects (cflocation)
This is the most commonly used of the two - you will probably find yourself using the cflocation tag often.
A temporary redirect is typically used when you need to redirect the user to another page based on some logical rule in your program. For example, straight after they submit a form, the browser might redirect to another page.
ColdFusion includes the cflocation tag for performing temporary redirects. This actually sends HTTP headers to the user's browser indicating a 302 status code, which means "Moved Temporarily".
<cflocation url="/new_location.cfm">
Permanent Redirects
A permanent redirect should be used when a page no longer exists.
Permanent redirects use the 301 HTTP status code, which means, "Moved Permanently". In ColdFusion, a permanent redirect can be achieved using the cfheader tag.
<cfheader statuscode="301" statustext="Moved Permanently">
<cfheader name="Location" value="http://www.quackit.com/coldfusion/tutorial">
<cfabort>
In case you're thinking, "but users can't see the status code anyway", that's only partially true. The 301 status code can be very useful for search engines. They will actually take notice of your 301 status code and index the correct file.

















14. Debugging Settings (via ColdFusion Administrator)

ColdFusion provides a number of debugging tools to assist us in troubleshooting problem areas. Problem areas could be anything from strange results being output from a query, to a slow running template.
ColdFusion's debugging tools, provides us with extra information that we (and our users) don't normally see when visiting the website.
When running a debugger, you should attempt to do so in a development environment. Obviously, this makes sense if you're only in development mode anyway, but, if you're debugging an issue that's occuring in a production environment (where real users are impacted), you should really try recreating the issue on your development environment. Having said that, there are ways of restricting debug output so that your users aren't affected.
The following ColdFusion tools/tags can be useful for debugging your applications:
  • The cfdump tag
  • The cfabort tag
  • Debugging Settings (via ColdFusion Administrator)
Below is an overview of each.
The cfdump Tag
The cfdump tag is a very handy debugging tool for ColdFusion developers. It allows you to output (or "dump") the contents of your variables on the screen. You can use this on any variable, regardless of it's type - arrays, structures, query objects etc
The great thing about cfdump is it's ease of use. The syntax is as follows:
<cfdump var="variable_name">
Example of Usage
It's just as easy to use cfdump on a complex object as it is on a simple variable. Therefore, to give you a better idea of how cfdump can help you visualize your objects, I will use a query object for this example.
First, lets create a query object. We do this with the cfquery tag:
<cfquery datasource="quackit" name="GetUsers">
select FirstName, IndividualId, LastName, UserName from individual
</cfquery>

<cfdump var="#GetUsers#">
A cfdump of the above query would like something like this:
query

FIRSTNAME
INDIVIDUALID
LASTNAME
USERNAME
1
Fred
1
Flinstone
freddo
2
Homer
2
Simpson
homey
3
Homer
3
Brown
notsofamous
4
Ozzy
4
Ozzbourne
Sabbath
5
Homer
5
Gain
noplacelike
The cfabort Tag
It can sometimes be handy placing a cfabort tag immediately after your cfdump. This way, you prevent the application from doing any further processing until you've decided whether the results of the cfdump are correct or not. If you decide the results of the cfdump are correct, you can continue to step through the page, placing cfabort (and/or cfdump) at logical points so that you can get a "snapshot" of the state that the application is in at a particular point.
Debugging Settings (via ColdFusion Administrator)
The ColdFusion Administrator provides a number of debugging options for developers. You can find these options under the DEBUGGING & LOGGING heading on the left menu. The first option isDebugging Settings. This allows you to specify what debug info should be displayed and how.
The next option on the left menu lets you restrict the debug output to specific IP addresses if required. This is useful if you are debugging in a production environment and don't want your users to see the debugging output.
Below are the options available in the Debugging Settings option:
Enable Debugging
This turns debugging on. Debug info is now displayed when you view the site in a browser. When this option is checked, the actual debug output is determined by the following options.
Select Debugging Output Format
You can choose whether the debug info is displayed at the bottom of the page (classic.cfm) or in a popup window (dockable.cfm).
Report Execution Times
This option allows you to see how long each ColdFusion file takes to execute. This includes templates, includes, modules, custom tags, and compoment method calls. A useful tool that allows you to isolate slow running blocks of code very quickly.
Database Activity
When this is enabled, you will be able to see each query as it is being run against the database. Useful if you have dynamic queries.
Exception Information
Provides information about any ColdFusion exceptions that are raised during processing.
Tracing Information
Allows you to track program flow and efficiency with the cftrace tag.
Variables
When this is enabled, the debug output will display each variable and its value. You can select which variable scope to report on, or you can choose all scopes if you like.
The following options can be enabled/disabled independently of the above debugging settings:
Enable Robust Exception Information
Allows visitors to see the following information in the exceptions page:
·         physical path of template
·         URI of template
·         line number and line snippet
·         SQL statement used (if any)
·         Data source name (if any)
·         Java stack trace
Enable Performance Monitoring
Allows you to monitor ColdFusion performance via the Windows Performance Monitor. If the website isn't on a Windows based machine, CFSTAT will provide the same info.
Enable CFSTAT
Allows you to monitor ColdFusion performance in real-time via CFSTAT - a command line interface.



15. Error Handling With cftry and cfcatch

Regardless of how well you test your ColdFusion applications, there will undoubtedly be times where an exception occurs in your application.
An exception is when something occurs out of the ordinary. Often, this will result in a nasty looking error message being presented to the user. You have probably seen the types of error messages that ColdFusion presents when something goes wrong - although these can be very useful to us as developers, it's probably enough to scare most users away from your website!
You can use error handling techniques to display a more user friendly error message to the user. You can still present your header and footer as you normally would, as well as any other content that was on the page, right up until the error occurred as well as after the error.
ColdFusion provides a number of error handling tools to assist developers in catching errors and performing another action accordingly.
Error Handling With cftry and cfcatch
You can use ColdFusion's cftry tag in conjunction with the cfcatch tag to "catch" the error before the user sees it, and display a more user friendly message to the user.
How this works is, once you identify high risk code, you nest that code inside the <cftry></cftry> tags. Then, just below the high risk code (but before the closing cftry tag, you insert <cfcatch></cfcatch> tags. In between these cfcatch tags, you specify what needs to take place if there's an error.
Example
In this example, we are attempting to perform a query against a database, then present the results. For the sake of this example, the database happens to reside on another server, but there's a problem with the network and therefore the database server is temporarily unavailable.
In this case, we have caught the error and presented a message to the user. If we hadn't done this, we would have seen the standard ColdFusion error message.
<p><b>Header, other content etc goes here</b></p>

<cftry>
<cfquery datasource="SomeUnavailableDsn" name="getUsers">
   select FirstName from individual
</cfquery>
<cfoutput query="getUsers">#FirstName#<br /></cfoutput>
<cfcatch type="any">
  Apologies, an error has occurred. Please try again later.
</cfcatch>
</cftry>

<p><b>Footer, other content etc goes here</b></p>
The above code results in the following error message.
Header, other content etc goes here
Apologies, an error has occurred. Please try again later.
Footer, other content etc goes here
Exception Types
You may have noticed that in the above example, the cfcatch tag contains a type attribute. This attribute allows you to specify which exception types should be caught by this cfcatch tag. This can be useful because, you may want to display a different error message depending on the type of error that occurred. The following table outlines the different exception types:
Exception Name
Description
Application
These errors can occur if you call a component that doesn't exist or if there's a problem with accessing it.
Database
These are errors that occur from a database call.
Security
Errors related to Sandbox Security.
Object
Errors resulting from a call to an object such as COM, CORBA, or Java objects.
MissingInclude
Errors resulting from a call to a missing include file or custom tag (i.e. called from a cfincludeor cfmodule tag.
Template
Errors resulting from a call to a missing template. Similar to the MissingInclude error.
Expression
Errors resulting from an invalid expression. This includes errors resulting from attempting to use a variable that doesn't exist.
Lock
Errors resulting from the cflock tag. Either the lock timed out, or it couldn't be created. Note: To receive this error, the cflock tag needs to have ThrowOnTimeout="yes".
SearchEngine
Errors resulting from the cfsearchcfindex, or cfcollection tags.
Any
Using this value catches all of the above errors.
Handling Multiple Error Types
To handle more than one error type, you simply use a different cfcatch for each type you want to handle.
<cftry>
... High risk code goes here...

<cfcatch type="Database">
  A database error has occurred. Please try again later.
</cfcatch>
<cfcatch type="Expression">
  An expression error has occurred. Please try again later.
</cfcatch>
<cfcatch type="MissingInclude">
  An include file has gone missing. Please try again later.
</cfcatch>
</cftry>
The cferror Tag
As well as using cfcatch and cftry, you can use the cferror tag for catching errors.
The cferror tag allows you to specify a generic template file that will handle any errors that occur. Usually, you would place this tag into your Application.cfm file. That way, it will automatically handle any error that occurs throughout your application.
The following example assumes a template called errors.cfm has already been created.
<cferror type="exception" template="errors.cfm" exception="any">
The good thing about this is that, you are able to display a customized error page for errors that aren't handled by a cftry/cfcatch (it's unrealistic to wrap your whole application within a cftry). The disadvantage is that it might be a bit harder to diagnose any problems. That's why you should still use cftry/cfcatch for blocks of code you think are vulnerable to an error occurring, but also have the cferror as a backup for other errors.
The Site-wide Error Handler
You can specify a site-wide error handler in case the previous methods didn't catch the error. The site-wide error handler is specified via the ColdFusion Administrator (under Server Settings > Settings).
The Missing Template Handler
The ColdFusion Administrator enables you to specify a missing template handler. This option is located on the same screen as the site-wide error handler (above). The missing template handler is a generic template you can use in case the application can't find a template.
Log Files
If you become aware that an error occured on your application, you can check the ColdFusion log files to find out details of the error. You can view ColdFusion's log files via the ColdFusion Administrator (under "Debugging & Logging > Log Files"), or by navigating to the log file folder. This is usually under cf_root\logs (for example C:\CFusionMX\logs).
It's a good idea to review the ColdFusion log files occasionally in case there are any errors that are going unnoticed (or at least, unreported!).
Email Alerts
It's a good idea to set up email alerts that notify the technical support team whenever an error occurs with your application. Otherwise, you might never know there's a problem until eventually one of your users decides to complain!

No comments:

Post a Comment