Click here to Skip to main content
Click here to Skip to main content

Retrieve All Active Sessions Data

, 31 May 2009
Rate this:
Please Sign up or sign in to vote.
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.

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.

//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.

//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)

About the Author

nmreddy83
Architect N/A
India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberbabak ravandi1-Jul-09 5:20 
GeneralMy vote of 1 PinmemberKamran Shahid18-Jun-09 0:53 
GeneralRe: My vote of 1 Pinmembergofal28-Feb-11 23:24 
GeneralMy vote of 1 Pinmemberzlezj1-Jun-09 5:48 
QuestionWhy duplicate all this session information? Pinmemberkalyankrishna131-May-09 19:55 
AnswerRe: Why duplicate all this session information? Pinmembernmreddy831-Jun-09 3:02 
GeneralNot thread safe PinmemberMichael Teper31-May-09 13:57 
GeneralRe: Not thread safe Pinmembernmreddy8331-May-09 18:54 
GeneralMy vote of 1 PinmemberRogic31-May-09 7:41 
GeneralRe: My vote of 1 Pinmembernmreddy8331-May-09 8:12 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 31 May 2009
Article Copyright 2009 by nmreddy83
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid