Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

ColdFusion's Application Framework

Apply it to your development

For the past month or so, I've had the pleasure of doing some development in Lotus Domino. I worked with Domino a lot when I was just starting out my IT career, so I know it's a powerful development platform for client/server applications.

I'm sure if you're reading this, you're developing, or want to be developing, client/server applications with ColdFusion. In the Domino world, we have the Domino server and Lotus Notes client. When developing ColdFusion apps, your client is most likely Internet Explorer, Safari, or Navigator. Your Web server is probably IIS or Apache.

While juggling some Notes work with my standard Web fare, I started thinking about how the Lotus Notes client is different from a browser client. The Notes client is smart. It knows that I like my e-mail sorted by ascending date. It knows which documents I've read and which I haven't. Lotus Notes maintains my state in the application.

The browser, on the other hand, has no idea about any of these things. Every request exists in a vacuum and has no knowledge of any other request. This is a problem that plagues all Web applications, whether you're accessing your gmail account or changing your MSN home page preferences. How does the browser know what's going on? It doesn't, but thankfully in ColdFusion there is an easy way to handle this. This article will talk about ColdFusion's application framework.

cfapplication Tag
At the heart of ColdFusion's application framework is the cfapplication tag. This tag defines how ColdFusion stores application-specific and session-specific data. An application is a group of related actions or functions that work together to give the user a seamless experience. Any of the Web-based e-mail accounts, such as gmail, Yahoo Mail, or Hotmail would serve as a perfect example of a Web application. Even though there is only one application, there can be many users on it. A session keeps track of individual users.

