Whose Online in ASP.NET 2.0


Some time requirement could be like, client do not want more than one person to logged in to the system with the same name, different people suggest different solutions and all the solutions work fine till the user is loging to the system and logged out to the system, but if user closed browser without loging out from the system. In such case user has to wait for the Session to expire.

I have given thougth so many time, and here I am with simple solution.

I have simple table called as Tbl_Users with following fields.

UId  int Primary key,
LoginName varchar(50),
LoginPassword varchar(50)

I am using C# Collection ie. HashTable. By using static hashtable if user is logging to the system very first time then I am adding users key value pair to the hashtable and while logging to the system I check programmatically that similar entry is available in the hashtable and prompt user with the message. I also allow user to kill users session explicitly, or let user to wait till the session expires.

To achive this functionality I used of seal class which is as below

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Collections;

/// <summary>

/// Summary description for WhoseHandler

/// </summary>

public sealed class WhoseHandler

{

    public static Hashtable objUser = new Hashtable();

    /**

     * Function to check if user is already inn, else will add into the

     * Whose online list

     **/

    public static int WhoseInn(int userId, string strUser)

    {

        int retVal = 0;

        if (!(objUser.Contains(userId)))

        {

            objUser.Add(userId, strUser);

            return retVal;

        }

        else

        {

            retVal = 1;

        }

        return retVal;

    }

    /**

     * List All the users who are online

     **/

    public static void WhoseOnline()

    {

        IDictionaryEnumerator whosOln = objUser.GetEnumerator();

        while (whosOln.MoveNext())

        {

            HttpContext.Current.Response.Write(whosOln.Value + "<br>");

        }

    }

    /**

     * Remove user explicitly from the list

     **/

    public static void RemoveUser(int userId)

    {

        if (objUser.Contains(userId))

        {

            objUser.Remove(userId);

        }

    }

}

I am attaching entire code zip with the article.

Enjoy easy coding!

Up Next
    Ebook Download
    View all
    Learn
    View all