Show ASP.NET Membership Online Users

There are several ways to show who is currently online within your ASP.NET Application if you use the build in Membership Provider. I tested a few on performance and accuary which lead me to the following conclusion:

Using a stored procedure on LastActivityDate is the winner.

Here is how I did it, create this stored procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
– =============================================
– Author: Andreas Kraus
– Create date: 2007-03-27
– Description: Who Is Online Box
– =============================================
CREATE PROCEDURE [dbo].[xx_WhoIsOnline]
@TimeWindow DATETIME
AS
BEGIN
– SET NOCOUNT ON added to prevent extra result sets from
– interfering with SELECT statements.
SET NOCOUNT ON;

— Insert statements for procedure here
SELECT UserName FROM aspnet_Users
WHERE IsAnonymous = ‘FALSE’ AND LastActivityDate > @TimeWindow
END
GO

and create a custom ASP.NET Control featuring this code:

   18         cn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);

   19 

   20         SqlCommand cmd = new SqlCommand();

   21         SqlDataReader dr;

   22 

   23         DateTime TimeWindow = DateTime.Now;

   24         TimeSpan TimeSpanWindow = new TimeSpan(0, 10, 0);

   25         TimeWindow = TimeWindow.Subtract(TimeSpanWindow);

   26 

   27         cmd.Connection = cn;

   28         cmd.CommandText = “battle_WhoIsOnline”;

   29         cmd.Parameters.AddWithValue(“@TimeWindow”, TimeWindow);       

   30         cmd.CommandType = System.Data.CommandType.StoredProcedure;

   31 

   32         cn.Open();

   33         dr = cmd.ExecuteReader();

   34 

   35         System.Text.StringBuilder sb = new System.Text.StringBuilder();

   36         while (dr.Read())

   37         {

   38             sb.Append(dr["UserName"].ToString());           

   39         }       

   40         dr.Close();

   41         cn.Close();

   42 

   43         if (sb.Length > 0)

   44         {

   45             sb.Remove(sb.Length - 2, 2);

   46         }

   47 

   48         Literal1.Text = sb.ToString();

Include the control on any .aspx page and you are set.

4 comments ↓

#1 Pablogrind on 01.05.08 at 7:46 am

Excelent nice code.. very interesting

#2 Greg Bray on 01.24.08 at 6:18 am

I think that is what the Membership.GetNumberOfUsersOnline() function does:

http://msdn2.microsoft.com/en-us/library/system.web.security.membership.getnumberofusersonline.aspx

The time window is configured as an attribute of the membership tag in web.config

#3 pwlasantha on 03.12.08 at 8:15 am

Exellent,this was a big problem to me.thanks lot.

#4 Icen on 09.15.08 at 4:20 pm

Nice but there is one problem what will happen if some one will press logout button?

He will appear one line for next 10 minutes which is unacceptable.

Leave a Comment