homeservicesportfoliocontactwebsite design tutorials
 

 

 
 

To the index

CFML

  • Can cflocation be used to redirect a particular frame within a frameset?
  • Can users accidentally share variables set in the Request scope?
  • Have the variable naming rules changed with ColdFusion MX?
  • How can I alter the format of a DateTime object so it doesn't look like {ts '2001-01-21 10:57:21'}?
  • How can I alternate the background colour to my table rows?
  • How can I check the spelling of words entered in a form?
  • How can I confirm that a user hasn't edited variables submitted with a form?
  • How can I detect if their browser has cookie enabled?
  • How can I display a recursive directory listing?
  • How can I display the columns in a query without specifying the column names?
  • How can I find out when a particular function was introduced?
  • How can I loop through all the form fields and values?
  • How can I make ColdFusion server pause before processing the rest of a template?
  • How can I output a database query in a table three cells wide?
  • How can I prevent users seeing ColdFusion error messages?
  • How can I put a carriage return in a string?
  • How can I remove the whitespace that's appears in the source of .cfm pages?
  • How can I see when a file was last modified or created?
  • How can I stop the cfid/cftoken values being appended to the URL when using cflocation?
  • How can I stop users submitting a form twice?
  • How can I uncache a cached query?
  • How can I use Iif and IsDefined to test for the existence of a variable without it throwing an error saying that the variable isn't defined?
  • How can I use the # symbol inside cfoutput?
  • How can I write a text file on the server?
  • How can you create two select boxes where the second alters when the first selection is changed.
  • How can you display all the form variables passed to a template?
  • How can you display the date/time of when a ColdFusion template was last modified?
  • I'm trying to set a cookie just before doing a cflocation but the cookie is never set. Why is this?
  • If I dynamically create a variable by using <cfset CountVar = "MyVar#x#">, how do I display the value of MyVar#x#?
  • If just use <cfset SomeVar = 1> in the Application.cfm file, are they created as Application varibales?
  • Is it more efficient to put wrap your entire template in <cfoutput></cfoutput> or just the variables that are displayed in the template?
  • Is ParameterExists() going to made be obselete?
  • Is there a way to display the total number of files in a directory?
  • Is there a way to specify a timeout period on a ColdFusion page?
  • Is there an easy way to display banner adverts on a site?
  • Is there any way for ColdFusion to determine the browser's settings (for example, the users screen resolution)?
  • What are the different variable scopes and what variables are there?
  • What is the request scope for?
  • What is the syntax to query a query in ColdFusion 5?
  • What WYSYWIG HTML editing tools are there to enable customers to edit web pages via their browser?
  • When do I need to use # symbols around variable names?
  • Why are my form fields visible in the querystring when the form is submitted?
  • Why don't Request scope variables need to be locked in ColdFusion 5 Server?
  • With two cfquerys on a page, how can you stop the first SQL statement from being run if the second one fails?
  • Have you got any tips on optimizing ColdFusion code?
  • How can I find the size of an image before it's been uploaded to the server?
  • How can I preserve the original order or column names when looping through a CFQUERY recordset using queryName.columnList?
  • How can I sort a multi-dimensional array?
  • How can I stop my webpages from being cached?
  • How can I zip up files on the server?
  • How do search engines react to URL query strings and how can I get my ColdFusion sites listed?
  • How to you embed error.Diagnostics as a hidden form field without it being accidentally displayed because its value includes a ' or an "?
  • How would I go about creating a multi-language site?
  • If a template has Form.Date and URL.Date and I refer to Date, which does ColdFusion use?
  • Is it possible to create a file on a mapped drive using cffile and a UNC path?
  • Is there any methodology that can help me write better ColdFusion applications?
  • Is this possible to use OOP (object oriented programming) in ColdFusion?
  • Is using cflock really necessary and how do you use it?
  • What does the error message !var=CFTempOnlyForSetVariableNeverUseThisNameInYourCFMLCode122333444455555654321 mean?
  • What is the difference between maxrows and blockfactor in cfquery?
  • What is the isolation attribute in the cftransaction tag for?
  • What list delimiter character can you use that can't be typed in by a user?
  • What tags and functions can be used within CFExpress?
  • When using cflock, when should I use the name attribute and when should I use SCOPE?
  • Beginner

    Can cflocation be used to redirect a particular frame within a frameset?

    ColdFusion, and server-side code in general, doesn't know anything about framesets. When you use cflocation, ColdFusion simply adds an HTTP redirect header to the HTTP response header.

    So, the short answer is "no".

    to question

    Can users accidentally share variables set in the Request scope?

    No. The Request scope exists on a per http request basis, i.e. the variables in the Request scope only exist while ColdFusion is completing that single request. They die as soon as ColdFusion has finished processing the request.

    If your server is set up to process 5 maximum simultanious connections, then, in theory, there could be 5 sets of Request variables in server memory. Each set is tied to a particular http request and cannot exist in another page request unless you copy them into another scope.

    to question

    Have the variable naming rules changed with ColdFusion MX?

    Yes. In CFMX, variables can now start with an underscore or dollar symbol.

    to question

    How can I alter the format of a DateTime object so it doesn't look like {ts '2001-01-21 10:57:21'}?

    Look into DateFormat and TimeFormat. They are functions that take a datetime object as an argument along with a mask. The mask determines how the date and time values are displayed.

    Incidentally, if you want to display the date and time together, you still have to use both functions - there isn't a DateTimeFormat() function. Just use them one after the other, passing the same variable to them. For example

    #DateFormat(YourDate, "dddd d mmm yyyy")# #TimeFormat(YourDate, "h:mm:ss tt")#

    to question

    How can I alternate the background colour to my table rows?

    Use the MOD function. MOD returns the remainder when one number divided by another. Eg 2 MOD 2 is 0 (2 divided by 2 is 1 remainder 0), whereas 3 MOD 2 is 1 (3 divided by 2 is 1 remainder 1). Here we use CurrentRow to refer to the number of the current record being output within the query.

    <cfoutput query="MyQuery">
       <td bgcolor="###Iif(CurrentRow MOD 2 is 1,DE("00FF00"),DE("FF0000"))#">
    </cfoutput>

    to question

    How can I check the spelling of words entered in a form?

    Use Ben Forta's CFX_Spell.

    to question

    How can I confirm that a user hasn't edited variables submitted with a form?

    What you want to do is impossible within the limitations of the HTTP protocol. Any data from the browser is subject to tampering by the user of that browser.

    The painful truth is that you must validate all data sent from the browser.

    to question

    How can I detect if their browser has cookie enabled?

    You can't read a cookie back immediately, since it will always appear as though the browser has accepted the cookie. Try including something like this, it hands the browser a cookie, then forwards them back to the same page.

    <!--- BrowserTakesCookies.cfm --->
    
    <cfif not IsDefined("Cookie.CookieTest")>
       <cfif IsDefined("URL.CookieTested")>
          <cfset variables.BrowserTakesCookies = FALSE>
       <cfelse>
          <cfcookie name="CookieTest" value="TRUE" EXPIRES="NEVER">
    
          <cfif CGI.QUERY_STRING IS not "">
             <cfset variables.IV_URLAppend = " #CGI.QUERY_STRING#&CookieTested=TRUE">
          <cfelse>
             <cfset Variables.IV_URLAppend = "?CookieTested=TRUE">
          </cfif>
    
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
          
          <cfoutput>
          <html>
          <head>
          <title>Testing Browser...</title>
          <meta http-equiv="Refresh" content="0;url=#CGI.SCRIPT_NAME##Variables.IV_URLAppend#">
          </head>
          <body>
          
          </body>
          </html>
          </cfoutput>
       </cfif>
       
    <cfelse>
       <cfparam name="Variables.BrowserTakesCookies" default=TRUE>
    </cfif>

    Once you've include the file, you need only to check the 'BrowserTakesCookies' variable.

    to question

    How can I display a recursive directory listing?

    Use CF_DirectoryList_Enhanced.

    to question

    How can I display the columns in a query without specifying the column names?

    <cfquery datasource="#request.DSN#" name="GetRecords">
       SELECT *
         FROM Employees
    </cfquery>
    
    <cfloop list="#GetRecords.ColumnList#" DELIMITERS="," index="column">
       #column#<bR>
    </cfloop>

    to question

    How can I find out when a particular function was introduced?

    http://www.houseoffusion.com/hof/functions.cfm

    to question

    How can I loop through all the form fields and values?

    <cfloop list="#form.FieldNames#" index="FormField">
        <cfoutput>Current form field: #FormField#</cfoutput>
    </cfloop>

    to question

    How can I make ColdFusion server pause before processing the rest of a template?

    Use CFX_Sleep.

    to question

    How can I output a database query in a table three cells wide?

    <table>
    <cfset counter = 0>
    <cfloop query="table_query">
       <cfset counter = counter + 1>
       <cfif counter EQ 1>
          <!--- first cell in row --->
          <tr>
       </cfif>
       <td>
       <cfoutput>#config_name#</cfoutput>
       </td>
       <cfif counter EQ 3>
          <!--- last cell in row --->
          </tr>
          <cfset counter = 0>
       </cfif>
    </cfloop>
    <cfif counter neq 0>
       <!--- in case the query's record count isn't a multiple of three --->
       </tr>
    </cfif>
    </table>

    to question

    How can I prevent users seeing ColdFusion error messages?

    Put the cferror tag in your Application.cfm:

    <cferror type="REQUEST" template="error.cfm" mailto="developer@apa.org">

    then in error.cfm, for example:

    <p>An error has occurred that prevents us from completing your request.</p>
    
    <p>We have logged the following information that will help us identify and correct the problem:</p>
    
    <ul>
       <li>Error occurred at <b>#ERROR.Datetime#</b> 
       <li>Your IP address is <b>#ERROR.RemoteAddress#</b> 
       <li>Your browser is <b>#ERROR.Browser#</b> 
       <li>You were trying to process <b>#ERROR.Template#?#ERROR.QueryString#</b>
    </ul>
    
    <p>If you can provide us with any additional information that would help us fix this problem,
    please send E-Mail to: <a href="mailto:#ERROR.MailTo#">#ERROR.MailTo#</a></p>

    to question

    How can I put a carriage return in a string?

    In Windows a carriage return is made up of two characters; carriage return and a line feed. In ColdFusion, you can use the Chr() function to output a character. Chr() takes one argument; the ASCII code of the character you want to output. So, to create a carriage return, concatenate a carriage return, Chr(13), with a line feed, Chr(10) like this.

    <cfset variables.CrLf = Chr(13) & Chr(10)>
    <cfset MyString = "First line" & variables.CrLf & "Second line">

    to question

    How can I remove the whitespace that's appears in the source of .cfm pages?

    Two ways. Either use the cfsetting tag

    <cfsetting enablecfoutputonly="Yes">
    A bunch non-displaying CFML tags
    <cfsetting enablecfoutputonly="No">

    or use CF_StripWhitespace.

    to question

    How can I see when a file was last modified or created?

    Check out the cfdirectory tag, with action="LIST". It returns a CFML query with columns including Name and DateLastModified.

    to question

    How can I stop the cfid/cftoken values being appended to the URL when using cflocation?

    Add the attribute addtoken="No" to the cflocation tag.

    to question

    How can I stop users submitting a form twice?

    This JavaScript disabled the button after it's been pressed and changes the button text to "Please Wait".

    <input type="Submit" value="Submit" onClick="if(this.value ==
    'Submit') this.form.submit(); this.disabled=true; this.value = 'Please
    Wait.';">

    Alternatively, try CF_SendOnce or read this article.

    to question

    How can I uncache a cached query?

    To refresh a specific query, run the query again with a CreateTimeSpan value of (0, 0, 0, 0). This has the effect of removing the old cached query from memory.

    <cfquery datasource="#request.DSN#" name="MyCachedQuery" cachedwithin="#CreateTimeSpan(0, 0, 0, 0)#">
       SELECT *
         FROM Sometable;
    </cfquery>

    Alternatively, to clear all queries from the server's cache, use this

    <cfobjectcache
       action="CLEAR">

    to question

    How can I use Iif and IsDefined to test for the existence of a variable without it throwing an error saying that the variable isn't defined?

    <cfset Value = "something">
    
    <cfoutput>
    #Iif(IsDefined("Value"), "Value", DE("nothing"))#
    </cfoutput>

    Delete the first line, and you'll see "nothing" output to the screen. If you remove the quotation marks around "variables.Value", ColdFusion will try to evaluate the variable called "something" which doesn't exist and this will throw an error.

    to question

    How can I use the # symbol inside cfoutput?

    Escape the pound sign by using two of them, like this

    <font color="##FF0000">Some text</font>

    Within applications, certain characters have a special meaning. For instance, then pound sign within ColdFusion tells ColdFusion Server to process any text in between. However, sometimes, as in the case of the pound sign, we want ColdFusion to not process output but to actually display the literal character itself.

    Escaping characters is the way of indicating to an application that when you use one of those characters that have a special meaning, that you literally mean that character.

    to question

    How can I write a text file on the server?

    You can use

    <cffile action="WRITE"...>

    to write ASCII text to a file.

    to question

    How can you create two select boxes where the second alters when the first selection is changed.

    Use CF_TwoSelectsRelated.

    to question

    How can you display all the form variables passed to a template?

    form.FieldNames gives a comma-delimited list of all form variables passed to a template. Using CFLOOP, we can loop over this list, evaluating each variable as we go.

    <cfloop list="#form.FieldNames#" index="FieldName">
      <cfoutput>#Evaluate("form." & FieldName)#</cfoutput>
    </cfloop>

    to question

    How can you display the date/time of when a ColdFusion template was last modified?

    ColdFusion pages don't have a Date Updated because they're dynamic every time.

    Consider why this makes sense: Say you have a page that has a query to a database. What is the Date Updated of the page? The date the .CFM file was updated? Or the last update of the data in the database? Who can tell? For that matter, what about custom tags?

    You can use CF_HTTP_TIMESTAMP from http://www.fsc.follett.com/ to set the Date Updated to a time you want, based on a file's timestamp.

    to question

    I'm trying to set a cookie just before doing a cflocation but the cookie is never set. Why is this?

    cfcookie and cflocation both write header information to the client. As ColdFusion doesn't send out any information until after a page request has completed processing, the cflocation being the last header-writing part of your template gets to write to the header, overwriting anything that cfcookie had prepared to write.

    As a workaround, you could set the cookie using ColdFusion and then use the JavaScript location.href to redirect the browser.

    to question

    If I dynamically create a variable by using <cfset CountVar = "MyVar#x#">, how do I display the value of MyVar#x#?

    Use Evaluate(CountVar).

    to question

    If just use <cfset SomeVar = 1> in the Application.cfm file, are they created as Application varibales?

    No, they are created in the Variables scope, just as if you had created them using the same code on a standard page.

    to question

    Is it more efficient to put wrap your entire template in <cfoutput></cfoutput> or just the variables that are displayed in the template?

    No matter what version, it's always slower to put <cfoutput> at the top </cfoutput> at the bottom.

    The fastest way for the server is that you put a CFOUTPUT around only the bit that contains the variables - otherwise CF has to scan through everything inside the tags to see what it does and doesn't have to translate for variables/functions. It takes longer to code, but is definitely faster on the server.

    to question

    Is ParameterExists() going to made be obselete?

    Yes. ParameterExists is not deprecated (meaning that it may work with current versions of ColdFusion Server, but it will be dropped at a future time). Use IsDefined() instead.

    to question

    Is there a way to display the total number of files in a directory?

    <cfdirectory directory="c:\winnt\" name="FileCount">
    
    <cfoutput>#FileCount.RecordCount#</cfoutput>

    to question

    Is there a way to specify a timeout period on a ColdFusion page?

    Set the RequestTimeout value as a form or url variable, for example

    http://normal.url.code.com/searchpage.cfm?Requesttimeout=100

    The value is measured in seconds.

    to question

    Is there an easy way to display banner adverts on a site?

    http://www.fuseware.com/ CF_Rotate

    to question

    Is there any way for ColdFusion to determine the browser's settings (for example, the users screen resolution)?

    There is no way of doing this directly with ColdFusion (remember, it runs on the server, not on the client).

    The following code illustrates how you can obtain the screen width and height using JavaScript. It creates an HTML form, containing hidden form inputs with the screen width and height, and the form is automatically submitted to page2.cfm when the page is loaded. page2.cfm can then refer to those form variables.

    <script LANGUAGE="JavaScript" type="text/javascript">
       function GetScreen(width,height) {
          document.write('<form name="form1" action="index2.cfm" method="post">');
          document.write('<input type="hidden" name="width" value="' + width + '">');
          document.write('<input type="hidden" name="height" value="' + height + '">');
          document.write('</form>');
          document.form1.submit();
       }
    </script>
    
    <body onLoad="GetScreen(screen.width,screen.height);">

    to question

    What are the different variable scopes and what variables are there?

    Variable types

    server. (global - to machine - server memory)
    application. (global - to app - time limit on server)
    client. (global - to user -in db or reg)
    session. (global - to user - time limit on server)
    variables. (local - server memory)
    request. (local - server memory)
    cookie. (global - to user - on client)
    form. (local - action page - HTTP Body)
    url. (local - target page - In URL)
    cgi. (global - to user - HTTP request)
    caller. (local - to calling page - server memory)
    attributes. (local - to custom tag - server memory)
    ThisTag. (local - to custom tag - server memory)
    CFQUERY. (local - server memory (1 only/.executiontime))
    'queryname'. (local - server memory)

    Return value scopes

    CFCatch. (local - server memory)
    Error. (local - server memory)
    File. (local - server memory)
    CFFTP. (local - server memory)
    CFHTTP. (local - server memory)
    CFStoredProc. (local - server memory)

    Client variables

    client.LastVisit
    client.HitCount
    client.TimeCreated

    Query variables

    QueryName.ColumnList
    QueryName.RecordCount
    QueryName.CurrentRow

    Form variables

    form.FieldNames

    File variables

    file.AttemptedServerFile - Initial name ColdFusion used attempting to save a file
    file.ClientDirectory - The directory the file was uploaded from
    file.ClientFile - Original name of file
    file.ClientFileExt - Original file extension (no period)
    file.ClientFileName - Original file name (no extension)
    file.ContentSubType - MIME subtype of the saved file.
    file.ContentType - MIME content type of the saved file.
    file.DateLastAccessed - Date and time the uploaded file was last accessed.
    file.FileExisted - Was there a name conflict.(Yes or No)
    file.FileSize - Size of the uploaded file.
    file.FileWasAppended - Was the file appended to an existing file.(Yes or No)
    file.FileWasOverwritten - Was the file overwritten.(Yes or No)
    file.FileWasRenamed - Was the file renamed.(Yes or No)
    file.FileWasSaved - Was the file saved.(Yes or No)
    file.OldFileSize - Size of the overwritten file.
    file.ServerDirectory - "Local" directory of new file.
    file.ServerFile - Filename of new file.
    file.ServerFileExt - Extension of the new file. (no periods)
    file.ServerFileName - Filename of the new file. (no extension)
    file.TimeCreated - Time the uploaded file was created.
    file.TimeLastModified - Date and time of the last modification to the uploaded file

    CGI variables

    cgi.SERVER_SOFTWARE
    cgi.SERVER_NAME
    cgi.GATEWAY_INTERFACE
    cgi.SERVER_PROTOCOL
    cgi.SERVER_PORT
    cgi.SERVER_PORT_SECURE
    cgi.REQUEST_METHOD
    cgi.PATH_INFO
    cgi.PATH_TRANSLATED
    cgi.SCRIPT_NAME
    cgi.QUERY_STRING
    cgi.REMOTE_HOST
    cgi.REMOTE_ADDR
    cgi.AUTH_TYPE
    cgi.REMOTE_IDENT
    cgi.CONTENT_TYPE
    cgi.CONTENT_LENGTH
    cgi.HTTP_REFERER
    cgi.HTTP_USER_AGENT

    The Maryland CFUG has two relevant articles at http://www.cfug-md.org/Articles.cfm. Under the Coding Guidelines section, see ColdFusion Variables - Scope Characteristics and CF Variables - Storage and Life Cycle Analysis. These articles describe each scope rather than listing the server-supplied variables within each scope. Good job by TeraTech.

    to question

    What is the request scope for?

    The request scope is a variable scope that has arisen from the development of Spectra. Spectra uses custom tags extensively. To avoid having to explicitly pass variables from one tag to another as attributes, the request scope was developed as a variable that is "visible" to all templates that are executed within one page request. Normally, custom tags operate within their own scope and do not have access to (cannot "see") variables created in other tags. Request scope variables are visible to every tag called within one page's execution.

    The other benefit is that if you use application variables for constants within an application, you should use cflock around all references to them, along with session and server variables. The request scope does not need to be cflocked and, as such, is ideal for storing contant values that are typically scoped as application values.

    So in your Application.cfm file, instead of this

    <cfparam name="#application.DSN#" name="MyDSNName">
    write

    <cfset request.DSN = "MyDSNName">

    and refer to your database variable by using

    <cfquery datasource="#request.DSN#"...

    to question

    What is the syntax to query a query in ColdFusion 5?

    <cfquery DBtype="Query" name="QoQ">
       SELECT *
         FROM OriginalQueryName
    </cfquery>

    to question

    What WYSYWIG HTML editing tools are there to enable customers to edit web pages via their browser?

    http://www.cdev.com/ ActiveEdit
    http://www.ektron.com/ eWebEditPro
    http://www.siteobjects.com/ ezEdit
    http://www.iautomated.com/products/ HTMLArea

    If you're willing to deal with IE-only compatibility, you can make your own using the DHTMLEdit control built into IE4.0+.

    to question

    When do I need to use # symbols around variable names?

    http://www.defusion.com/articles/index.cfm?ArticleID=26 Ben Forta's article
    http://www.sys-con.com/coldfusion/archives/0106/schulze/index.html Bernard Schulze's article

    to question

    Why are my form fields visible in the querystring when the form is submitted?

    It'll happen if you don't have method="post" in your form. This is because the default method is get, not post. Check it's there and spelled correctly.

    to question

    Why don't Request scope variables need to be locked in ColdFusion 5 Server?

    They don't need to be locked, because they're not persistent memory variables. They're not shared between threads and therefore have no chance of being accessed simultaneously by 2 or more threads.

    to question

    With two cfquerys on a page, how can you stop the first SQL statement from being run if the second one fails?

    Use cftransaction. It's designed to ensure that either all database transactions in a block occur or none at all. The syntax is

    <cftransaction>
    
       <cfquery...>
          INSERT...
       </cfquery>
    
       <cfquery...>
          UPDATE...
       </cfquery>
    
    </cftransaction>

    to question

    Advanced

    Have you got any tips on optimizing ColdFusion code?

    Here's some advice from Ben Forta

    It’s very easy to write BAD CF code, because CF is a very easy language to learn.
    CF is an interpretive language, there is virtually no code compilation.
    Let the database do what it does best.
    Don’t use CF for operations that the database can do itself.
    Use dB enforced referential integrity
    Take advantage of triggers for pulling newly entered OrderID’s, etc.
    Specify unique constraints, and use CF error handling to catch errors.
    Use SQL aggregate and calculation functions, rather than CF aggregate functions.
    Take advantage of SQL server specific functions, for maximum optimization (use the SQL Scheduler)

    <cfoutput>

    use only when necessary!
    Any text within a <cfoutput> block must be parsed and inspected.
    Don’t place text between <cfoutput> tags unnecessarily!
    Often, <cfloop> can often outperform <cfoutput>
    Use <cfoutput query=""> when all the contents of the loop pertain to the query results.
    Use <cfoutput query=""> when the processing contains calculations, etc.

    Optimize conditional processing

    Use "NOT Error" rather than "Error is ‘No’"
    Use short-circuit boolean evaluation (CF 4.0.1 or later ONLY)
    Avoid unnecessary dynamic expression evaluation.
    Evaluate() and DE() functions allow you to write dynamic code, but slow!

    Enable Enforce Strict Attribute Validation server variable

    CF code is processed quicker when this is option is enabled
    Poorly written code may throw errors, but this is good for new development.

    Code Reuse

    Create small reusable sharable components
    Include common code using <cfinclude>
    Encapsulate code within your own tags.

    <cfinclude>

    Included pages share their parent’s scope.
    Included pages add almost no processing time (especially with caching)
    Best used for components that don’t use intelligent processing.

    Custom Tags

    Custom tags allow you to "black-box" code and provide cleanly published set of I/O.
    Custom tags are resource expensive, as they require their own environment.
    Included files are processed quicker than Custom Tags
    Best used for business/logic blocks, because they will not step on external variables.

    Caching

    Minimize disk access to optimize performance, by storing data in RAM

    CF supports several forms of caching

    • page level caching
    • page output caching
    • database query caching (discussed later)
    Page Level Caching

    CF compiles pages into p-code before they are executed, p-code can be cached
    Administrator specifies cache size
    Page caching uses a MFU algorithm
    Page caching requires only that the source timestamp be checked on each request, and that check can be disabled in trusted cache mode.
    Cache size should be about the size of the sum of all of your CF pages (use dir /s)

    Page Output Caching

    Dynamic pages are processed slower than static pages
    CF can cache dynamic output to create simulated static pages
    Dynamic output is stored and reserved until the cache timeout interval, cutting down on dynamic processing time
    Page output caching is enabled using the cfcache tag. (research this)
    Use <cfinclude> to cache parts of pages, leaving other parts dynamic.

    Detecting Bottlenecks

    On most servers, CF can always process a page containing just HTML in under 10 ms.
    Use Debugging Output to examine execution times.
    Logging slow performance pages for ongoing performance checking.
    GetTickCount() function can be used to check performance of specific lines of code.
    The output from this function can be subtracted from another GetTickCount().

    Database Optimization

    Database access is almost always the culprit in poor performing CF applications
    Write efficient (optimized) SQL
    Use correct relational database design
    Correctly use primary and foreign keys
    Use and manage indexes
    Create and use stored procedures.

    Native Database Drivers

    Prior to CF4, all CF database support was via ODBC
    CF4 supports native support for Oracle and Sybase
    CF4.0.1 added native support for Informix and DB2

    Primary reasons to use native database sources:

    Performance.
    Improved stored procedure support.
    ODBC leaves a bad taste in many developers’ mouths.
    ODBC functions CANNOT be used with native database drivers.
    Don’t use CreateODBCDate(), CreateODBCTime(), etc.
    Must use DateFormat() and TimeFormat() functions to create appropriate date/time values.

    Query Result Caching

    CF queries are cached to improve application performance
    Some candidates are perfect candidates for caching
    Queries that never change (list of US states)
    Queries that are used as part of a "next 10" style interface
    Queries that need not be 100% current. (Employee lists, etc.)

    Variable based results caching

    not suited for dynamic queries, or for results that need a time-out
    cache can be easily flushed and updated
    refer to queries by ‘scope.query’ (application.states)
    cannot self-timeout, data manipulation must be aware of cache.

    Query based result caching

    Well suited for dynamic queries
    Max of 100 cached queries, cannot easily be flushed.
    Uses CACHEDWITHIN and CACHEDAFTER to set relative/absolute cache time.
    Actually caches compiled SQL, rather than result set.
    Requesting cache does not guarantee that the query will be cached
    Look in debugging data to see if a query has been cached.

    Stored Procedures

    Collection of stored procedures stored on server
    CF provides support for these via cfquery
    Does not provide access to multiple result sets, return codes. <cfstoredproc> is new to CF4
    passes parameters into and out of procedures.
    More versatile than CFQUERY, but more complicated.

    Block Factor (Use sparingly)
    Database drivers usually retrieve records one at a time
    Block factoring allows the database driver to retrieve multiple records in a single request.
    Good for queries that return lots of records.
    Specified at query level, so each query can have a specific block factor.
    Not all databases/drivers support block factoring.
    Errors are not thrown if block factoring is not supported, rather CF downgrades automatically.
    Can increase large query performance, but can degrade overall system performance.

    to question

    How can I find the size of an image before it's been uploaded to the server?

    It isn't possible as the HTTP protocol doesn't have provisions for this. You must upload to the server first and then do your check's on the image.

    to question

    How can I preserve the original order or column names when looping through a CFQUERY recordset using queryName.columnList?

    Use CFX_QueryColumns or CF_ColumnList to sort the columns.

    to question

    How can I sort a multi-dimensional array?

    In a 3-dimensional array the first and second dimensions are arrays of pointers, not values. You'll need a loop to sort them.

    <cfset ta = arrayNew(3)> <cfset ta[1][1][1] = "a"> <cfset ta[1][1][2] = "b"> <cfset ta[1][1][3] = "c"> <cfset ta[1][2][1] = "f"> <cfset ta[1][2][2] = "h"> <cfset ta[1][2][3] = "e"> <cfset ta[2][1][1] = "q"> <cfset ta[2][1][2] = "j"> <cfset ta[2][1][3] = "k"> <cfoutput> <cfloop from="1" to="#arrayLen(ta)#" index="i"> <cfloop from="1" to="#arrayLen(ta[i])#" index="j"> <cfset temp = arraySort(ta[i][j],"text")> <!--- output the results for verification ---> <cfloop from="1" to="#arrayLen(ta[i][j])#" index="k"> #ta[i][j][k]#<br> </cfloop><br> </cfloop> </cfloop> </cfoutput>

    to question

    How can I stop my webpages from being cached?

    A bit hefty, but it's the technically correct method, and one of the few that AOL's proxies will pay attention to:

    <cfset gmt = gettimezoneinfo()>
    <cfset gmt = gmt.utcHourOffset>
    <cfif gmt EQ 0>
       <cfset gmt = "">
    <cfelseif gmt GT 0>
       <cfset gmt = "+" & gmt >
    </cfif>
    <cfheader name="Pragma" value="no-cache">
    <cfheader name="Cache-Control" value="no-cache, must-revalidate">
    <cfheader name="Last-Modified"
       value="#DateFormat(now(), 'ddd, dd mmm yyyy')# #TimeFormat(now(), 'HH:mm:ss')# GMT#gmt#">
    <cfheader name="Expires" value="Mon, 26 Jul 1997 05:00:00 GMT">

    Alternatively, in the flow of an application, you often need to return the user to a page that has already been displayed--but you've already passed new variables to the page so it will dynamically output something different this time. Since you don't want the user looking at the old page, you need to ensure that the page refreshes somehow and makes a call to the server again for reprocessing.

    Most popular browsers (Internet Explorer and Netscape) cache pages already visited on the local machine. Then, when another call is made for it, the browser pulls up the local copy rather than make another call for the page. This can prove to be a problem under the circumstances described above, since the old page will be displayed to the user.

    The key to creating a workaround for this situation is to know that browsers identify a page by its URL--if the URL is the same as the one it just cached locally, it uses the local copy. Accordingly, you can simply append a dynamically created variable name to the URL, thereby producing a new URL and forcing the browser to make a subsequent call to the server to retrieve the new, and up-to-date, page. Here is an example of the code you can use to do this:

    <cflocation url="index.cfm?norefresh=#Rand()#">

    Rand() returns a random number in the range of 0 to 1, including fractions, so the URL will be different each time you call it, which forces the browser to request the page again from the server. That, in turn, ensures the most current information will be displayed.

    A third option is to use standard meta tags

    <meta http-equiv="Refresh" content="0;url=MyPage.cfm">

    But, meta tags are for people who have only static pages, and cannot create HTTP headers. That's why it's "HTTP-EQUIV". It tells the browser "Pretend that you got this HTTP header".

    But we have ColdFusion. ColdFusion creates HTTP headers very nicely, using the CFheadER tag. If you want to create an HTTP header, then do it, rather than relying on the browser handling the meta tag properly.

    Try this in the head of a document:

    <cfheader name="Expires" value="Mon, 06 Jan 1990 00:00:01 GMT">
    <cfheader name="Pragma" value="no-cache">
    <cfheader name="cache-control" value="no-cache">
       
    <!-- meta anti cache-->
    <meta http-equiv="Expires" content="Mon, 06 Jan 1990 00:00:01 GMT"> 
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">

    to question

    How can I zip up files on the server?

    http://www.forta.com/cf/tags/
    CFX_Zip
    Also, you can use PKZip via the command line using cfexecute

    to question

    How do search engines react to URL query strings and how can I get my ColdFusion sites listed?

    The answer to your question of how the engines spider the sites varies almost daily. As soon as someone figures it out, they publish it, people abuse that knowledge to get ahead and the engines change their rules to compensate. The only way to win is to focus a great deal of time on this. I have done that for a few companies and can say that it is effective, but requires a lot of attention.

    However, to give you a little insight, I can give you a few hints.

    First of all, many engines will accept .cfm URLs. HOWEVER... ANYTHING after the ? in a .cfm URL will nearly always be skipped... COMPLETELY. While this is not the case in all engines, it is a good rule for the major 10 (which is where over 90% of all search engine traffic comes from). If you use index.cfm with parameters after it to build your entire site, assume you'll have just one page in the search engines (index.cfm with no parameters).

    If you wish for search engines to spider your site, you may be out of luck. They often won't read after the ? so if they see a URL and strip the ?, your site might break and they will stop (assuming they even try). One way around this is to use a Ben Forta trick. Create a url like:

    http://www.yoursite.com/index.cfm/productID

    where productID is the value of a variable productID. Then use the URL CGI variables delimited by / with a ListGetLast and you'll get the variable in your page to work with. Search engines won't see a ? and therefore will index the page and spider it as well. ALL URLs would need to be coded in this manner. I run a joke site (http://www.jokecenter.com) where I did this and it worked fairly well. However, I found .htm files worked better so I built a series of directories for this and that works better.

    A side note. If you do build a submission spider in CF, consider doing a few pages a day and not the same pages. If you submit a hundred pages an engine may decide you're spamming the engine and skip your entire set of entries. Schedule a few a day and you will probably have better results.

    Another rule to watch out for is that most engines take WEEKS to get you listed. So even if you're working hard, your results won't take effect for weeks. If your clients buy a product to monitor the engines, they may not see your work as effective for a while (if at all). Once you get a ranking, assume others are trying to take it away from you and stay on track or your ranking will erode.

    to question

    How to you embed error.Diagnostics as a hidden form field without it being accidentally displayed because its value includes a ' or an "?

    You can use a textarea instead of a hidden form field for Error.Diagnostics.

    While you might prefer to hide the error field by using a hidden form field, you can make the textarea very small, and potentially make it uneditable by the user as well.

    to question

    How would I go about creating a multi-language site?

    Did a dynamic five language site (Japanese, Korean, Cantonese, Mandarin, English) using access for prototyping and oracle for publishing. The language code is simple, note that you can only specify one charsetper page:

    <meta http-equiv='content-type' content='text/html;charset=#bnkCharSet#'>

    If you're using explorer and don't have support for that locale it will automatically try to download a font set for you, with Netscape you've to manually install the fonts.

    A list of common charsets can be found at
    http://www.w3.org/International/O-charset-list.html

    The database and interacting with it via forms was a little more tricky. After going through a few file formats we finally had the translators use notepad to translate into the different languages because double-byte and unicode characters were causing problems and losing certain characters in insert and update statements. They would save the files as text or html and we could simply copy paste them into the fields. Use the extended ascii set. Oracle has some nifty language support I would check out technet.oracle.com for more info, in access we used memo fields to store the html and translated content.

    On an English machine all except the html tags look garbled when you open the db but once you query it and throw it into a page with the above meta tag, the browser interprets the content and all's displayed fine. I have not tried this but I'm pretty sure if we had a Chinese version of windows/access we would see Chinese characters in access as well. Using ie goto ntt.co.jp and refuse to install the fonts or chose western European from the encoding menu under view, that's what the data looks like inside the field and this is what I'm referring to as 'garbled'. One problem was updating the db from a textarea. The admins for the site were using English machines and were to be responsible for maintaining the site, but we had localized the admin pages where the database was to be updated using the charset code above so that when you copied and pasted the (garbled) text in to the textareas you could see the localized content and do some visual formatting if need be. Bad choice, since the page was 'labeled' as Japanese when you inserted the textarea content into the db it would come back out as Unicode. Lots of u1234, u2345 stuff. Changed the the charset back to English and all was fine for a while. After a myriad of different problems in different languages similar to the above I switched from textareas to a modified version of activEdit (cfdev.com) to update the content. For some reason this dandy tag would always update the db in English (I'm assuming because it uses windows components), hence here's a solution for managing and translating localized content with the least amount of headache.

    1. Setup AcitvEdit instead of using textareas and specify the local charset at the top of the page.
    2. Feed the panel formatted (tables, images, vs.) ENGLISH version of the content. All the charsets that I used had English fonts embedded so this was possible.
    3. Have the translators TYPE into the panel over the English instead of sending you some unrecognizable file which you have to sift through. This is actually the most difficult part and a huge pia, because you have to put in an incredible amount of effort to get the translators to use your admin panel rather than his/her copy of word 2.0. I'll explain below. This method actually solves a major organizational problem. How do you know where one sentence ends and the other starts if you don't know Chinese? If you end up having to send out text only to get translated at least make sure you leave breadcrumbs behind.
    4. Update the db from activEdit, and serve it back out from the frontend making sure that you specify the charset.

    That's basically it. Except for one minor problem... the translators. I can't emphasize the importance of having them TYPE over the English content. Worst case copy and paste from NOTEPAD sentence by sentence, but don't let them know that upfront because more often than necessary they ended up copying and pasting from word documents or other similar fancy word processors. With activEdit that was a huge problem as word retains a whole bunch of utterly useless data along with the content.

    Weird div tags and incomprehensible font declarations really messes up your visual formatting not to mention that it usually spurts out ie only code. Export a localized document as html from word and you'll see what I mean.

    Did I mention that Arabic reads right to left? ;-)

    to question

    If a template has Form.Date and URL.Date and I refer to Date, which does ColdFusion use?

    If you do not specify the scope of the variable, according to the docs, CF will search for it in the following order (this is called the order of precedence):

    • Local variables, created using cfset and cfquery
    • CGI
    • File
    • URL
    • Form
    • Cookie
    • Client

    Other scopes always need to be scoped:

    • Server
    • Application
    • Session
    • Request
    • Attributes
    • Error

    to question

    Is it possible to create a file on a mapped drive using cffile and a UNC path?

    Yes, but ColdFusion Server needs to be logged on using an account that has access rights to the network (ie not as the default LocalSystem account, which is a security context analogous to a local Administrator with no network rights).

    The UNC must be the share name, so if the share is "d" then the path should be

    \\myServer\d\temp\myfile.txt

    to question

    Is there any methodology that can help me write better ColdFusion applications?

    http://www.black-box.org/
    http://www.cfobjects.com/
    http://www.defusion.com/articles/index.cfm?ArticleID=17
    http://www.fusebox.org/
    http://www.iiframework.com/
    http://www.litter-box.org/
    http://www.smartobjects.com/
    http://www.switch-box.org/

    to question

    Is this possible to use OOP (object oriented programming) in ColdFusion?

    No, as ColdFusion is not an object oriented language/environment. However Fusebox, Spectra and CFOjects all attempt to bridge this gap in thier own way.

    to question

    Is using cflock really necessary and how do you use it?

    http://www.sys-con.com/coldfusion/archives/0208/forta/ Ben Forta explains the importance of locking and how to do it
    http://www.allaire.com/handlers/index.cfm?ID=17318&method=Full
    http://www.allaire.com/handlers/index.cfm?ID=17196&method=Full
    http://www.allaire.com/cfdocs/Developing_Web_Applications_with_ColdFusion/12_Using_the_Application_Framework/dwa12_14.htm
    http://www.allaire.com/cfdocs/CFML_Language_Reference/2_ColdFusion_Tags/lr2_058.htm
    http://www.allaire.com/cfdocs/Administering_ColdFusion_Server/03_Configuring_ColdFusion_Server/admin0312.htm

    to question

    What does the error message !var=CFTempOnlyForSetVariableNeverUseThisNameInYourCFMLCode122333444455555654321 mean?

    http://www.mail-archive.com/cgi-bin/htsearch?method=and&format=short&config=cf-talk_houseoffusion_com&restrict=&exclude=&words=CFTempOnlyForSetVariableNeverUseThisNameInYourCFMLCode122333444455555654321

    to question

    What is the difference between maxrows and blockfactor in cfquery?

    maxrows specifies the maximum number of rows. blockfactor specifies the number of rows that CF will attempt to store in the database driver's storage buffer upon each row fetch. The two don't have anything to do with each other. The buffer is 32 Kb, so you can figure out how many rows (assuming the maximum possible row length) can fit into the buffer, then specify that number as the blockfactor attribute value. This is a performance enhancement; it makes getting the data faster. It doesn't affect how many rows will be returned by your query.

    to question

    What is the isolation attribute in the cftransaction tag for?

    The isolation attribute is used to specify how that transaction will behave with regard to database locking. I'll try to provide a very brief, general (and incomplete) description; the details may vary slightly between database servers. There are four possible values:

    READ_UNCOMMITTED means that the transaction will not honor locks that it encounters, and it won't lock anything that it touches. This may result in bad things happening, such as "dirty reads" (reads containing data that hasn't been committed to the database yet). On the other hand, in some cases the performance gain may be worth the possibility of retrieving bad data. For example, if you wanted to retrieve aggregate values calculated from half a million rows of data, it probably wouldn't matter too much if one of those rows was being written to by another transaction during the calculation.

    READ_COMMITTED, the default value, means that the transaction will honor any locks that it encounters, and that it will place locks on data as needed - exclusive locks when writing data, and shared locks when reading data. This is generally the behavior you want when running transactions, at least. Your transaction may still be vulnerable to nonrepeatable reads (if you have multiple statements returning the same row, the data may have changed between those reads) and phantom data (when your transaction tries to select a nonexistent row, but another transaction inserts that row after your first select).

    REPEATABLE_READ prevents dirty and nonrepeatable reads.

    SERIALIZABLE prevents dirty and nonrepeatable reads, and phantom data. Serializable transactions can be run in any order, and you'll end up with the same result.

    These four isolation levels are those specified in ANSI SQL-92, so you can find out more about them from a good SQL reference. In general, the more isolated your transaction is from other transactions, the more locking will be required and they'll be more likely to have to wait in line before they can run.

    to question

    What list delimiter character can you use that can't be typed in by a user?

    Use one of the non-printing characters. For exmple the ASCII bell character, Chr(7).

    to question

    What tags and functions can be used within CFExpress?

    http://www.allaire.com/products/coldfusion/cfexpress/
    http://www.allaire.com/handlers/index.cfm?ID=13700
    http://www.allaire.com/handlers/index.cfm?ID=13570&method=Full&Title=Edition%20Comparison%20Matrix&Cache=False

    to question

    When using cflock, when should I use the name attribute and when should I use SCOPE?

    http://www.sys-con.com/coldfusion/archives/0208/Forta/index.html

    to question