Transcription

Week 1www.learncfinaweek.com

AcknowledgementsThis course would not have been possible without the following people:Authors Emily Christiansen Tim Cunningham David Epler Sam Farmer Dave Ferguson Simon Free Paul Hastings Guust Nieuwenhuis Dan Skaggs Nic Tunney Adam Tuttle Dan WilsonEditors Mark Esher Kristin Ferguson Tiffany GoebelDesigners Nick Borden Jim PriestCopyrightCode licensed under the Apache License v2.0. Documentation licensed under CC BY 3.0.

ContentsInstallation.1The Basics.8What is ColdFusion?.9Setting Variables.10Data Types.15Commenting.21ColdFusion Tags vs. ColdFusion Script.23Hands On 1.25Hands On 2.27Decision Making and Scopes.29Decision Making.30Scopes.35Hands On 3.38Hands On 4.40Hands On 5.42Hands On 6.44Looping.46Hands On 7.54Hands On 8.56Data Handling.59Databases.60XML.70JSON.77Hands On 9.79Hands On 10.81Hands On 11.86Code Reuse.89Functions.90Including.96Custom Tags.98Components.100Hands On 12.105Hands On 13.108Hands On 14.111Hands On 15.114Application.cfc.116Request Lifecycle Events.117Time for the Code!.119More than Just Events.122What is an Application?.124Where does Application.cfc go?.125What’s Application.cfm?.126Appendix: Application.cfc Template.127

Hands On 16.129OOP.133Hands On 17.140Intro to ORM.143Introduction.144Configuration.144Working with Data.148Hands On 18.151Hands On 19.154Hands On 20.157Hands On 21.163Mail.168Configure Mail Settings.169Send Email.169Using CFScript.179View Undelivered Mail.181Overwrite Default Mail ServerSettings.182Hands On 22.183Document form.197File Manipulation.200Image Manipulation.205Spreadsheets.210Hands On 23.214Hands On 24.216Hands On 25.219Hands On 26.222Caching.228Hands On ss-site Scripting (XSS).246Cross-Site Request Forgery (CSRF).252Session Identifier Protection.254File Uploads.256Secure Password Storage.259ColdFusion Configuration.262Hands On 28.264Hands On 29.267Error Handling and Debugging.271Error Handling.272

Debugging.281Hands On 30.284Hands On 31.286i18n.289Hands On 32.295What to do Next.297

InstallationTo be able to follow along with the Hands On portion of the course you will need to installColdFusion, MySQL and the sample files. The following instructions show you how to install thesoftware as well as the sample files.Installing ColdFusionTo be able to program in ColdFusion, a ColdFusion server needs to be installed. There are a coupleof options available, but the one that we are going to focus on is a local development server.A local development server is free and allows you to develop ColdFusion applications that use allof ColdFusion’s available features. There are, however, a few limitations, such as not being ableto use the server as an external web server. That being said, there are additional benefits to usinga local ColdFusion development server, such as not needing to have IIS or Apache installed, butinstead using the packaged web server.To install ColdFusion, follow the steps below:Windows1. Open up a web browser and go to: http://www.adobe.com/go/trycoldfusion/2. Sign in with your Adobe ID. If you do not have an Adobe account, click on the "Create an Adobeaccount" button on the left.3. Select the appropriate version of ColdFusion you wish to download. If you have a 64 bit systemselect 'English Windows 64 bit', else select 'English Windows'.4. Click "Download".5. Save the file to your desktop.6. Once downloaded, double click the file.7. Click "Next".8. Accept the terms and click "Next".9. When you see the screen below, select "Developer Edition" and click "Next".Learn CF in a Week - Week 1 - InstallationPage 1

10. Select Server configuration and click "Next".11. Leave all checkboxes selected and click "Next".12. Leave the "Enable Secure Profile" checkbox unchecked and click "Next".13. Provide a password and click "Next". Make sure you remember the password!14. Leave the location at C:\ColdFusion10\ and click "Next". If you want to install in a differentlocation you can, but it is important to note that the install instructions will always referenceC:\ColdFusion10\.15. Select 'Built-in web server (Development use only)' and click "Next".16. Provide a password and click "Next". Make sure you remember the password; you will need thislater on in the install process.17. Select 'Enable RDS', provide a password and click "Next". Make sure you remember thepassword!18. Leave the 'Automatically check for server updates' selected and click "Next".19. Click "Install".20. If you receive any Windows firewall messages, click 'Allow'.21. When the installation wizard is done, keep the 'Launch the Configuration Wizard in the defaultbrowser' selected and click "Done".22. A browser window will open. Enter your ColdFusion Administrator Password and click "Login".(This is the password from step 16)23. Once you receive the 'Setup Complete' screen, click the "OK" button.24. You will now see the ColdFusion Administrator screen. To access this screen at a later date, youLearn CF in a Week - Week 1 - InstallationPage 2

