cf tutorial

Upload: mulugeta-ashango

Post on 04-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/30/2019 Cf Tutorial

    1/28

    Developing Cold Fusion Applications Tutorial

    This document accompanies the CF pages that are labeled lesson1, etc. The applicationis a simple Human Resources application. Our final application will include CF pagesfor user input, processing input, and outputting results. Additionally, I have include filesdemonstrating login procedures, the application framework, and security. These files arenot fully documented. Additional references are the Allaire Documentation available for free from their web-site or you can purchase a book on ColdFusion, the book written byBen Forta generally considered the best.

    Lesson 1 Web Development Process of Static Pages

    1. Add simple text to the page: My Name is Ron2. Use the toolbar to edit the Font for the text you typed above.3. Save the file as: name.cfm (a good habit is to explicitly type the .cfm)4. ftp the file to your directory on the server 5. In the browser address box input the address of where you saved the file:

    http://ein5990.eng.fiu.edu/userc20/cftemplates/Name.cfm6. Go back to CF Studio. By right mouse click on a tag the edit window appears.

    For example, right click on the text you typed and you can change the font tag.

    Lesson 2 CFSET

    1. Open the file from lesson 1 and rename it for lesson 2 (use SAVE AS)2. Under the text type 3. Add
    and then text My Age is4. Add #MyAge#5. Save the file and view it in the browser.6. Select view source from your browser window. Do you see the CF tags? Why

    not?

    * CFSET is used to assign a local variable* CFOUTPUT is required to output any Cold Fusion variable to the page.* Notice that CFStudio color codes the different types of tags, variables, etc.

    Lesson 3 More about variables

    1. Create a new CF page2. create a local variable using CFSET for FirstName (remember to put around

    the value of the variable)3. create a local variable called LastName

    http://ein5990.eng.fiu.edu/userc20/cftemplates/Name.cfmhttp://ein5990.eng.fiu.edu/userc20/cftemplates/Name.cfm
  • 7/30/2019 Cf Tutorial

    2/28

    4. create a final variable that concatenates the first two variables

    5. Add text, My Name is:6. Add a cfoutput tag to output the variable FullName after the text

    #FullName#7. Save the file, ftp to server, and view in browser.8. An alternative method is to put the text inside of the cfoutput tags

    My Name is: #FullName#9. Save the file, ftp to server, and view in browser. There should be no difference

    between having the text inside or outside of the CFOUTPUT tags.

    Variables

    Several different types of variables: Local Form Session CGI Client Cookie

    All CF Variables are typeless, you dont need to specify integer, text, or other types.Variable scope is different for each variable type.For example, the local variable we created with is only scoped for that page,furthermore, the variable is only available after the CFSET line since the CF code isinterpreted sequentially.

    Summary:

    Two tags were demonstrated: to define and set the value of local variables to replace the variable with its value and output it to the HTML page.

    - you put all variables in between # signs to replace variable name with itsvalue.

    - You can put text, HTML tags, and client variables in betweenCFOUTPUT tags. It ignores them except for the # signs.

    - CFOUTPUT is a very important tag.

    Lesson 4 Querying a Database

    1. Create a new page2. Use the CFQUERY tag to embrace SQL query to the database.

  • 7/30/2019 Cf Tutorial

    3/28

    SELECT FirstName, LastName, StartDate, Salary, TemporaryFROM Employees

    #FirstName# #LastName# #StartDate# #Salary# #Temporary#

    SummaryThe CFQUERY tag is used to enclose SQL queries that are sent to the Datasource specified.In a properly setup Cold Fusion Development environment you can view the tablestructure through CF Studio which greatly aids you in writing the SQL. To output theresults of the query you use the CFOUTPUT tags but include the query name as shown. Thevariable names to output are the column names from the query you wrote. All other rulesfor CFOUTPUT still apply.

    About CFQUERY

    The SQL does not get a semicolon (;) delimiter for the end of the SQL. Also, text must be in single quotes when used in the WHERE clause. For example:

    SELECT FirstName, LastNameFROM EmployeeWHERE FirstName = #Form.FirstName#

    However, numbers do not use single quotes.

    SELECT FirstName, LastNameFROM EmployeeWHERE EmployeeID = #EmployeeID#

    Lesson 5 Formatting the data

    Tables are the easiest method for controlling the layout of HTML pages. In this lessonwe learn how to use the CFOUTPUT tag with HTML table tags to output each row of thequery as a row of the table.

    1. The CFOUTPUT tag must be outside of the table row tag. Then for eachinstance of the query a single row will be outputted. Also, note the use of specialformatting tags for Dates and Currency.

  • 7/30/2019 Cf Tutorial

    4/28

    First NameLast NameStart DateSalaryTemporary

    #FirstName##LastName##DateFormat(StartDate)##DollarFormat(Salary)##Temporary#

    2. Except for full-time developers, memorizing the special formatting tags like

    DollarFormat(salary) is not realistic. Learn how to utilize the help in order tofind special formatting tags.

    Forms

    Forms allow the user to input data. This can be used to insert new records into a database(use the SQL Insert); to update existing records (SQL Update); to search the database onspecific criteria (the user-specified criteria goes in the Where clause). To use forms youneed two pages: The form page and the action page. The form page is used to collect thedata. The data is saved into a form variable. The form variables are sent to the action

    page where they are processed. Note, the scope of form variables is the action page. It is

    suggested that you include the words form and action in the file names. For example, ona form used to collect new employee information for inserting into the database call itInsertForm.cfm and call the corresponding action page InsertAction.cfm .

    All Cold Fusion pages must use the method POST.

    Check boxes and radio buttons do not send data to the Action page if they are notselected. Thus, on the action page you must use an IF statement to see if they werechecked.

    Lesson 6 Form Page

    1. Forms must identify the action page the data will be sent to and the HTTP methodto use. For Cold Fusion applications always use the POST method. The HTTPmethod is GET.

  • 7/30/2019 Cf Tutorial

    5/28

    3. This course does not cover basic HTML. You should be familiar with all thecontrols (input devices) available for collecting data from the user.

    Lesson 6 Action Page

    1. To identify the variable as a form variable precede it with Form.

    Last Name: #Form.LastName#
    Department:#Form.Department#
    Temporary Status: #Form.Temporary#

    2. This is only a simple action page that shows what the user input.

    Lesson 7 Action page with Conditional Logic to Check Input

    There are several methods to validate user input and to check for values in radio buttonsand check boxes. Here we will show the Cold Fusion approach. However, JavaScript is

    probably preferable for developing scalable web applications because it is performed onthe client-side whereas Cold Fusion is performed on the server-side. In web applicationsthis is a critical difference.

    The user must enter text into the box so we check if they leave the field blank by using anIF statement. The IF statement is shown below.

    Last Name: #Form.LastName#

    Last Name Not Entered!

    We can also use the IF logic to see if the checkbox for temporary is selected. Notice howwe use this to specify whether the employee is temporary or permanent.

    Status: Temporary Employee

    Status: Permanent EmployeeAn alternative approach to check the form input is with the Len tag. Also, you can definetwo local variables Valid and Error . Then at the end just check if Not Valid .

  • 7/30/2019 Cf Tutorial

    6/28

    Here we check if the email entered is valid or not. This is a more complicated formvalidation since we cannot simple check if it is text or integer.

    Lesson 8 dynamically populate drop-down boxes

    In most web applications when a drop-down select box is used the developer mustenumerate all of the options. For example, if the select box is for states then all 50 statesmust be programmed into the HTML page. Cold Fusion provides a method to

    dynamically populate the select box options. So for example, if we wish to add PuertoRico as a new state then we just add it once to the database and it will appear dynamicallyon all select boxes.

    Department

    All

    #Department_Name#

    CFINCLUDE

  • 7/30/2019 Cf Tutorial

    7/28

    Use CFInclude to include code segments from other files. For example to include thetitle bar. On the page you insert into you put the following code segment:

    The code you insert should not have the AND tags since it will beinserted into another page.

    Lesson 8 Action page that dynamically generates SQL

    In order to search on multiple items but also allow the user to only input a subset of themyou use conditional logic embedded into the SQL. For example, this code allows the user to search on any single field or combination of all three fields. If the user does not enter alast name then it is not used in the query.

    SELECT Employees.FirstName,Employees.LastName,Departments.Department_Name,Employees.StartDate,Employees.Salary,Employees.Temporary

    FROM Employees, DepartmentsWHERE Departments.Department_ID = Employees.Department_ID

    AND Employees.LastNameLIKE '%#Form.LastName#%'

    AND Departments.Department_Name =

    '#Form.Department_Name#'

    AND Employees.Temporary = '#Form.Temporary#'

  • 7/30/2019 Cf Tutorial

    8/28

    Sometimes there may be no records in the database that must the users search. Insteadof letting the system generate an error you add the following code that utilizes a propertyof the query called RecordCount.

    No records match your search criteria.
    Please click the back button and try again.

    Lesson 9 Using Hidden Fields in forms to validate input

    The name of the hidden field must be the Input Name with an underscore (_) Required.The message the user is prompted goes into the Value.

    Here is the corresponding input text box.

    Employee First Name

    To enforce a date format use VariableName_Date or to enforce a real number useVariableName_float.

    Lesson 9 Action page to insert values

    We simple use SQL and the Insert command to insert the user entered data into thedatabase. Notice how we use the form variables in the Values section.

    INSERT INTO Employees

    (FirstName, LastName,Department_ID, StartDate,Salary, Temporary)

    VALUES('#Form.FirstName#','#Form.LastName#',#Form.Department_ID#,#Form.StartDate#,#Form.Salary#, '#TempStatus#')

  • 7/30/2019 Cf Tutorial

    9/28

    Application FrameworkAn application is a set of ColdFusion Templates that enables you to:

    Maintain state by setting variables that can be accessed from any template in theapplication (scope is the entire application).

    Provide custom error messages Enhance the security of an application

    The application framework consists of an application.cfm template that must be savedin the root directory and variables that have scope throughout the entire application.These variables are:

    Variable Type DescriptionClient Tied to a single client (or browser) and can

    persist over multiple sessions.Session Exists for a single client in a single sessionApplication For an application and accessible by

    multiple clients.Server Accessible by all clients and applications in

    a single server.

    The application.cfm template is processed first, before all other *.cfm templates in theapplication. The process of a user request for a page is as follows:

    1. User requests a cfm page in the application.2. Before the *.cfm page is processed, ColdFusion checks the directory for an

    application.cfm template.3. If no application.cfm template is found it checks the next higher directory.4. If no application.cfm template is ever found then processing of the requested *.cfm

    template takes place as usual.5. If the application.cfm template is found then it is processed first, and then the

    *.cfm template requested is processed.6. After the *.cfm template is requested ColdFusion then searches for a

    OnRequestEnd.cfm template. If found this template is then processed.

    The application.cfm template is consequently processed everytime a *.cfm template isrequested in the application. Consequently, you could define global variables and

    procedures in the application.cfm template that will be processed each time.

    To enable session, client, and application management you use the following tag:

  • 7/30/2019 Cf Tutorial

    10/28

    CLIENTSTORAGE = registry or cookie or name of datasourceSetDomainCookies = Yes/No

    >

    Attribute Description Value Default Required NAME Name of the application Name Yes

    SESSIONMANAGEMENT Enables session variables Yes/No No NoSESSIONTIMEOUT Time limit after which

    session expires (dontmake too long)

    Use thecreatetimespan function.

    CLIENTMANAGEMENT Enables client variables Yes/no No NoCLIENTSTORAGE Specifies where to store

    client variablesRegistry or cookie or data source

    Registry No

    SETCLIENTCOOKIES Specifies whether youuse cookies whendefining session andclient variables(otherwise you must passit on the URL)

    Yes/No Yes No

    Client Management

    Client variables are for a single client and persist over multiple sessions. Two clientvariables are set by default:

    CFID An incremental ID for each client that connects to the server CFTOKEN A random number used in conjunction with CFID to uniquely identify a

    particular client.

    You use these for:

    User display preferences such as background colors User content preferences such as stocks to watch, show sports stories, etc. Counts of how many times a user visits and when they visit last Items in a shopping cart and past purchases Scores for quizzes or games

    Default Client Variables

    LastVisit the date and time of the last visit.HitCount the number of hits on the applicationTimeCreated when the client cookie was first created

  • 7/30/2019 Cf Tutorial

    11/28

    Storage Alternatives

    The three storage options are registry, cookies, or external data sources. The registry haslimited memory and in a multi-server clustered environment cannot be used. The cookieshave limitations since clients may turn them off. Using a datasource eliminates these

    problems but it increases the number of database calls from the application server.

    Client variables are limited to 255 characters and no arrays or query recordsets.

    Session Management

    Session variables are stored in the Servers RAM (not very scalable). Session variablesare intended to be used for a short period of time. You use session variables for:

    Enforcing user login Storing arrays instead of passing them between templates Storing calculations Storing query recordsets.

    Notice, you can store more complex and larger variable data in session variables thanclient variables.

    To create a session variable:

    The CFLOCK tag is used to prevent problems with simultaneous read/write to sharedvariables. Although, a session variable is not shared it is recommended to use theCFLOCK. What CFLOCK does is it prevents others from use the shared resource until thefirst user releases it.

    A default session variable created is session.SessionID. You can use this to identify asingle session and user.

    The other two variable types; application and server are not discussed here due to

    infrequent use.

    Lesson 10 Sophisticated Login Pages

    The database should have a table with two attributes, UserID and Password. The systemlogin requires three pages: LoginForm.cfm LoginAction.cfm and Main.cfm. TheLoginForm is used to input username and password. The LoginAction checks via query

  • 7/30/2019 Cf Tutorial

    12/28

    the database to see if they match. If they do not match the user is prompted to try again.If they match the user is sent to the Main.cfm page via a CFLOCATION tag.

    LoginForm.cfm

    Please enter your user ID:

    Please enter your Password:

    LoginAction.cfm

    SELECT passwords.user_id,

    passwords.password,passwords.user_name

    FROM passwordsWHERE passwords.user_id = '#form.user_id#' AND

    passwords.password = '#form.password#'

    #title#

    Your User ID and Password are not in ourdatabase.
    Please try again.

  • 7/30/2019 Cf Tutorial

    13/28

    - Stops processing of page. - is a goto statement that sends the user to the page (URL) listed.

    Error Handling

    You can define generalized error handling for your application.

    Validation Errors: Occur when a user improperly completes and submits a form, such asnot filling in a text box.

    Request Errors: Occur due to misplaced template in an include tag, misspelled variablename or similar error.

    To define custom error handling you use:

    And you must create of course the page error_request.cfm .

    The CFERROR tag is best placed within the application.cfm template.

    mailto:[email protected]:[email protected]
  • 7/30/2019 Cf Tutorial

    14/28

    There are default error variable names such as error.diagnostics which you can use. Thereader is referred to ColdFusion user manual for the list of these variables.

    Trouble Shooting

    Trouble shooting skills require you to apply logic and the process of elimination.

    Common Errors:

    1. Spelling MistakesSpelling of the code as well as the variables.

    2. No closing tagFor example, #Form.UserID and you forget the closing # sign.

    3. type mismatch with databasesText requires single quotes and numbers do not. Also, need to validateform input to see that it matches the database table format.

    4. Mis-matching names

    Naming conventions are crucial. As sites become more complex if youhaphazardly name variables, forms, and pages then you will havedifficulty managing your site. For example, did you call a page to updateemployee records (UpdateEmployeeForm.cfm) but you called the form toinsert new employee records (EmployeeInsertForm.cfm). This isinconsistent naming and will become difficult to manage.

  • 7/30/2019 Cf Tutorial

    15/28

    The HR Database

  • 7/30/2019 Cf Tutorial

    16/28

    The Department Table

  • 7/30/2019 Cf Tutorial

    17/28

    The Employee Table

  • 7/30/2019 Cf Tutorial

    18/28

  • 7/30/2019 Cf Tutorial

    19/28

  • 7/30/2019 Cf Tutorial

    20/28

    Sorry. An error occurred.#Error#Please correct the error

    Name

    Phone

    E-mail

  • 7/30/2019 Cf Tutorial

    21/28

    The Form is Valid!

  • 7/30/2019 Cf Tutorial

    22/28

    Sending Your Greeting

    Hi!

    This is a quick, computer-generated greeting sent toYou courtesy of #Form.name# and the CFMAIL tag.Message Sent

    Your message to #Form.to# has been sent

    Oops

    You need to provide an E-mail address forthe recipient. Hit the Back button to return tothe form and provide one. Thanks.

  • 7/30/2019 Cf Tutorial

    23/28

    Job Scheduled

    Job Scheduled

    The report #Form.report#.cfm has been scheduled torun tonight at 11:00 p.m. for #Form.username#.

    Click here to scheduleanother report.

  • 7/30/2019 Cf Tutorial

    24/28

    SecurityColdFusion provides three tags for enforcing security of an application. These tags work with a directory of usernames and passwords for authentication and authorization toaccess certain resources. To establish security you must:

    1. Specify a secure server (the ColdFusion Server in our case).2. Specify a user directory to contain a list of users and groups of users to specify

    permissions to specific resources. This is done through the ColdFusionAdministration Page.

    3. Define a security context. A security context defines a cohesive group of resources and their security information. This is done through the ColdFusionAdministration Page.

    4. Associate User Directory with a Security Context. This is done through theColdFusion Administration Page.

    5. Define Security Rules. Rules define what actions are available on which

    resources. This is done through the ColdFusion Administration Page.6. Create a Security Policy that defines what user(s) are covered by what policies.

    This is done through the ColdFusion Administration Page.7. In the Application.cfm page use the appropriate tags to authenticate users.

    Tags

    CFAUTHENTICATE checks a username and password combination against a givensecurity context. Once checked, you can use the IsAuthenticated and IsAuthorized tagsto obtain results. You would use the CFAuthenticate tag in the application.cfm pagesince this page is accessed before all templates.

    The IsAuthenticated function is used to check if a user is authenticated. The functionreturns either True or False. Obviously, you could use IsAuthenticated to advantage witha CFIF tag.

    The IsAuthorized tag is used to secure specific resources based on the access policies

    created in the security context.IsAuthorized (ResourceType, ResourceName, Action)

    Resource type must match a resource in the security context definition. It can be:Application, CFML, File, Component, Collection, CustomTag, or UserObject.

  • 7/30/2019 Cf Tutorial

    25/28

    Actions depend on the resource type since not every action is possible with everyresource. For example, for a File actions can be Read or Write. You are referred to theCF manual for further details.

    Example Application.cfm listing

  • 7/30/2019 Cf Tutorial

    26/28

    Username:
    Password:

  • 7/30/2019 Cf Tutorial

    27/28

    Sorry. An error occurred.#Error#Please correct the error

    Name

    Phone

    E-mail

  • 7/30/2019 Cf Tutorial

    28/28

    The Form is Valid!