17 octobre 2007

Concurrent access in ASP.NET

I want to know how many people are connected on my Web application
A user is in a group and we want to know if there is a user of the group who's inthe Site. But, it's possible to have 2 guys who use the same account. So i found this solution, with the Session and the Application in DotNet 2.0.

int ConnectedCount = 0;
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{

//Dynamic string if you have more than 1 group of users
string HashTableName = "NameOfMyHashtable"
if (System.Web.HttpContext.Current.Session != null)
{

//Create new Hashtable if null:
Application[HashTableName] = Application[HashTableName] ?? new Hashtable();

//region Refresh information about current User
if (((Hashtable)Application[HashTableName]).Contains

(System.Web.HttpContext.Current.Session.SessionID))
{
((Hashtable) Application[HashTableName]).Remove

(System.Web.HttpContext.Current.Session.SessionID);
}
((Hashtable) Application[HashTableName]).Add(System.Web.HttpContext.Current.Session.SessionID,
DateTime.Now.AddMinutes(System.Web.HttpContext.Current.Session.Timeout));

//region clean Hashtable
foreach (string pKeys in ((Hashtable) Application[HashTableName]).Keys)
{
if (((DateTime) ((Hashtable) Application[HashTableName])[pKeys]).CompareTo(DateTime.Now) <

connectedcount =" ((Hashtable)"> 0 )
{
lblUsersConnected.Attributes.Add("class", "fontMessageError fade");
lblUsersConnected.Text = "Attention, il y a déjà " + ConnectedCount + " utilisateur connecté";
}

}

Aucun commentaire: