Nothing new here, just refactored to some new syntax. We have a large number of users that expect our web application to work like a desktop application. Our marketing/sales department makes not effort to differentiate our desktop product from our web product. So we need a way to keep a user's session alive as long as they remain in the app. One option is to set session timeouts to an outrageously large number like 600 minutes. The problem here is that when users navigate away from the site, any data stored in session will continue to persist unnecessarily. The goal is to maintain a short session timeout, but still keep the session alive for idle users. So we start with a nice simple controller that will tickle the session:
namespace My.App
{
using Castle.MonoRail.Framework;
[Serializable]
public class SessionSaverController : Controller
{
public void Index()
{
Session["KEEP_ALIVE"] = DateTime.Now;
CancelLayout();
CancelView();
}
}
}
Now we need the client to periodically call this method before their session times out. jQuery (and other frameworks like Prototpye) make this painfully simple. Consider the script below:
$(document).ready(function()
{
setTimeout($.myApp.sessionSaver, $.myApp.sessionSaverInterval);
});
(function($)
{
$.myApp =
{
sessionSaverUrl: '/sessionSaver/index.rails',
sessionSaverInterval: (60000 * 5),
sessionSaver: function()
{
$.post($.myApp.sessionSaverUrl);
setTimeout($.myApp.sessionSaver, $.myApp.sessionSaverInterval);
}
};
})(jQuery);
Obviously this script relies on jQuery to do the dirty work of an AJAX request. You could roll all this code yourself but jQuery offers a number of additional benefits so I strongly recommend picking a framework and enjoying it. We use the built in setTimeout to call our sessionSaver() function every five minutes. With a standard session timeout of 20 minutes this should be more than adequate to ensure a session does not timeout prematurely. The only thing to note is the use of the jQuery $.post() AJAX method rather than a traditional $.get(). Internet Explorer has a nasty habit of adhering to some W3C/RFC spec that says GET requests can/should be cached. So if you issue your AJAX request with a GET there is a good chance it will be cached and subsequent requests will not make it to the server causing you much wailing and gnashing of teeth when your sessions are not extended.
posted @ Monday, November 26, 2007 9:42 AM