Search code examples
asp.netvisual-studio-2010securityasp.net-membership

how to Get Number Of Users Online for each role using ASP.NET


I would like to know the number of users logged for each role into my ASP.NET application i have an (Admin) role and the (rest) role i want to know the Number Of Users Online for each one not the entire application what this method did :

Membership.GetNumberOfUsersOnline()

Solution

  • You will need to enumerate the users yourself. If you make use of

    Membership.GetAllUsers()
    

    you get a collection of all available users. Then you can loop through each user and check the IsOnline property to see if the user is online. To determine the roles of the user, you can make use of the methods in the Roles class.

    For example, if you have two roles admin and rest, and you would like to display how many users are online in each role, you could do something like this:

    var adminCount = 0, restCount = 0;
    foreach ( var user in Membership.GetAllUsers().Where(u => u.IsOnline) )
        if (Roles.IsUserInRole(user.UserName, "admin"))
            adminCount++;
        else if (Roles.IsUserInRole(user.UserName, "rest"))
            restCount++;
    
    // do something with adminCount and restCount
    

    If you have more complicated role structure, or many roles, you could use a map to store the count per role. The logic is up to you what you want to accomplish, this should provide all the pieces necessary to express your custom counting logic.