can go to: m25. You have now successfully installed ColdFusion 10. To access the web root, you can go to:http://localhost:8500/. he web root on the file system isC:\ColdFusion10\cfusion\wwwroot\.Mac1. Open up a web browser and go to: http://www.adobe.com/go/trycoldfusion/2. Sign in with your Adobe ID. If you do not have an Adobe account, click on the "Create an Adobeaccount" button on the left.3. Select the English MAC OS X version of ColdFusion.4. Click "Download".5. Save the file to your desktop.6. Once downloaded, double click the file.7. Click "Next".8. Accept the terms and click "Next".9. When you see the screen below, select "Developer Edition" and click "Next".10. Select Server configuration and click "Next".11. Leave all checkboxes selected and click "Next".12. Leave the "Enable Secure Profile" checkbox unchecked and click "Next".Learn CF in a Week - Week 1 - InstallationPage 3

13. Provide a password and click "Next". Make sure you remember the password!14. Leave the location at /Applications/ColdFusion10/ and click "Next". If you want to installin a different location you can, but it is important to note that the install instructions will alwaysreference /Applications/ColdFusion10/.15. Select 'Built-in web server (Development use only)' and click "Next".16. Provide a password and click "Next". Make sure you remember the password; you will need thislater on in the install process.17. Select 'Enable RDS', provide a password and click "Next". Make sure you remember thepassword!18. Leave the 'Automatically check for server updates' selected and click "Next".19. Click "Install".20. When the installation wizard is done, keep the 'Launch the Configuration Wizard in the defaultbrowser' selected and click "Done".21. A browser window will open. Enter your ColdFusion Administrator Password and click "Login".(This is the password from step 16)22. Once you receive the 'Setup Complete' screen, click the "OK" button.23. You will now see the ColdFusion Administrator screen. To access this screen at a later date, youcan go to: http://localhost/CFIDE/administrator/index.cfm24. You have now successfully installed ColdFusion 10. To access the web root, you can go to:http://localhost:8500/. The web root on the file system is/Applications/ColdFusion10/cfusion/wwwroot/Learn CF in a Week - Week 1 - InstallationPage 4

Installing MySQLColdFusion has the ability to communicate with a number of different databases, which will becovered later on in this course; for the sample application we will be working on throughout thecourse, we will be using MySQL. If you already have MySQL 4 or 5 already installed, you canproceed to the 'Install Sample Files' section. If not, follow the steps below:Windows1. Open up a browser and go to: http://dev.mysql.com/downloads/mysql/2. Scroll to the list of available downloads. Click the 'Download' button next to the applicabledownload. Windows 64 bit - Windows (x86, 64-bit), MSI Windows 32 bit - Windows (x86, 32-bit), MSIIf you are unsure, assume you are on a 32 bit machine.3. To begin the download, you must either login using pre-existing credentials by clicking the'Proceed' button under the New Users section or click the 'No thanks, just start my download'link at the bottom of the screen.4. Save the file to your desktop.5. Double click the file.6. On the Welcome screen click 'Next'.7. Accept the terms in the license agreement and click 'Next'.8. When presented with a list of available Setup Types, Select 'Typical'.9. When ready to install, click 'Install'.10. If a system message pops up asking if you want the software to be installed on your machine,click 'Yes'.11. If a MySQL enterprise pop up window appears, click 'Next' until it disappears.12. When the Setup Wizard has completed, Click 'Finish'.13. If you receive another pop up message asking if you want the software to be installed on yourmachine, click 'Yes'.14. When the Server Instance Configuration Wizard displays, Click 'Next'.15. When displayed the available Server Instance Configuration types select 'StandardConfiguration' and click 'Next'.16. When on the Windows Options scree, keep 'Install as a Service' selected as well as 'Launch theMySQL Server automatically'. Select the 'Include Bin Directory in Windows PATH' option andselect 'Next'.Learn CF in a Week - Week 1 - InstallationPage 5

17. On the Security Options scree, specify a new root password and select 'Next'. Remember thispassword as it will be needed later!18. When the Ready to Execute screen displays, click 'Execute'.19. After all the Configuration steps have successfully run, Click 'Finish'.20. You have successfully installed MySQL.Mac1. Open up a browser and go to: http://dev.mysql.com/downloads/mysql/2. Scroll to the list of available downloads. Click the 'Download' button next to the applicabledownload. Mac 64 bit - Mac OS X ver. 10.6 (x86, 64-bit), DMG Archive Mac 32 bit - Mac OS X ver. 10.6 (x86, 32-bit), DMG ArchiveIf you are unsure, assume you are on a 32 bit machine3. To begin the download, you must either login using pre-existing credentials by clicking the'Proceed' button under the New Users section or click the 'No thanks, just start my download'link at the bottom of the screen.4. Save the file to your desktop.5. Double click the file.6. Once the DMG has mounted, double click the mysql-5.5.28-osx10.6-x86 64.pkg (or similar) file.It should be the first file in the list.7. On the welcome screen, click 'Continue'.8. Review the Important Information screen and click 'Continue'.9. Review the Software License Agreement and click 'Continue'.10. Agree to the terms.11. Select the drive you wish to install the software to and click 'Continue'.12. Click 'Install'.13. Provide your system password and click 'OK'.14. Once you receive the screen stating the Installation was Successful, click 'Close'.15. Double click the MySQL.prefPane icon.16. Click 'Install'.17. If the MySQL server is not running, click the 'Start MySQL' Server button.Learn CF in a Week - Week 1 - InstallationPage 6

