locked
store signal R conenction ID and used in class RRS feed

  • Question

  • User81789783 posted

    here is my signal R hub class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Threading.Tasks;
    using Microsoft.AspNet.SignalR;
    //https://archive.codeplex.com/?p=realtimenotifications
    
    namespace LetsChatApplication
    {
    
        public static class UserHandler
        {
            //   public static HashSet<string> ConnectedIds = new HashSet<string>();
            public static List<KeyValuePair<string, string>> ConnectedIds = new List<KeyValuePair<string, string>>();
            //  var list = new List<KeyValuePair<string, int>>();
        }
        public class LetsChatHub : Hub
        {
            public void Send(string name, string message, string connId)
            {
                Clients.Client(connId).addNewMessageToPage(name, message);
            }
            public void Send(string name, string connId)
            {
                
                //  Clients.Client(connId).addNewMessageToPage(name, connId);
                //  UserHandler.ConnectedIds.Add(Context.ConnectionId);
                UserHandler.ConnectedIds.Add(new KeyValuePair<string, string>(connId, name));
               
                //Clients.Client(Context.ConnectionId).addNewuserToPage(UserHandler.ConnectedIds);// work fne too
                  Clients.AllExcept(connId).addNewuserToPage(UserHandler.ConnectedIds);
            }
            public override Task OnConnected()
            {
    
                //  UserHandler.ConnectedIds.Add(Context.ConnectionId);
                //   Clients.Client(Context.ConnectionId).addNewuserToPage(UserHandler.ConnectedIds);
    
                for (int i = 0; i < UserHandler.ConnectedIds.Count; i++)
                {
    
    
                }
                return base.OnConnected();
            }
    
            public override Task OnReconnected()
            {
                return base.OnReconnected();
            }
        }
    }

    i wanted to store connId in  above code ,highlighted in above code and want to used in  another class i.e getdata function.can any one help me how to store in hub class and store in another used define class

     public List<users> GetData(DateTime afterDate)
       
            {
                ExecuteTsql ex = new ExecuteTsql();
                DataSet ds = new DataSet();
    
                //ds=  ex.SelectQueryDS("SELECT *   FROM[LetsChat].[dbo].[users] where [AddedOn]>"+"'"+  afterDate+"'");
                ds = ex.SelectQueryDS("SELECT *   FROM[LetsChat].[dbo].[users]");
    
                //map with displayed list except
                        var notificationHub = GlobalHost.ConnectionManager.GetHubContext<LetsChatHub>();
               // notificationHub.Clients.AllExcept(users).addNewuserToPage(UserHandler.ConnectedIds);
    
                var userList = ds.Tables[0].AsEnumerable().Select(dataRow => new users { Name = dataRow.Field<string>("Name") }).ToList();
                return userList;
                //using (SignalRDBEntities dc = new SignalRDBEntities())
                //{
                //    return dc.tblEmployees.Where(a => a.AddedOn > afterDate).OrderByDescending(a => a.AddedOn).ToList();
                //}
            }

    Monday, May 27, 2019 5:15 PM

Answers

  • User81789783 posted
          public List<users> GetData(string ExcludeConnectionid)
            //public List<users> GetData(DateTime afterDate)
    
            {
    
                ExecuteTsql ex = new ExecuteTsql();
                DataSet ds = new DataSet();
    
                //ds=  ex.SelectQueryDS("SELECT *   FROM[LetsChat].[dbo].[users] where [AddedOn]>"+"'"+  afterDate+"'");
                ds = ex.SelectQueryDS("SELECT *   FROM[LetsChat].[dbo].[users] where contextid!="+"'" + ExcludeConnectionid +"'");
    
                
           //   var notificationHub = GlobalHost.ConnectionManager.GetHubContext<LetsChatHub>();
            //  var data =   notificationHub.Clients.All.showMessage();
               // await this.notificationHub.Clients.All.InvokeAsync("GetConnections");
               
                
                var userList = ds.Tables[0].AsEnumerable().Select(dataRow => new users { Name = dataRow.Field<string>("Name") , ContextID = dataRow.Field<string>("ContextID") }).ToList();
                return userList;
               
            }

    already done myself

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 1, 2019 9:21 AM

