How to prevent AJAX polling keeping Asp.Net sessions alive - ajax

We have a ASP.Net application that has been given a 20 minute sliding expiry for the session (and cookie).
However, we have some AJAX that is polling the server for new information. The downside of this of course is that the session will continue indefinitely, as it is being kept alive by the polling calls causing the expiry time to be refreshed. Is there a way of preventing this - i.e. to only allow the session to be refreshed on non-ajax calls?
Turning off sliding expiry is not really an option as this is an application that business users will be using for most of their day between telephone calls.
Other Stackoverflow discussions on this talk about maintaining 2 separate application (one for authenticated calls, one for unauthenticated. I'm not sure this will be an option as all calls need to be authenticated.
Any ideas?

As this question is old I am assuming it has been resolved or a workaround implemented. However, I wanted to mention that instead of AJAX polling the server to perform an operation we have utilized SignalR which allows both the client to communicate with the server via JQuery and/or the server to notify the client.
Check it out: Learn About ASP.NET SignalR

add below code to your controller action that you are reference for polling.Convert this into an attribute so it can be used everywhere. This line will not extend session timeout
[HttpPost]
public ActionResult Run()
{
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
return Json("");
}

There is no way to stop the ajax from keeping the session and cookies alive!
However, there is a way to achieve what you want to do. That is if the process I will describe will be ok to you.
I think what you really want to achieve is first to refresh your page with ajax so that some processes will be active and running. Also to know when the user has stopped operating the program.
If that is what you want then there is a simple process to achieve this
You will have your ajax running for the things you want to run.
You will remove the session you want to check if user has stopped operation on the page and manage the session as a variable instead.
The variable can be a global variable or a class variable that will be set to initial value whenever the user clicks an element on the page.
(You will select the click event of an element and set the variable to initial value)
You will increment the variable every given time (say every time your ajax runs)
You will also have a function/method run to check the value of that variable if it is greater than the value you set as limit. This can run every time your ajax runs or every time you want it to run (timed event).
If the value of your variable is greater than the limit set it should invalidate or clear session/log user out.
This way if user stops operating (clicking elements) the system on any page that this is running will eventually log out the current user and stop running the program.

I have done this by creating a hidden page in an i-Frame. Then using JavaScript it posts back every 18 minutes to keep the session alive. This works really well.
This example is from a ASP.NET Forms project but could be tweaked for MVC.
Create a page called KeepSessionAlive page and add a meta refresh tag
meta id="MetaRefresh" http-equiv="refresh" content="21600;url=KeepSessionAlive.aspx"
In the code behind
protected string WindowStatusText = "";
protected void Page_Load(object sender, EventArgs e)
{
//string RefreshValue = Convert.ToString((Session.Timeout * 60) - 60);
string RefreshValue = Convert.ToString((Session.Timeout * 60) - 90);
// Refresh this page 60 seconds before session timeout, effectively resetting the session timeout counter.
MetaRefresh.Attributes["content"] = RefreshValue + ";url=KeepSessionAlive.aspx?q=" + DateTime.Now.Ticks;
WindowStatusText = "Last refresh " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
}
Add the hidden iFrame in a master page
iframe ID="KeepAliveFrame" src="KeepSessionAlive.aspx" frameBorder="0" width="0" height="0"
Download example

Related

how to delete a value from session with revel

Is there a way to delete the value from session witch revel the go web framework?
I have a function for validate captcha for user input, and I set the value of captcha in session, and delete the captcha from session if there nothing to do for client after 1 minute. The code is like:
time.AfterFunc(time.Minute, func() {
delete(this.Session, CSecurityCode)
})
But I can still get the old value of captcha , why, and how to fix this?
Anybody who can help me?
The Session value is valid only while processing a client request. i.e. between the time you get the request and the time you respond to that request. Its contents are kept in a cookie on the client side and you'll get a new Session every time the client connects to your server. Thus if you keep it for later use (like the name of your AfterFunc suggests, triggered by a timer?), anything you do with it will be lost on the next client connection.
In order to achieve what you want to do, you'll need to add a "lastSeen" timestamp to the Session. When a request comes in, check Session["lastSeen"], and if it's older than 1 minute, then you can discard CSecurityCode from it.

Classic ASP and session Timeouts - keeping track of the session timer?

I've been stuck on this problem all week and I'm more than annoyed at the fact that I have to fix this application to meet the security policies the company I work for has... anyways...
I am trying to keep track of a session in a Classic ASP web app. I am able to set the session.timeout as well as a session variable in the session_onstart sub of my gobal.asa file. It works just fine:
Sub Session_OnStart
Session("LoggedOn") = true
Session.Timeout = 5
End Sub
Next, on one page (to test out a solution to this problem), I have implemented akiller's solution from here.
I needed to modify the code to look like this:
session.asp
<%
Response.ContentType = "application/json"
If Session("LoggedOn") = true Then
Response.Write "{""loggedOn"": true}"
Else
Response.Write "{""loggedOn"": false}"
End If
%>
and:
<script type="text/javascript">
$(document).ready(function () {
var checkLoggedOn = function () {
$.getJSON('session.asp', function (data) {
if (data.loggedOn = false){
alert(data.loggedOn);
//Need to get alert working when session time expires before redirect can be used.
//window.location.replace("http://stackoverflow.com");
}
});
};
// Call checkLoggedOn every x milliseconds
setInterval(checkLoggedOn, 30000);
});
</script>
Now, what I need to do is find out how to check how much time is left before the session expires. While I can use Javascript code to run a checker like the one above client-side, the time left in the session MUST be checked from the server (to prevent hacking of sessions client-side).
So here's the final steps of what I'm trying to accomplish.
Trigger a Session.Abandon when session expires (server-side)
Set Session("LoggedOn") to false in the Session_OnEnd event in global.asa
session.asp will return false as a result
redirect the user where they need to go.
Thanks,
Nick
Short answer: see this comment by Lankymart.
More detailed answer: you can't do what you want.
Each time when you a request page when current session is alive, ASP will automatically prolong session lifetime on timeout value assigned in this page. In this case, session will live until IIS is restarted.
Setting any values to Session collection in Session_OnEnd is meaningless: after this event completes, ASP will destroy all Session collection object and remove SessionID from ASP process.
Remember, that calling Session.Abandon doesn't call event Session_OnEnd immediately: see MSDN http://msdn.microsoft.com/en-us/library/ms524310(v=vs.90).aspx
Ultimately, it was decided that it wasn't worth upgrading this project and we're going to keep it on a domain that can only be accessed internally so security fixes are not required.

Jquery async calls block page reload

I have a function that performs a backup every 5 seconds. From time to time the target server of the backup is not reachable and the request stops until the timeout is reached.
Since this affects the user interface I execute this 'backup function' as a async ajax request.
setInterval("doSync()", 5000 );
function doSync() {
$.ajax({
url: "backup.php",
async : true
});
};
This runs pretty good in the background.
But as soon as a reload of the page is executed, already waiting backup function calls will be completed. So in the worst case, if I have a backup with 30 seconds timeout, the user has to wait this 30 seconds before the new page is loaded.
That is not acceptable for the user.
Which strategy can I implement to avoid this?
It would be ok to terminate the backup request...
I think that issue is rather specific to the browser.
Indeed, most of them limit the number of parallel requests to the same host and that's why it "waits" before reloading the page.
If you're calling the exact same URL via your AJAX request as the one you're trying to reload, Firefox will not run more than ONE request at the same time. A simple workaround is to append a random query string to the URL.
Another option is to use the javascript beforeunload event to cancel your AJAX request : Abort Ajax requests using jQuery
I would maybe think about setting timeout in your case.
I also found similar problem already solved: click

Long Running Wicket Ajax Request

I occasionally have some long running AJAX requests in my Wicket application. When this occurs the application is largely unusable as subsequent AJAX requests are queued up to process synchronously after the current request. I would like the request to terminate after a period of time regardless of whether or not a response has been returned (I have a user requirement that if this occurs we should present the user an error message and continue). This presents two questions:
Is there any way to specify a
timeout that's specific to an AJAX
or all AJAX request(s)?
If not, is there any way to kill the current request?
I've looked through the wicket-ajax.js file and I don't see any mention of a request timeout whatsoever.
I've even gone so far as to try re-loading the page after some timeout on the client side, but unfortunately the server is still busy processing the original AJAX request and does not return until the AJAX request has finished processing.
Thanks!
I think it won't help you to let the client 'cancel' the request. (However this could work.)
The point is that the server is busy processing a request that is not required anymore. If you want to timeout such operations you had to implement the timeout on the server side. If the operation takes too long, then the server aborts it and returns some error value as the result of the Ajax request.
Regarding your queuing problem: You may consider to use asynchronous requests in spite of synchronous ones. This means that the client first sends a request for starting the long running process. This request immediately returns. Then the client periodically polls the server and asks if the process has finished. Those poll requests also return immediately saying either that the process is still running or that it has finished with a certain result.
Failed solution: After a given setTimeout I kill the active transports and restart the channel, which handles everything on the client side. I avoided request conflicts by tying each to an ID and checking that against a global reference that increments each time a request is made and each time a request completes.
function longRunningCallCheck(refId) {
// make sure the reference id matches the global id.
// this indicates that we are still processing the
// long running ajax call.
if(refId == id){
// perform client processing here
// kill all active transport layers
var t = Wicket.Ajax.transports;
for (var i = 0; i < t.length; ++i) {
if (t[i].readyState != 0) {
t[i].onreadystatechange = Wicket.emptyFunction;
t[i].abort();
}
}
// process the default channel
Wicket.channelManager.done('0|s');
}
}
Unfortunately, this still left the PageMap blocked and any subsequent calls wait for the request to complete on the server side.
My solution at this point is to instead provide the user an option to logout using a BookmarkablePageLink (which instantiates a new page, thus not having contention on the PageMap). Definitely not optimal.
Any better solutions are more than welcome, but this is the best one I could come up with.

How to Track the Online Status of Users of my WebSite?

I want to track users that are online at the moment.
The definition of being online is when they are on the index page of the website which
has the chat function.
So far, all I can think of is setting a cookie for the user and, when the cookie is found on the next visit, an ajax call is made to update a table with their username, their status online and the time.
Now my actual question is, how can I reliably turn their status to off when they leave
the website? The only thing I can think of is to set a predetermined amount of time of no user interaction and then set the status to off.
But what I really want is to keep the status on as long as they are on the site, with or without interaction, and only go to off when they leave the site.
Full Solution. Start-to-finish.
If you only want this working on the index.php page, you could send updates to the server asynchronously (AJAX-style) alerting the server that $_SESSION["userid"] is still online.
setInterval("update()", 10000); // Update every 10 seconds
function update() {
$.post("update.php"); // Sends request to update.php
}
Your update.php file would have a bit of code like this:
session_start();
if ($_SESSION["userid"])
updateUserStatus($_SESSION["userid"]);
This all assumes that you store your userid as a session-variable when users login to your website. The updateUserStatus() function is just a simple query, like the following:
UPDATE users
SET lastActiveTime = NOW()
WHERE userid = $userid
So that takes care of your storage. Now to retrieve the list of users who are "online." For this, you'll want another jQuery-call, and another setInterval() call:
setInterval("getList()", 10000) // Get users-online every 10 seconds
function getList() {
$.post("getList.php", function(list) {
$("listBox").html(list);
});
}
This function requests a bit of HTML form the server every 10 seconds. The getList.php page would look like this:
session_start();
if (!$_SESSION["userid"])
die; // Don't give the list to anybody not logged in
$users = getOnlineUsers(); /* Gets all users with lastActiveTime within the
last 1 minute */
$output = "<ul>";
foreach ($users as $user) {
$output .= "<li>".$user["userName"]."</li>";
}
$output .= "</ul>";
print $output;
That would output the following HTML:
<ul>
<li>Jonathan Sampson</li>
<li>Paolo Bergantino</li>
<li>John Skeet</li>
</ul>
That list is included in your jQuery variable named "list." Look back up into our last jQuery block and you'll see it there.
jQuery will take this list, and place it within a div having the classname of "listBox."
<div class="listBox"></div>
Hope this gets you going.
In the general case, there's no way to know when a user leaves your page.
But you can do things behind the scenes such that they load something from your server frequently while they're on the page, eg. by loading an <iframe> with some content that reloads every minute:
<meta http-equiv="refresh" content="60">
That will cause some small extra server load, but it will do what you want (if not to the second).
Well, how does the chat function work? Is it an ajax-based chat system?
Ajax-based chat systems work by the clients consistently hitting the chat server to see if there are any new messages in queue. If this is the case, you can update the user's online status either in a cookie or a PHP Session (assuming you are using PHP, of course). Then you can set the online timeout to be something slightly longer than the update frequency.
That is, if your chat system typically requests new messages from the server every 5 seconds, then you can assume that any user who hasn't sent a request for 10-15 seconds is no longer on the chat page.
If you are not using an ajax-based chat system (maybe Java or something), then you can still accomplish the same thing by adding an ajax request that goes out to the server periodically to establish whether or not the user is online.
I would not suggest storing this online status information in a database. Querying the database every couple of seconds to see who is online and who isn't is very resource intensive, especially if this is a large site. You should cache this information and operate on the cache (very fast) vs. the database (very slow by comparison).
The question is tagged as "jquery" - what about a javascript solution? Instead of meta/refresh you could use window.setInterval(), perform an ajax-request and provide something "useful" like e.g. an updated "who's online" list (if you consider that useful ;-))
I have not tried this, so take it with a grain of salt: Set an event handler for window.onunload that notifies the server when the user leaves the page. Some problems with this are 1.) the event won't fire if the browser or computer crashes, and 2.) if the user has two instances of the index page open and closes one, they will appear to logout unless you implement reference counting. On its own this is not robust, but combined with Jonathan's polling method, should allow you to have pretty good response time and larger intervals between updates.
The ultimate solution would be implementing something with websockets.

Resources