I have implemented a solution for the my question. I need your help in identifying the problem if any when multiple threads are trying to access the content at a time. Before asking the question i have researched for similar question i found this link when-the-same-user-id-is-trying-to-log-in-on-multiple-devices-how-do-i-kill-the
but the implementation is slightly different from my code. Please have a look at my code. In Login page I have written following code in the login button click.
protected void btnSignIn_Click(object sender, EventArgs e)
{
string email = tbEmail.Value.ToLower();
string pwd = tbPwd.Value;
bool isUserSessionExists = false;
List<string> lstLoggedInUsers = null;
/* */
//lstLoggedInUsers.Add(email);//for detecting if user is logged in from any machine or not.
BAL.UserDetails oUserDetails = new BAL.UserDetails();
BO.User oUser = oUserDetails.IsAValidUser(email, pwd);
if (oUser != null)
{
if (Application["loggedInUsers"] != null)
{
lstLoggedInUsers = Application["loggedInUsers"] as List<string>;
//crntUser.SuspectedAttemps
//lstLoggedInUsers.Add(email);
foreach(var v in lstLoggedInUsers)
{
if(oUser.Email.ToLower()==v.ToLower())
{
isUserSessionExists = true;
break;
}
}
}
if (!isUserSessionExists)
{
Session["user"] = oUser;
//add authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
oUser.Lastname, DateTime.Now, DateTime.Now.AddMinutes(60), true, oUser.FirstName);
//FormsAuthentication.SetAuthCookie(oUser.Lastname, true); uncomment this when you want to createpersistent cookie
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); // Hashed ticket
// Add the cookie to the response, user browser
lock (lstLoggedInUsers)
{
lstLoggedInUsers.Add(oUser.Email);
}
Response.Cookies.Add(cookie);
Response.Redirect("~/campus/training-room.aspx");
}
else
{
//this condition will execute when a duplicate user is //trying to access the app with same emailid
//and pwd as an existing user.
errmsg2.InnerHtml = "duplicate login error";
}
}
else
{
errmsg2.InnerText = "some error here";
}
}
In My Global.asax i have written following code.
void Session_End(object sender, EventArgs e)
{
BO.User oUser = Session["user"] as BO.User;
if (oUser != null)
{
List<string> lstCurrentLoggedInUsers = Application["loggedInUsers"] as List<string>;
lock (lstCurrentLoggedInUsers)
{
foreach (var v in lstCurrentLoggedInUsers)
{
if (v.ToLower() == oUser.Email.ToLower())
{
lstCurrentLoggedInUsers.Remove(v);
break;
}
}
}
}
}
void Application_Start(object sender, EventArgs e)
{
if(Application["loggedInUsers"]==null)
{
Application["loggedInUsers"] = new List<string>();
}
}
Note: My application is about to go live. I tested this code by simulating different user concurrent requests by opening 3 browsers(IE/MFF/GC) in local machine. For me it is looking like everything is working fine. But still i need your valuable review.