Using this code block, you can prevent simultaneous logins by a single User ID.
In order to use this code, you need to have your customized session based authentication method, which means that in your login method, you need to fetch the user from your storage (database, XML ...) and create a user object and put it in the Session. After that, the following code block should be used:
Hashtable sessions = (Hashtable)Application["WEB_SESSIONS_OBJECT"];
Your login method will look like this:
void yourLoginMethod(string userID, string password)
{
Hashtable sessions = (Hashtable)Application["WEB_SESSIONS_OBJECT"];
if (sessions == null)
{
sessions = new Hashtable();
}
HttpSessionState existingUserSession =
(HttpSessionState)sessions[userID]; if (existingUserSession != null)
{
existingUserSession[WebKeys.USEROBJECT] = null;
}
Session[WebKeys.USEROBJECT] = user;
sessions[user.UserName] = Session;
Application.Lock();
Application["WEB_SESSIONS_OBJECT"] = sessions;
Application.UnLock();
}
Your logout method will look like this:
void yourLogoutMethod(string userID)
{
Hashtable sessions = (Hashtable)Application["WEB_SESSIONS_OBJECT"];
if (sessions == null)
{
sessions = new Hashtable();
}
Session.Abandon();
sessions.Remove(userID);
Application.Lock();
Application["WEB_SESSIONS_OBJECT"] = sessions;
Application.UnLock();
}
I hold a BS degree in software engineering and am a Microsoft Certified Solution Developer(MCSD).
I have more than 8 years of experience in .NET developement, mostly web develop using C# and ASP.NET.