18. If prompted, provide your system password and click 'OK'.19. Click the 'Automatically Start MySQL Server' on Startup check box.20. Close the window.21. Open up a terminal window and enter the following:/usr/local/mysql/bin/mysqladmin -u root password [NewPassword]22. Make sure to replace [NewPassword] with the password you wish to use for the root user.Remember this password, it will be needed later.23. Close the Terminal window.24. You have successfully installed MySQL and set the root user password. Learn CF in a Week - Week 1 - InstallationPage 7

Installing Sample FilesAs well as having the ability to read about ColdFusion, 'Learn CF in a Week' has a Hands Onsection of the course, giving you the opportunity to create your own ColdFusion web site. Duringthe course, you will take a basic HTML website and add ColdFusion to it, creating a fully functionalColdFusion application.To be able to take part in the Hands On, you must first install the necessary Application files. To dothis, follow the steps below:Windows1. Download the sample application files from the download link in the header ofhttp://www.learncfinaweek.com/.2. Create a folder in your web root called 'learncfinaweek'. Your webroot is located at:C:\ColdFusion10\cfusion\wwwroot\3. Unzip the sample application files into the learncfinaweek folder. The contents of the foldershould look like this:Learn CF in a Week - Week 1 - InstallationPage 8

4. To confirm you have the files in the correct place, go to: http://localhost:8500/learncfinaweek/.5. Now that you have the files in the correct place, you now need to run an install script that willpopulate your database and set up ColdFusion with the necessary information.Go to: http://localhost:8500/learncfinaweek/install/.6. Fill out the form using the passwords from the previous installation processes and click on"Install".7. If any problems occur, follow the onscreen instructions on how to correct them. If no problemsexist, you are good to start the course.Mac1. Download the sample application files from the download link in the header ofhttp://www.learncfinaweek.com/.2. Create a folder in your web root called learncfinaweek. Your webroot is located at/Applications/ColdFusion10/cfusion/wwwroot/3. Unzip the sample application files into the learncfinaweek folder. The contents of the foldershould look like this:4. To confirm you have the files in the correct place go to: http://localhost:8500/learncfinaweek/.5. Now that you have the files in the correct place you now need to run an install script that willpopulate your database and set up ColdFusion with the necessary information.Go to: http://localhost:8500/learncfinaweek/install/.6. Fill out the form using the passwords from the previous installation processes and click oninstall.Learn CF in a Week - Week 1 - InstallationPage 9

7. If any problems occur follow the onscreen instructions on how to correct them. If no problemsexist then you are good to start the course.How the Hands On WorksThroughout this course you will see a number of hands on pages. These pages give you stepby step instructions on what to do to your ColdFusion code. The root of the project is locatedat: \ for Windows and inaweek/www/ for Macs.Inside the 'learncfinaweek' folder, you will see a number of folders that relate to the chapters, suchas chapter1Solution, chapter2Solution, and so on. Inside these folders, you will find copies of thecode which have all the hands ons completed up until and including that chapter. If at any point youget stuck with a code problem, you can look at these files to see what the solution is. If you are stillunable to find what is causing the problem in your code, you can copy the files and folders fromthe chapter folder and place them in your 'www' folder. Once you have copied them in, you cancontinue with the next chapter.Once you have completed the hands on problems, you will have a fully functioning ColdFusionweb site that is ready to be launched right away. Included in this application is file manipulation,database calls, remote calls, sending emails, ORM, and a fully secured Admin area.Learn CF in a Week - Week 1 - InstallationPage 10

