ASP.NET, Coding

Display Online Users

There is an inbuilt support for getting user status in NET 2.0 using Memebership Namespace.

You can get the list of online users by looping through the MembershipUserCollection returned by Memeberhisp.GetAllUsers() method and checking the IsOnline property:

    MembershipUserCollection muc = Membership.GetAllUsers();
        foreach (MembershipUser mu in muc)
        {
            if (mu.IsOnline)
            {
                Response.Write(mu.UserName);
            }
        }

There is an alternate method to create a customized method to get more details. You can add a property in the Global.asax.vb/Global.asax.cs which returns a DataTable that holds the users’ information. Add this information a user logs on and remove as the user logs off:

Imports System.Data

Public Class Global
      Inherits System.Web.HttpApplication
      Private Shared _table As DataTable
      Public Shared ReadOnly Property Users() As DataTable
            Get
                  If _table Is Nothing Then
                        _table = New DataTable("Users")
                        With _table.Columns
                              .Add("UserID",GetType(Integer))
                              .Add("Logon",GetType(DateTime))
                              .Add("Active",GetType(Boolean))
                              
                              .Item(0).AllowDBNull = False
                              .Item(1).AllowDBNull = False
                              .Item(2).AllowDBNull = False
                              
                              _table.PrimaryKey = New DataColumn() { .Item(0) }
                        End With
                        
                  End If
                  
                  Return _table
            End Get
      End Property
      
End Class

Now you can add the data table or remove the entries after log on and log off:

' When User Logs In

Dim userRow As DataRow = Global.Users.Rows.Find() 
If userRow Is Nothing Then
  userRow = Global.Users.NewRow()
  userRow("UserID") = 
End If

userRow("Logon") = Now
userRow("Active") = True

If userRow.RowState = DataRowState.Detached Then
  Global.Users.Rows.Add(userRow)
End If

Global.Users.AcceptChanges()

'When User Logs Off

Dim userRow As DataRow = Global.Users.Rows.Find()
If Not userRow Is Nothing Then
  Global.Users.Remove(userRow)
End If

You Might Also Like