Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET

Retrieve All Active Sessions Data

Rate me:
Please Sign up or sign in to vote.
1.67/5 (6 votes)
31 May 2009CPOL2 min read 71.5K   1.2K   11   10
Helps to view all the active Session IDs, Session Keys, and Session Values in an ASP.NET application.

Introduction

As far as I know, in ASP.NET, we do not have a predefined class library to find out all the active session IDs and their data. This article helps you list all the active session keys using a simple logic.

Background

This code can be used to track the active sessions of an application.

Using the code

This simple application has two pages: one to view the data (Manager.aspx) and the other to enter the current date time into the session.

In the application, create a variable of type Dictionary<string, HttpSessionState> and store it into the application memory. It facilitates us to keep the “Session IDs” of all the sessions and a “Session” object reference.

C#
protected void Application_Start(object sender, EventArgs e)
{
    Dictionary<string, HttpSessionState> sessionData = 
               new Dictionary<string, HttpSessionState>();
    Application["s"] = sessionData;
}

Once we are ready with the object structure, we need to add and remove Session IDs and Session objects in the Session_Start and Session_End events, respectively. By default, ASP.NET reuses Session IDs, so we cross-check every time we add a Session ID reference.

C#
//Sesssion Start Event
protected void Session_Start(object sender, EventArgs e)
{
    Dictionary<string, HttpSessionState> sessionData = 
      (Dictionary<string, HttpSessionState>)Application["s"];

    if (sessionData.Keys.Contains(HttpContext.Current.Session.SessionID))
    {
        sessionData.Remove(HttpContext.Current.Session.SessionID);
        sessionData.Add(HttpContext.Current.Session.SessionID, 
                        HttpContext.Current.Session);
    }
    else
    {
        sessionData.Add(HttpContext.Current.Session.SessionID, 
                        HttpContext.Current.Session);
    }
    Application["s"] = sessionData;
}

//Session End Event
protected void Session_End(object sender, EventArgs e)
{
    Dictionary<string, HttpSessionState> sessionData = 
       (Dictionary<string, HttpSessionState>)Application["s"];
    sessionData.Remove(HttpContext.Current.Session.SessionID);
    Application["s"] = sessionData;
}

We are done with our Global.asax.cs page coding; the next part is we need an interface to store some dummy values in to the Session and a page to monitor all the application objects. For this, we use a very simple code in the Default.aspx page to keep the session values.

Apart from this, the Manager.aspx.cs page contains code to see all session data. This page contains an AJAX timer control and uses a GridView to display data. It refreshes every 10 seconds.

C#
//Filling Session Value from Deafult.aspx.cs
protected void button1_Click(object sender, EventArgs e)
{
    HttpContext.Current.Session[Guid.NewGuid().ToString()] = 
                                DateTime.Now.ToString();
}        
            
//Grid Binding For every ten Seconds using Updatepanel
protected void Timer1_Tick(object sender, EventArgs e)
{
    try
    {
        List<SessionData> gv = new List<SessionData>();
        Dictionary<string, HttpSessionState> sessionData = 
          (Dictionary<string, HttpSessionState>)Application["s"];

        if (sessionData != null)
        {
            foreach (KeyValuePair<string, HttpSessionState> item in sessionData)
            {
                gv.Add(new SessionData() { SessionId=item.Key, SessionKey =null, 
                                           SessionValue = null }); 
                if (item.Value != null && item.Value.Count > 0)
                {
                    foreach (string key in item.Value.Keys)
                    {
                        gv.Add(new SessionData() {SessionId=item.Key, SessionKey = key, 
                           SessionValue = item.Value[key] != null ? 
                           item.Value[key].ToString() : string.Empty });
                    }
                } 
            }
            sessionValuesGrid.DataSource = gv;
            sessionValuesGrid.DataBind();
        }
    }
    catch { }
}

Apart from this, we can use "Session.IsNewSession" to detect whether a Session is new or an existing one. We have one another hard and robust technique as well, which is using HttpModules.

Points of interest

Using this kind of logic in production environment is very difficult. If Microsoft provides an alternative, that would be really helpful in tracking expiring sessions easily.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect N/A
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
babak ravandi1-Jul-09 5:20
babak ravandi1-Jul-09 5:20 
GeneralMy vote of 1 Pin
Kamran Shahid18-Jun-09 0:53
Kamran Shahid18-Jun-09 0:53 
GeneralRe: My vote of 1 Pin
gofal28-Feb-11 23:24
gofal28-Feb-11 23:24 
GeneralMy vote of 1 Pin
zlezj1-Jun-09 5:48
zlezj1-Jun-09 5:48 
QuestionWhy duplicate all this session information? Pin
kalyankrishna131-May-09 19:55
kalyankrishna131-May-09 19:55 
AnswerRe: Why duplicate all this session information? Pin
nmreddy831-Jun-09 3:02
nmreddy831-Jun-09 3:02 
GeneralNot thread safe Pin
Michael Teper31-May-09 13:57
Michael Teper31-May-09 13:57 
GeneralRe: Not thread safe Pin
nmreddy8331-May-09 18:54
nmreddy8331-May-09 18:54 
GeneralMy vote of 1 Pin
Rogic31-May-09 7:41
Rogic31-May-09 7:41 
GeneralRe: My vote of 1 Pin
nmreddy8331-May-09 8:12
nmreddy8331-May-09 8:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.