All replies

  • User61956409 posted

    Hi erum,

       Clients.AllExcept(connId).addNewuserToPage(UserHandler.ConnectedIds);

    i wanted to store connId in  above code ,highlighted in above code and want to used in  another class i.e getdata function.can any one help me how to store in hub class and store in another used define class

    var notificationHub = GlobalHost.ConnectionManager.GetHubContext<LetsChatHub>();

    It seems that you'd like to send messages to client(s) from outside an instance of the Hub class, the HubContext should be able to help achieve the requirement. Can you clarify more about the problem? 

    I did a test in my application with the following code snippet, which work well on my side.

    var ids = ChatHub.ConnectedIds;
    
    var context = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
    
    context.Clients.All.addNewuserToPage(ids);

    Test Result:

    With Regards,

    Fei Han

    Tuesday, May 28, 2019 5:29 AM
  • User81789783 posted

    yes i need to use in another class

    var ids = ChatHub.ConnectedIds;

    well ,if i write  so after LetsChatHub it does not showing ConnectedIds

    where ChatHub is my hub class

    below is the function where i need to

     public   void DataBaseInsert ()
            {
                //Alternate of sql dependency 
    
                var notificationHub = GlobalHost.ConnectionManager.GetHubContext<LetsChatHub>();
                notificationHub.Clients.All.notify("added");
               // var id = LetsChatHub.
             
    
                //  var ids= notificationHub.Clients.c
                //re-register notification
                //RegisterNotification(DateTime.Now);
                RegisterNotification(DateTime.Now);
    
            }

    Tuesday, May 28, 2019 6:19 AM
  • User81789783 posted

    well ,let rephrase what i actually required , when connection

    id is created ,i goes to here

    public static List<KeyValuePair<string, string>> ConnectedIds = new List<KeyValuePair<string, string>>();

    when  GetOnlineusers () function i want to show all connected client except own ..

      function updateNotificationCount() {
                    alert("updateNotificationCount")
                    $.ajax({
                        type: 'GET',
                        url: '/LetsChat/GetOnlineusers',
                        success: function (response) {
                            debugger;
                            $('#notiContent').empty();
                            if (response.length == 0) {
                                $('#notiContent').append($('<li>Currently You Have No New Notifications.</li>'));
                            }
                            $.each(response, function (index, value) {
                                $('#notiContent').append($('<li>The User , ' + value.Name + '&nbsp;' + 'Of ID' + ' (' + value.ID + ') Is Written Something.</li>'));
                            });
                        },
                        error: function (error) {
                            console.log(error);
                        }
                    })
    
                    //$('span.count').show();
                    //var count = 0;
                    //count = parseInt($('span.count').html()) || 0;
                    //count++;
                    //$('span.noti').css("color", "white");
                    //$('span.count').css({ "background-color": "red", "color": "white" });
                    //$('span.count').html(count);
    
                }

      public JsonResult GetOnlineusers()
            {
                var notificationRegisterTime = Session["LastUpdated"] != null ? Convert.ToDateTime(Session["LastUpdated"]) : DateTime.Now;
                NotificationComponent NC = new NotificationComponent();
                var list = NC.GetData(notificationRegisterTime);
    
                //update session here for get only new added contacts (notification)
                //   Session["LastUpdate"] = DateTime.Now;
                
                     Session["LastUpdated"] = DateTime.Now;
                return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }



    public void Send(string name, string connId)
    {

    UserHandler.ConnectedIds.Add(new KeyValuePair<string, string>(connId, name));


    }

    Tuesday, May 28, 2019 6:50 AM
  • User61956409 posted

    Hi erum,

    You are making request to your API (action GetOnlineusers), does it return the expected data? What's the data in that list.

    var list = NC.GetData(notificationRegisterTime);

    With Regards,

    Fei Han

    Friday, May 31, 2019 8:16 AM
  • User81789783 posted
          public List<users> GetData(string ExcludeConnectionid)
            //public List<users> GetData(DateTime afterDate)
    
            {
    
                ExecuteTsql ex = new ExecuteTsql();
                DataSet ds = new DataSet();
    
                //ds=  ex.SelectQueryDS("SELECT *   FROM[LetsChat].[dbo].[users] where [AddedOn]>"+"'"+  afterDate+"'");
                ds = ex.SelectQueryDS("SELECT *   FROM[LetsChat].[dbo].[users] where contextid!="+"'" + ExcludeConnectionid +"'");
    
                
           //   var notificationHub = GlobalHost.ConnectionManager.GetHubContext<LetsChatHub>();
            //  var data =   notificationHub.Clients.All.showMessage();
               // await this.notificationHub.Clients.All.InvokeAsync("GetConnections");
               
                
                var userList = ds.Tables[0].AsEnumerable().Select(dataRow => new users { Name = dataRow.Field<string>("Name") , ContextID = dataRow.Field<string>("ContextID") }).ToList();
                return userList;
               
            }

    already done myself

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 1, 2019 9:21 AM