473,385 Members | 1,487 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Getting All Active Web Sessions

Hi,

I am running .NET Framework 2.0 on windows XP SP2. I am stuck in a situation
where I need to find out a list of all active sessions running in IIS for a
web application.

I know that .NET 2.0 has introduced a new class that facilitate this task
very easily, somehow couldnt recall its name.

Any help would be highly appreciated.
Thanks
Atul
Aug 21 '06 #1
3 3844
hi atul,
you can get the number of active sessions via the performance monitoring
component of windows.
however if you want to track data in the sessions, that you are restricted
to .Net as far as i am aware. i haven't heard of a built-in method to list
active sessions and usernames etc in .Net 2.0.

i've included below the code i use to track user sessions. it's quite
simple, my only requirement is to record who is online, and when they last
accessed a page. I use the Cache object to track sessions because it has
built-in expiry functionality which is needed in cases where the user closes
the browser (instead of clicking 'log-out) and the session won't expire
until the time-out occurs, at which time you no longer have access to the
data in the session, so you can't track who the session belonged to. the
Cache takes care of removing entries automatically after a specified idle
period.

global.asax:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// update the 'CurrentUser' cached entry for this user
if(Context.User != null && Context.User.Identity != null &&
Context.User.Identity.IsAuthenticated)
{
string key = String.Format("Cache_{0}", Context.User.Identity.Name);
Context.Cache.Remove(key); // just in case it's there already, cache
allows duplicate names
Context.Cache.Add(key, new ObjectPair(User.Identity.Name,
DateTime.Now.ToString("HH:mm:ss")), null, DateTime.Now.AddMinutes(15),
Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
}


Logout.aspx:
private void Page_Load(object sender, System.EventArgs e)
{
string key = String.Format("Cache_{0}", User.Identity.Name);
Context.Cache.Remove(key); // remove from active users list

Active_Users_List.aspx:
private void Page_Load(object sender, System.EventArgs e)
{
this.DataGrid1.DataSource = ActiveUsers;
this.DataGrid1.DataBind();
}

/// <summary>
/// Returns an array of Pair objects, containing the username (First) and
the last access time (Second)
/// </summary>
public static ArrayList ActiveUsers
{
get
{
ArrayList activeUsers = new ArrayList();
IDictionaryEnumerator CacheEnum =
HttpContext.Current.Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
if(CacheEnum.Current is DictionaryEntry)
{
DictionaryEntry de = (DictionaryEntry)CacheEnum.Current;
if(de.Key.ToString().StartsWith("Cache_"))
{
// the value stores the username and the last access time in a Pair
object
activeUsers.Add(de.Value as ObjectPair);
}
}
}
return activeUsers;
}
}
Last but not least, the ObjectPair class to store the Username/AcessTime
values. there is one in the framework already but it can't be used in a
GridView because it doesn't have properties, only public members. You could
probably use a DictionaryList instead but i vaguely recall some limitations
there.

/// <summary>
/// A class to store a pair of objects. There is a class in System.Web.UI
but this class has fields
/// and not properties, which are necessary for using with a gridview.
/// </summary>
public class ObjectPair
{
private object pFirst, pSecond;

public ObjectPair(object f, object s)
{
this.pFirst = f;
this.pSecond = s;
}
public object First
{
get { return pFirst; }
set { pFirst = value; }
}
public object Second
{
get { return pSecond; }
set { pSecond = value; }
}
}

hope this helps
tim
Aug 21 '06 #2
Hi Tim,

Your solution is excellent. It has just one limitation, as you said, if user closes browser simply by clicking "X" or "ALT+F4". In this case, Cache expiration will expire it based on the expiration time, not immediate. I have another suggestion, think about it and tell me if it is ok.
In case if user closes its browser by clicking any of the two ways as I mentioned above, having a javascript code on browser window event Window.Close(). Is it possible to send any message from JavaScript code to Cache object to remove the Key object immediately? I thought of using AJAX here. Is it gonna be helpful?

Anything clicking in your mind.

Regards,
Atul
"Tim_Mac" <ti********@community.nospamwrote in message news:%2******************@TK2MSFTNGP03.phx.gbl...
hi atul,
you can get the number of active sessions via the performance monitoring
component of windows.
however if you want to track data in the sessions, that you are restricted
to .Net as far as i am aware. i haven't heard of a built-in method to list
active sessions and usernames etc in .Net 2.0.

i've included below the code i use to track user sessions. it's quite
simple, my only requirement is to record who is online, and when they last
accessed a page. I use the Cache object to track sessions because it has
built-in expiry functionality which is needed in cases where the user closes
the browser (instead of clicking 'log-out) and the session won't expire
until the time-out occurs, at which time you no longer have access to the
data in the session, so you can't track who the session belonged to. the
Cache takes care of removing entries automatically after a specified idle
period.

global.asax:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// update the 'CurrentUser' cached entry for this user
if(Context.User != null && Context.User.Identity != null &&
Context.User.Identity.IsAuthenticated)
{
string key = String.Format("Cache_{0}", Context.User.Identity.Name);
Context.Cache.Remove(key); // just in case it's there already, cache
allows duplicate names
Context.Cache.Add(key, new ObjectPair(User.Identity.Name,
DateTime.Now.ToString("HH:mm:ss")), null, DateTime.Now.AddMinutes(15),
Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
}


Logout.aspx:
private void Page_Load(object sender, System.EventArgs e)
{
string key = String.Format("Cache_{0}", User.Identity.Name);
Context.Cache.Remove(key); // remove from active users list

Active_Users_List.aspx:
private void Page_Load(object sender, System.EventArgs e)
{
this.DataGrid1.DataSource = ActiveUsers;
this.DataGrid1.DataBind();
}

/// <summary>
/// Returns an array of Pair objects, containing the username (First) and
the last access time (Second)
/// </summary>
public static ArrayList ActiveUsers
{
get
{
ArrayList activeUsers = new ArrayList();
IDictionaryEnumerator CacheEnum =
HttpContext.Current.Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
if(CacheEnum.Current is DictionaryEntry)
{
DictionaryEntry de = (DictionaryEntry)CacheEnum.Current;
if(de.Key.ToString().StartsWith("Cache_"))
{
// the value stores the username and the last access time in a Pair
object
activeUsers.Add(de.Value as ObjectPair);
}
}
}
return activeUsers;
}
}
Last but not least, the ObjectPair class to store the Username/AcessTime
values. there is one in the framework already but it can't be used in a
GridView because it doesn't have properties, only public members. You could
probably use a DictionaryList instead but i vaguely recall some limitations
there.

/// <summary>
/// A class to store a pair of objects. There is a class in System.Web.UI
but this class has fields
/// and not properties, which are necessary for using with a gridview.
/// </summary>
public class ObjectPair
{
private object pFirst, pSecond;

public ObjectPair(object f, object s)
{
this.pFirst = f;
this.pSecond = s;
}
public object First
{
get { return pFirst; }
set { pFirst = value; }
}
public object Second
{
get { return pSecond; }
set { pSecond = value; }
}
}

hope this helps
tim

Aug 22 '06 #3
hi Atul,
i didn't try and cater for all the variations, because they are very difficult to track:

- user closes the browser window via 'X' button in top right corner (javascript can catch this as you point out)
- user navigates to a different web site (window.onbeforeunload can catch this but IE / Firefox only)
- browser crashes / end-task (can't catch this)
- windows shut-down = kill browser (can't catch this, i think)
- user stays on the same page for 30 minutes, you don't know if they are still there or not (unless you have some javascript timer)

if you were to cater for all these situations, in my opinion the result would be a lot of messy, incompatible, and possibly intrusive javascript code, that still isn't going to cover all the scenarios. be my guest if you want to go to all this trouble! the cache/request-based approach covers everything, albeit to the lowest common denominator of "inactivity".

i like javascript but i keep it to an absolute minimum where possible.
tim
Aug 22 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Chris Hayes | last post by:
Is it possible to iterate through all the active sessions of an ASP.net application? I have this fancy user object (with all kinds of properties) that I set as a session level object on session...
2
by: Marcio Kleemann | last post by:
Is there a way to get a list of the session id's for all currently active sessions for the application? Thanks
7
by: Christina N | last post by:
I want to output a list of all active SessionID's and their last time of activity. Can I loop through the active sessions and create a list like that? I use ASP.Net (VB.Net) Best regards,...
2
by: Lenn | last post by:
Hello, This requirement might seem strange to someone out there, but here it's We need to make sure only certain number of users can be logged in the site at the same time. Is there any way to...
2
by: Cesar Ronchese | last post by:
Hello, I'm experiencing a very weird problem. I have a ASP.Net 2005 application (VB.Net) that creates some folders to store temporary files. example: Session_Start(...)...
9
by: Laurent Bugnion | last post by:
Hi, I am wondering what is the best way to find out which ASP.NET sessions are still active. Here is the reason: I have a custom control which can upload files. It saves the files in a folder...
2
by: JoeSep | last post by:
Hello, I know that when the SessionState is set to SQL Server (ASP.NET 1.1) these counters in PerfMon are not valued: - Sessions Abandoned - Sessions Active - Sessions Timed Out - Sessions...
2
by: Krish........... | last post by:
Hi all, How to find out no of active sessions (at a time) in the web server.. I dont think handling Session_start and Session_end events are useful for this. Is there any way to find all current...
6
by: bill | last post by:
I have been "Googling" for about an hour and am turning up squat! I just started receiving this error when trying to log into a MS Access database from a vb .net web application. Recycling IIS...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.