3

I am using SignalR library to show online Users. At present i am able to display total number of online users but when i am diplay the list of online user with their name it makes me confused. I don't have any idea that how could i manage the particular online status at present i want to manage the particular online user status by database. I have table which i want to manage on Onconnected and OnDisconnected method. Please give me an idea that how could i display list of online user Here it is my code.

<script src="~/Content/Scripts/jquery-ui.min.js"></script>
<script src="~/Content/Scripts/jquery.ui.touch-punch.js"></script>
<script src="~/Content/Scripts/jquery.signalR-1.1.3.js"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script>
    $(document).ready(function () {
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var userActivity = $.connection.userActivityHub;
            var Chat = $.connection.Chat;
            // Create a function that the hub can call back to display messages.
            userActivity.client.updateUsersOnlineCount = function (count) {
               
                // Add the message to the page.

                console.log('Count :' + count);
                $('#usersCount').text(count);
            };
            //Chat.server.SetName($.connection.hub.id, $("#displayname").val())

            $.connection.hub.start();
        });
    });
</script>


I have a HubClass named UserActivityHub.

using System.Collections.Generic;
using System;
using System.Web;
using IMWedding.BAL.UserInfos;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace IMWedding.Utils
{
    [HubName("userActivityHub")]
    public class UserActivityHub : Hub
    {
        IUserInfosRepository _userRepo;
        public UserActivityHub()
        {
            this._userRepo = new UserInfosRepository();
        }
        /// <summary>
        /// The count of users connected.
        /// </summary>
        public static List<string> Users = new List<string>(); 

        /// <summary>
        /// Sends the update user count to the listening view.
        /// </summary>
        /// <param name="count">
        /// The count.
        /// </param>
        public void Send(int count)
        {
            // Call the addNewMessageToPage method to update clients.
            var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
            context.Clients.All.updateUsersOnlineCount(count);
        }

        /// <summary>
        /// The OnConnected event.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// 
        public override System.Threading.Tasks.Task OnConnected()
        {
            string clientId = GetClientId();
            if (Users.IndexOf(clientId) == -1)
            {
                Users.Add(clientId);
            }
            //if (!string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Session["UserInfoID"])))
            //{

            //    var detail = _userRepo.GetUserDetailByUserID(UserId);
            //    if (detail != null)
            //    {
            //        if (!string.IsNullOrEmpty(clientId))
            //        {
            //            detail.CreatedBy = UserId;
            //            bool Result = _userRepo.AddUserDetail(detail);
            //        }
            //    }
            //}

            // Send the current count of users
            Send(Users.Count);

            return base.OnConnected();
        }

        public void SetName(string cid, string name)
        {
            //Users.Find(uo => uo.con_id == cid).client_name = name;
        }

        /// <summary>
        /// The OnReconnected event.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        //public override System.Threading.Tasks.Task OnReconnected()
        //{
        //    string clientId = GetClientId();
        //    if (Users.IndexOf(clientId) == -1)
        //    {
        //        Users.Add(clientId);
        //    }

        //    // Send the current count of users
        //    Send(Users.Count);

        //    return base.OnReconnected();
        //}

        /// <summary>
        /// The OnDisconnected event.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public override System.Threading.Tasks.Task OnDisconnected(bool StopCalled)

        {
            string clientId = GetClientId();

            if (Users.IndexOf(clientId) > -1)
            {
                Users.Remove(clientId);
            }
            if (!string.IsNullOrEmpty(clientId))
            {
                bool Result = _userRepo.RemoveDetail(clientId);
            }
            // Send the current count of users
            Send(Users.Count);

            return base.OnDisconnected(StopCalled);
        }

        /// <summary>
        /// Get's the currently connected Id of the client.
        /// This is unique for each client and is used to identify
        /// a connection.
        /// </summary>
        /// <returns>The client Id.</returns>
        private string GetClientId()
        {
            string clientId = "";
            if (Context.QueryString["clientId"] != null)
            {
                // clientId passed from application 
                clientId = this.Context.QueryString["clientId"];
            }

            if (string.IsNullOrEmpty(clientId.Trim()))
            {
                clientId = Context.ConnectionId;
            }

            return clientId;
        }
    }
}

The application_start method in global.asax File

  protected void Application_Start()
       {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            MailSchedulerModel objmodel = new MailSchedulerModel();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
           // GlobalFilters.Filters.Add(new )
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            }
            
            
Here it is my Startup.Auth.cs

 public void ConfigureAuth(IAppBuilder app)
        {
            app.MapSignalR();
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
shami sheikh
  • 552
  • 3
  • 13
  • 26
  • The following article covers all this: https://www.red-gate.com/simple-talk/dotnet/asp-net/tracking-online-users-with-signalr/ – Savage Nov 07 '19 at 14:13

1 Answers1

2

Firstly, create SendUserList method inside UserActivityHub hub.

    public void SendUserList(List<string> users)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
        context.Clients.All.updateUserList(users);
    }

Then, inside System.Threading.Tasks.Task OnConnected() method call SendUserList method;

    public override System.Threading.Tasks.Task OnConnected()
    {
        string clientId = GetClientId();
        if (Users.IndexOf(clientId) == -1)
        {
            Users.Add(clientId);
        }
        //if (!string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Session["UserInfoID"])))
        //{

        //    var detail = _userRepo.GetUserDetailByUserID(UserId);
        //    if (detail != null)
        //    {
        //        if (!string.IsNullOrEmpty(clientId))
        //        {
        //            detail.CreatedBy = UserId;
        //            bool Result = _userRepo.AddUserDetail(detail);
        //        }
        //    }
        //}

        // Send the current users
        SendUserList(Users);

        return base.OnConnected();
    }

Lastly, inside javascript part insert updateUserList function to handle userList which is pushed from server;

$(document).ready(function () {
    $(function () {
        // Reference the auto-generated proxy for the hub.
        var userActivity = $.connection.userActivityHub;
        var Chat = $.connection.Chat;
        // Create a function that the hub can call back to display messages.
        userActivity.client.updateUsersOnlineCount = function (count) {

            // Add the message to the page.

            console.log('Count :' + count);
            $('#usersCount').text(count);
        };
        userActivity.client.updateUserList = function (userList) {

            //Take action with userList
        };
        //Chat.server.SetName($.connection.hub.id, $("#displayname").val())

        $.connection.hub.start();
    });
});
lucky
  • 12,734
  • 4
  • 24
  • 46
  • #Rainman, First of all thank you so much . But still i have some confusion like the userlist which is coming from oncconnected and on disconnectd method. So how could i perform action to manage the table . I mean how could i recognize that it is coming from onconnected and on disconnected method. And one more thing how could i recognize which id has to be delete from table because on disconnected methos ClientId is already destroyed. Please suggest me i will be highly obliged to you. – shami sheikh Nov 27 '17 at 06:48
  • You can just pass a bool parameter to determine it but I am wondering that why are you pushing data inside of Ondisconnected method? It comes weird. – lucky Nov 27 '17 at 06:52
  • actually sir i have to delete a record from database table in respect with client ID . Because i have to show the name of user also while displaying the online User list. – shami sheikh Nov 27 '17 at 07:04
  • I would like to clear one important thing like i will have only those user's detail in my table who are online . The user those comes to disconnect i will remove their data from my table . – shami sheikh Nov 27 '17 at 07:07
  • Okey, just modify SendUserList method. SendUserList(List users,bool isPushedFromOnConnected); You can pass false or true parameter depends on methods – lucky Nov 27 '17 at 07:08
  • Ok Thank you so much sir. – shami sheikh Nov 27 '17 at 07:18