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 not IsDefined("session.test")>
     <cfset session.test = "Not Set Yet">
    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.

    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
    Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
    DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
    All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
    The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
    CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
    Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
    The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
    SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...