| By Christian Schneider | Article Rating: |
|
| July 26, 2000 12:00 AM EDT | Reads: |
9,885 |
During a recent intranet project, I encountered the need for live reports of all currently open user sessions within an application.
The goal was for me to be able to see how many users were currently online with an open session when rolling out new templates from the development server to the production server. That way I would be able to determine whether it was a good idea to update the live production server or if it would be better to wait until the late evening (of course, I'd probably need to call the local pizza service, instead of having a nice dinner with my girlfriend). It would put an end to the numerous nights behind the PC if I could develop some kind of a live-session monitor that enabled me to see how many users were currently online with running sessions.
Overview of Sessions
Sessions are frequently used by ColdFusion developers to track a certain state of a connection over multiple pages. Since HTTP is by nature a stateless protocol, meaning it has no built-in mechanisms to track a session over multiple pages (instead, each page request opens a new connection to the host), the guys from Allaire opted to use cookies and issue unique IDs to each client and incorporate this into the popular session framework. That way developers can simply set any variable in one template into the session scope: <cfset SESSION.userName = "John"> and access them in another template called by the client afterwards. This session framework, as part of the CF Web application framework, is activated within the Application.cfm file by using the following statement:
<cfapplication name="My_Test_App"
clientmanagement="yes" sessionmanagement="yes"
sessiontimeout=#CreateTimespan(0,0,20,0)#>
This statement sets the default timeout of a session to 20 minutes by using the CreateTimespan() function. It means that after 20 minutes of inactivity the client's session is closed. When returning to the application, this timeout-event should be caught and the user sent back to the login page. Setting a session timeout is mainly used for security reasons; it's also used on large-scale sites since keeping sessions open for a long time would produce too much overhead on the server. Now I'll present a solution on how to live- monitor these sessions.
A Simple but Effective Solution
As difficult as it sounds to develop a live monitor of all open sessions, it was (to my own surprise) done quite easily with the use of ColdFusion mechanisms and techniques. All we need are three ingredients: applications-scoped variables, structures and the Application.cfm file.
Application-Scoped Variables
The variables set in the application scope, like<cfset APPLICATION.systemColor = "Blue">, are accessible (read and write) by all clients accessing the application, as opposed to session-scoped variables that are accessible (read and write) only by each client separately.
Structures
These kinds of variables are like associative Arrays, which have a set of keys in them mapped to certain values. They could be described as a bunch of key-value pairs held within one variable that are set the following way:
<cfset myStruct = StructNew()>Alternatively the last statement could be coded another way, using the ColdFusion structure functions:
<cfset dummy = StructInsert(myStruct, "color", "Blue", true)>where the last boolean parameter (here true) indicates whether or not existing keys should be overwritten. Note that CF has a very rich set of structure functions, including a mechanism of looping over structures that we'll also be using.
Application.cfm File
Our next basic ingredient is the Application.cfm file, the root for enabling the ColdFusion Web application framework. It has a useful characteristic: its content is executed before any page request within an application.
Having listed these three ingredients, I can now tell you the recipe for a live-session monitor. In brief: we need to set some kind of flag when a user is active. When we timestamp this flag we can also determine if the user's session has timed out (and is therefore no longer active). CF treats every page request within an application as an event to set the session timeout ticker back, which means it sees that the user is still active and his or her session should be kept active too. The easiest way to set the flag is to do so in the Application.cfm file, because this file is executed on every page request.
As we wish to track every user of an application, this flag should be placed into the application scope so it can hold information about all current active users. Besides (as you might already guess from my ingredients list), this flag is a structure logging every active user's timestamp with some unique part as the key and the current timestamp as its value. This unique key could be a user ID derived from the user's login or just the user's IP address (see Listing 1).
Of course, if you run a site that asks every user to log in (as most intranet applications do), taking the user's login ID here would be nice, because that way your session monitor would show you not only the IP addresses of all active users but also their actual user names. I decided to take the user's IP address as the key in Listing 1 for demonstration purposes and to keep the code snippet general so you can take it and run it on your site.
The rest is a simple reporting page that loops over the mentioned structure and checks whether each logged session is still active or has timed out, and presents the neatly formatted results. As we have the timestamp along with the user's IP address, it's also possible to set some thresholds for color-coding the report according to how long a session was inactive.
Explaining the Code
Now I've presented my idea for developing the session monitor, let's look inside the code. Basically all we need is a code snippet to place into the Application.cfm file shown in Listing 1 and a simple reporting page that presents a nicely formatted session report (see Listing 2).
First I'd like to comment the Application.cfm snippet shown in Listing 1. The first cfset statement sets a locally scoped variable, theTimeout, to a time span by using ColdFusion's CreateTime-span() function. This is necessary to define the timeout for CF's session framework activated in the next statement. You might wonder why I decided to use a locally scoped variable instead of directly using CreateTimespan() in the cfapplication tag, but as I need the timeout value in the reporting page to determine when a user's session has timed out, setting a variable and referencing it makes more sense.
The next block of code is the session monitor's heart; it's surrounded by a cflock statement because proper locking of application-scoped variables is a good style of writing code and a must to guarantee consistency between simultaneous accesses in large-scale sites. Inside the heart the session monitor generates the structure holding the tracked information (APPLICATION.SessionTracker) if it doesn't already exist. The last and most important statement:
<CFSET dummy = StructInsert(APPLICATION.SessionTracker, CGI.REMOTE_ADDR, Now(), true)>takes the user's IP address as a key and the current time as its value and inserts this into the session monitor's structure. If the key (meaning the user) already exists in the structure, it's automatically updated. This feature is made available by the boolean parameter true of StructInsert()'s parameters. As this snippet is executed on every page request, it continuously updates the structure that holds all active users and is fed into the reporting page (shown in Listing 2 and explained next).
The code in Listing 2 is just a sample reporting page that uses the session monitor's application-scoped structure holding all active users with their last activity time-stamped. It shows an HTML table listing all active users and their inactivity time. This report is color-coded according to how long a user was inactive (see Figure 1). The threshold values for coloring the report might be individualized depending on how granular you want the report to be colored (just take mine as sample values). Besides the surrounding cflock statement to guarantee consistency for simultaneous accesses and the HTML code to format the table, Listing 2 contains the following interesting code: inside the table the reporting page loops over the session monitor's structure and determines the time of each user's last activity to decide whether the user's session is still active or has timed out. This is achieved by comparing the time of the user's last activity plus the timeout value against the current time. If the user's session has timed out, the entry is removed from the session-tracker using the StructDelete() function. Otherwise the still-active session is written onto the report along with the user's inactivity time, colored according to how long he or she was inactive. That way you get a live report showing all active users (see Figure 1).
Introducing OnRequestEnd.cfm
Introduced with ColdFusion 4.01, OnRequestEnd.cfm is the counterpart of Application.cfm. As the name suggests, OnRequestEnd.cfm is executed at the end of each request, like Application.cfm at the beginning. This means you're free to decide whether you'd like to place the session monitor's heart (the block of code inside the cflocks in Listing 1) into the Application.cfm or OnRequestEnd.cfm file.
Further Ideas
Having presented my idea of a simple session monitor, I'd like to conclude with a few thoughts and enhancements based on the ability to track user sessions.
Of course, the first (and probably easiest) enhancement would be to define a more detailed report that could be sorted (by inactivity time) and filtered (by usergroups). This should be implemented easily using the handy CF functions for structure, array and list handling. I decided not to implement it here because I wanted to keep the code simple.
If your monitored application supports a defined group of users that have to log in, another straightforward enhancement would be to log by user IDs instead of IP addresses. This enables grouping based on how many users from any given department are currently online.
Using the Application.cfm file more intensively with the awareness of who is currently active, it's also possible to develop some kind of instant messaging between online users by setting an application-scoped message structure indexed by user IDs with the messages as their values. Whenever a user accesses a page of the application that has instant messaging, this queue is checked for messages for the current user.
Knowing how many users are currently active in your apps is also valuable information for licensing and security issues. For example, you can prevent applications you've sold from being used by more simultaneous online users than your customer has purchased licenses for (depending on your licensing model). Knowing how many simultaneous users are accessing your application can also be used to initiate certain mission-critical tasks whenever too many users are active, such as automatically caching queries, activating the sleeping backup server to become part of the productive cluster or just sending an e-mail warning to your system administrator to watch the servers.
These are only a few aspects of this topic. I'd be interested in any feedback and ideas you may have so I can incorporate them and make the session monitor a handy feature every application should have.
Published July 26, 2000 Reads 9,885
Copyright © 2000 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Christian Schneider
Christian Schneider is an Allaire Certified ColdFusion and Web site developer. He has over four years of intensive experience developing CF-based intranet applications for banks and logistic corporations.
![]() |
Steve Hicks 12/09/07 11:50:47 PM EST | |||
Hi, just trying to get the listings referenced in your article. Any help would be appreciated. |
||||
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Adobe Flex Developer Earns $100K in New York City
- Adobe LiveCycle Enterprise Suite 2 for Cloud Computing
- Adobe Betas Target RIAs and Cloud Computing
- Adobe Cans Another 9% of its Workforce
- Moyea DVD4Web Converter V2.0 Converts DVD to FLV Fast and Synchronously with Watermarks
- Adobe Fiddles with its Web Apps
- Adobe & Salesforce Cut Cloud Deal
- Hosting.com Launches ColdFusion 9 in the Cloud
- The Real Time Infrastructure Ultimatum
- Adobe’s Aiming ColdFusion at Multiple Clouds
- Eval JavaScript in a Global Context
- Fig Leaf Software to Exhibit at Government IT Conference & Expo
- Cloud Computing Journal: Adobe to Deliver ColdFusion in the Cloud
- Is Microsoft as Free as Open Source?
- Adobe Reader Sued
- The Planet Named “Bronze Sponsor” of Cloud Computing Expo
- Microsoft Expression Web Has Got Game
- Adobe May Cooperate with Apple to Transplant Flash Player to iPhone
- Adobe Flex Developer Earns $100K in New York City
- Bruce Chizen Joins Voyager Capital as Venture Partner
- My Top Seven Wishes From Adobe MAX 2009
- The Next Programming Models, RIAs and Composite Applications
- Where Are RIA Technologies Headed in 2008?
- Constructing an Application with Flash Forms from the Ground Up
- AJAX World RIA Conference & Expo Kicks Off in New York City
- CFEclipse: The Developer's IDE, Eclipse For ColdFusion
- Personal Branding Checklist
- Adobe Flex 2: Advanced DataGrid
- Has the Technology Bounceback Begun?
- Building a Zip Code Proximity Search with ColdFusion
- i-Technology Viewpoint: We Need Not More Frameworks, But Better Programmers
- The Asynchronous CFML Gateway
- Web Services Using ColdFusion and Apache CXF
























