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.

    @ThingsExpo Stories
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    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 ...
    Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
    Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
    The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
    Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
    Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
    Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
    As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
    Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
    DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
    DXWorldEXPO | CloudEXPO 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.
    The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
    DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. 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 bus...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. 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 ov...
    DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
    DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
    With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...