1The BasicsBy Dan WilsonAbout Dan WilsonAs principal partner of DataCurl LLC, Dan Wilson runs boththe consulting practice and ChallengeWave.com, a way to helpemployees start and stick with healthier lifestyles.Before launching DataCurl, Dan held numerous seniorprogram and development positions in such industries asTechnical Consulting, Health Care, Online Publishing andGovernment Contracting.Dan is an avid participant in technology communities; anAdobe Community Professional, manager of the TriangleColdFusion User Group in Research Triangle Park, NorthCarolina, Managing Director of the popular Model-Glueframework and contributor to numerous open source projectsbased on ColdFusion, Flex and AIR platforms.Dan presents on ColdFusion, Flex and Rapid Development Techniques at popularconferences around the world. You can find his thoughts on ColdFusion, Flex, AIR and othertechnology matters at http://www.nodans.com and some occasional ramblings on food athttp://blog.chefdanwilson.com.When not in front of a computer, you can find him biking, hiking, surfing, playing volleyball andhelping small businesses improve their sales and marketing.Learn CF in a Week - Week 1Page 8

What is ColdFusion?ColdFusion is a rapid development platform for building modern web applications. ColdFusionis designed to be expressive and powerful. The expressive characteristic allows you to performprogramming tasks at a higher level than most other languages. The powerful characteristic givesyou integrations with functionality important to web applications like database access, MS Exchangeaccess, PDF form creation and more.The ColdFusion platform is built on Java and uses the Apache Tomcat J2EE container. While youhave full access to Java and Tomcat, you need not worry about these details. You'll interact withColdFusion and the user friendly ColdFusion Mark-up Language (CFML) to write your programs. YourColdFusion files will use the file extension '.cfc' for objects and '.cfm' for pages. CFML requires muchless ceremony and infrastructure than typical java while offering a significantly faster developmentexperience than Java.After taking this CF in a Week series, you'll have the basics necessary to begin making dynamic websites, building intranet applications, or even working on the next Facebook competitor!Learn CF in a Week - Week 1Page 9

Setting VariablesProgramming is all about doing stuff to things. Generally, the stuff is the execution of a process oralgorithm and the things are information or data.An algorithm is just a fancy name for a series of steps, like tying your shoelaces. Information or datais just values. Your name is a piece of information and so is your birth date. Since it's shorter, in thisarticle we'll use the word data to describe a piece of information.In ColdFusion, data is held in variables. Think of a variable like a mailbox. You can stuff things likeletters and packages into a mailbox and get them out later to do stuff. ColdFusion makes storinginformation very easy because it's a loosely typed Language. You can stick any kind of data into aColdFusion variable without having to tell ColdFusion what kind of data it is.Here's the simplest code to set a variable: cfset ThisIs "fun" / Now, any time I refer to ThisIs in my ColdFusion code, it'll hold the data "fun". You can look at thecontents of a variable in ColdFusion by using the cfdump tag. cfdump var "#ThisIs#" / See how the variable contains the string "fun"?A few things to note. Examine the statement again: cfset ThisIs "fun" / The part of the statement to the left (ThisIs) of the equals sign is the variable name. The part of thestatement to the right of the equals sign ("fun") is the value to assign to the variable.Now, in the second statement, you'll note we surrounded the variable name with pound # or hashsymbols. The pound sign tells ColdFusion to evaluate the contents. In the below example, thepound sign will tell ColdFusion to replace the ThisIs string with the contents of the previously definedvariable ThisIs. cfdump var "#ThisIs#" / Here's another way to look at pound sign use. Examine the below three statements. Can you guesswhat will happen in each case?Learn CF in a Week - Week 1Page 10

cfdump var "1 2" / br / cfdump var "#1 2#" / br / cfdump var "1 2 IS #1 2#" / br / In the first statement, our math problem is surrounded by the Double Quote character. This tellsColdFusion to treat the statement as a string and do no evaluations on it.In the second statement, we also surrounded the math problem with the pound sign. ColdFusionexecutes the statement and performs our calculation for us.In the third statement, notice we've mixed strings and evaluations through the correct use of thepound sign and the double quotes.The Left Side Of The Statement: cfset ThisIsThe left side of the statement is the variable name. You can have numbers as part of the variablename, but the variable name must start with a letter. You must not have any spaces in your variablenames. If you need to use more words for your variable name, you can simply write the variable withCamelCase letters, or use Under Scores to separate each word if you want. The choice is one ofstyle, there are no right answers. Also, most special characters are not allowed in variable names. Agood rule to follow is variable names should be descriptive and help provide context to what is beingdone.For example, the word variable is a bad naming choice because the name adds no context to whythe variable exists: cfset variable "12/26/1975" / The variable name UserBirthdate is a good naming choice because it adds context to why thevariable exists: cfset UserBirthdate "12/26/1975" / Pro Tip: You'll understand the most about WHY your program is written a certain way as youare writing it. Take advantage of that hard-earned understanding and leave yourself (or others)as many clues and as much context as possible. Later on, after you've forgotten some of thedetails, it'll be much easier to

3. Select the English MAC OS X version of ColdFusion. 4. Click "Download". 5. Save the file to your desktop. 6. Once downloaded, double click the file. 7. Click "Next". 8. Accept the terms and click "Next". 9. When you see the screen below, select "Developer Edition" and click "Next". 10. Select Se