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.


    @ThingsExpo Stories
    In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
    With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
    Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
    SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
    WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a mu...
    Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
    Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
    SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
    SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
    SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
    SYS-CON Events announced today that WineSOFT will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Based in Seoul and Irvine, WineSOFT is an innovative software house focusing on internet infrastructure solutions. The venture started as a bootstrap start-up in 2010 by focusing on making the internet faster and more powerful. WineSOFT’s knowledge is based on the expertise of TCP/IP, VPN, SS...
    SYS-CON Events announced today that Akvelon will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Akvelon is a business and technology consulting firm that specializes in applying cutting-edge technology to problems in fields as diverse as mobile technology, sports technology, finance, and healthcare.
    SYS-CON Events announced today that TechTarget has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TechTarget storage websites are the best online information resource for news, tips and expert advice for the storage, backup and disaster recovery markets.
    Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
    SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we've...
    DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real r...
    No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, will present a step-by-step plan to develop your technology implementation strategy. He will discuss the evaluation of communication standards and IoT messaging protocols, dat...
    SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
    Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
    SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).