These are the attributes of the cfapplication tag:

  • Name: The name attribute is used to accept the name of the application. ColdFusion uses the name to keep application and session data separate within the context of an application. You can have as many applications as you like on a ColdFusion server, but each one must have a different name. It is not uncommon to have a site and the site administrator running as separate applications, even though they often access the same database.

  • ApplicationTimeOut: The application timeout attribute specifies the life span of the application variables. You can specify the value of this attribute with the CreateTimeSpan function. More information on the CreateTimeSpan function can be found at http://livedocs.macromedia.com/coldfusion/ 6.1/htmldocs/functi53.htm#wp1102715. A little-known fact is that any place that you use the CreateTimeSpan function can be replaced with a constant value. For example, one day is equal to 1. Two days and 12 hours equals 2.5. You can find the specific value you need by wrapping the CreateTimeSpan function in a cfoutput, executing the template, and using the value output. Using the CreateTimeSpan function is more explicit, but using an integer value is one less function that your application has to execute. The maximum value set in the ColdFusion administrator will take precedence if this value is larger than that value. The timeout value is specified from the date of last access.

  • LoginStorage: The login storage attribute is used to specify where login information is stored. The login information is specified in ColdFusion's cflogin and cfloginuser tags. The default value is cookie, with the alternative being session.

  • SetClientCookies: By default, ColdFusion uses two values to associate sessions on the server with a specific client. The first value is CFID, which is an integer that increments. The second is CFTOKEN, which is a random number. The setClientCookies attribute tells CF whether to store these values as cookies. If set to no, you'll have to pass the CFID and CFTOKEN in the query string on each request to access session information. These values must be in the query string, so on form posts you must add them to the action attribute of the form tag, not pass them as hidden form variables. To make this easier, there is a session variable called URLToken that contains the query string with CFID and CFTOKEN. If you have J2EE sessions enabled in the ColdFusion administrator, ColdFusion will set a JsessionID value instead of CFID and CFTOKEN.

  • ClientManagement: The ClientManagement attribute is a Boolean value that tells the application whether or not to allow for client variables in the application. Client variables are similar to session variables, except that they are stored on disk instead of in memory. Client variables are better in clustered environments, because the data is accessible from all servers when stored in cookies or a central database.

  • ClientStorage: The ClientStorage attribute is used to specify the location where client variables are stored. There are three options here. The default is to store them in the registry. I wouldn't recommend ever using the registry. The registry is not designed for massive read and writes. I've also heard too many horror stories of the registry growing too big and bringing down machines. The second option is to store the client variables as browser cookies. This has advantages, such as the cookies will always exist when the user returns to the site. If you use cookies, there's a limit to the amount of data a single site can store as cookie data. The third option is my preferred (and the recommended) choice, which is to store the information in a database. You can specify the name of the data source for the value of this attribute. Storing client variables in a database is much slower than using browser cookies; however, your only size limitation is the amount of hard disk space you have. You can set the default client variable storage options in the ColdFusion administrator, although they can be overridden by the cfapplication tag.

  • SessionManagement: The SessionManagement attribute is a Boolean attribute that specifies whether session management is enabled for this application or not. The default is no.

  • SessionTimeout: The SessionTimeout attribute is similar to the ApplicationTimeout attribute. It specifies how long the session variables will exist. Its value can be set with the CreateTimeSpan function. The maximum value set in the ColdFusion administrator will take precedence if the attribute value is larger than that CF Admin value. The timeout value is referenced from the date of the last request.

  • SetDomainCookies: The SetDomainCookies attribute is used on clustered servers. Instead of setting the cookies for the host, it sets them for the full domain. That means when a user switches from one machine to another, ColdFusion will still know about the user's session. Keep in mind that session variables are not stored between requests; however, client variables stored as cookies or in a data source are, assuming that both machines have access to the same data source, of course.

    In a typical cfapplication tag, you'd probably use:

    
    <cfapplication name="MyApp" applicationTimeOut="1" clientstorage="MyDSN"
     setClientCookies="Yes" sessionManagement="Yes" sessionTimeOut = ".4">
    
    This will create the application MyApp with an application timeout of one day and a session timeout of one hour. ClientStorage will be in the MyDSN database, and the CFID and CFTOKEN values will be cookies on the user's machine. Domain cookies are not set, since that is the default behavior and we didn't specify the attribute. Login storage information will be stored as cookies, since we didn't specify that attribute either.

    Application, Session, and Client Variable Scopes
    One of the primary reasons for setting up an application with the cfapplication tag is so you can store application and session-specific data between page requests. If you do not set a cfapplication tag in a page request, you can still use variables in the application, client, or session scopes. However, there will be no way to reference the values on your next page request. You should always set up your application using the cfapplication tag.

    Because variables in the application, client, and session scopes persist between requests, you often need to set them only on application or session initialization, respectively. Unfortunately, ColdFusion does not have a way to execute code when a session or application is initialized. There is a great Java workaround for this. You can read more about it in "Making the Most of J2EE Event Listeners," by Eric Brancaccio in the May 2004 edition of CFDJ. You may also want to tell Macromedia you want this feature to be in the next version of ColdFusion. If so, go to www.macromedia.com/support/email/wishform/.

    Until we have that feature, there is a simple method for simulating an application or session startup. You can use a cfif to see if one of your application, session, or client variables has been defined yet. This is a simple example:

    
    <cfif not IsDefined("application.test")>
     <cfset application.test = "Not Set Yes">
    </cfif>
    
    <cfif not IsDefined("session.test")>
     <cfset session.test = "Not Set Yet">
    </cfif>
    
    The code utilizes the cfif tag (reference this column in the April 2004 issue), cfset tag (reference this column in February 2004), and the IsDefined function. The IsDefined function accepts one parameter, a string. The string is the name of the variable. If the variable is defined, the function returns true, otherwise it returns false. If the application variable is defined, you don't have to do anything. If it isn't, then you need to define it. The same concept applies to session variables. Generally, you only need to check for the existence of a single variable. If one is not defined, then it is safe to assume that none of them are defined.

    Session and application variables are called shared scope variables, because they are stored in shared memory space. You should always consider locking your shared scope variable access with the cflock tag. An in-depth explanation of locking is beyond the scope of this article. Read about the cflock tag in the live docs: http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/tags-p71.htm# wp1100787. Versions of CF5 and prior had memory stability problems if you did not use locking. Read the Macromedia TechNote at www.macromedia.com/support/coldfusion/ts/documents/tn17882.htm. ColdFusion MX no longer has memory stability problems, but the best practices of locking remain relatively unchanged. You can find more information at www.macromedia.com/support/coldfusion/ts/documents/tn18235.htm.

    Client variables are stored on disk, either in a database, the registry, or as cookies on the client's browser. Since they are not stored in shared memory, they do not need to be locked.

    Application.cfm and OnRequestEnd.cfm
    You may now be saying, "So, Jeff, that cfapplication tag seems pretty powerful. And the method for creating application and session variables is simple, yet elegant. But, I don't want to have this code on every single page. Is there a simpler way?" Well, I'm glad you asked. Yes, there is a simpler way. ColdFusion has a reserve filename, "Application.cfm", which helps us set our application variables or session variables in one place.

    Application.cfm is a file that runs at the start of every request for a ColdFusion page. ColdFusion will search in the current directory, then the parent directory, and so-on, all the way up to the drive root until it finds a file called "Application.cfm". If it doesn't find one, then it continues processing normally. The Application.cfm file can be considered an implicit include, and if ColdFusion does find one, the code contained within Application.cfm will be executed (the same way that an included file is executed). That means the Application.cfm file is executed on every request for a ColdFusion page in that directory and below (provided none of the subdirectories has its own Application.cfm). This makes the Application.cfm ideal for things like the cfapplication tag, initializing application or session variables, and any other business logic you need to run at the beginning of every request.

    If the ColdFusion server finds an Application.cfm file it will search in the same directory for an "OnRequestEnd.cfm" file. Just like the Application.cfm, this file (if found) will execute on every page request. Unlike Application.cfm, the OnRequestEnd.cfm executes after the page is finished processing, not before. OnRequestEnd.cfm does not typically get as much use as the Application.cfm, but it's good to know it exists, as it can be useful for footers or application cleanup at the end of each request.

    Conclusion
    When the Web started out, it wasn't being used for anything other than static content. As time went by people started using it for much more. ColdFusion's application framework represents a powerful mechanism for turning a simple Web site into a Web application. This article gave you the groundwork; now all that remains is for you to apply it to your development. Let me know how it goes.

  • More Stories By Jeffry Houser

    Jeffry is a technical entrepreneur with over 10 years of making the web work for you. Lately Jeffry has been cooped up in his cave building the first in a line of easy to use interface components for Flex Developers at www.flextras.com . He has a Computer Science degree from the days before business met the Internet and owns DotComIt, an Adobe Solutions Partner specializing in Rich Internet Applications. Jeffry is an Adobe Community Expert and produces The Flex Show, a podcast that includes expert interviews and screencast tutorials. Jeffry is also co-manager of the Hartford CT Adobe User Group, author of three ColdFusion books and over 30 articles, and has spoken at various events all over the US. In his spare time he is a musician, old school adventure game aficionado, and recording engineer. He also owns a Wii. You can read his blog at www.jeffryhouser.com, check out his podcast at www.theflexshow.com or check out his company at www.dot-com-it.com.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    Every organization is facing their own Digital Transformation as they attempt to stay ahead of the competition, or worse, just keep up. Each new opportunity, whether embracing machine learning, IoT, or a cloud migration, seems to bring new development, deployment, and management models. The results are more diverse and federated computing models than any time in our history.
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Japan DX Pavilion at @CloudEXPO Silicon Valley
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Where many organizations get into trouble, however, is that they try to have a broad and deep knowledge in each of these areas. This is a huge blow to an organization's productivity. By automating or outsourcing some of these pieces, such as databases, infrastructure, and networks, your team can instead focus on development, testing, and deployment. Further, organizations that focus their attention on these areas can eventually move to a test-driven development structure that condenses several l...
    The term "digital transformation" (DX) is being used by everyone for just about any company initiative that involves technology, the web, ecommerce, software, or even customer experience. While the term has certainly turned into a buzzword with a lot of hype, the transition to a more connected, digital world is real and comes with real challenges. In his opening keynote, Four Essentials To Become DX Hero Status Now, Jonathan Hoppe, Co-Founder and CTO of Total Uptime Technologies, shared that ...
    Over the course of two days, in addition to insightful conversations and presentations delving into the industry's current pressing challenges, there was considerable buzz about digital transformation and how it is enabling global enterprises to accelerate business growth. Blockchain has been a term that people hear but don't quite understand. The most common myths about blockchain include the assumption that it is private, or that there is only one blockchain, and the idea that blockchain is...
    Never mind that we might not know what the future holds for cryptocurrencies and how much values will fluctuate or even how the process of mining a coin could cost as much as the value of the coin itself - cryptocurrency mining is a hot industry and shows no signs of slowing down. However, energy consumption to mine cryptocurrency is one of the biggest issues facing this industry. Burning huge amounts of electricity isn't incidental to cryptocurrency, it's basically embedded in the core of "mini...