locked
prevoius browser window notifed when new client come RRS feed

  • Question

  • User81789783 posted

    I have chat app in signal R mvc . Its working fine and its working like this

    1. i created client say client1 in Chrome it displayed its connectionid  and name
    2. i created client say client2 in Firefox it displayed its connectionid and name also client1 connectionid   and name
    3. i created client say client3 in opera it displayed its connectionid and name also previous two connectionid  and name (i.e client1 and client2) onl

    That means first browser have only one, second  browser have two,third browser have three

    i want to update prevoius window also i.e update all browser window when  new one created . 

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Threading.Tasks;
    using Microsoft.AspNet.SignalR;
    
    namespace LetsChatApplication.Hubs
    {
        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);
            }
            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();
            }
        }
    }
    @{
        ViewBag.Title = "LetsChat";
    
    }
    
    
    <h2>Lets Chat</h2>
     <h5>Online</h5>
    <link href="~/Content/sweetalert.css" rel="stylesheet" />
    @*<input type="text" placeholder="your session" id="txtSession" />
    <br />
    <input type="button" value="Sign In" id="signIn" />
    <br />
    
    <input type="button" value="Create Session" id="createSession" />
    <br />*@
    <div class="form-group col-xl-12">
        
        <ul id="online"></ul>
        <label id="connlbl" class="control-label">Your connection Id</label><br />
        <input type="text" class="col-lg-12 text-primary" id="frndConnId" placeholder="Paste your friend's connection Id" /><br /><br />
        <label class="control-label">Your Message</label><br />
        <textarea type="text" class="col-lg-10 text-primary" id="message"></textarea>&nbsp;&nbsp;&nbsp;&nbsp;
    
        <input type="button" class="btn btn-primary" id="sendmessage" value="Send" /><br /><br />
        <img src="~/Content/smile.jpg" width="20" height="20" id="smile" style="cursor:pointer"/>
        <img src="~/Content/uff.jpg" width="20" height="20" id="ufff" style="cursor:pointer" />
        <div class="container chatArea">
            <input type="hidden" id="displayname" />
            <div id="discussion"></div>
        </div>
    </div>
    <br />
    <input type="hidden" id="connId" />
    @*<input type="button" value="Sign Out" id="signOut" />*@
    <!--Reference the autogenerated SignalR hub script. -->
    @section scripts {
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
        <script src="~/Content/sweetalert.min.js"></script>
        <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
        <script src="~/signalr/hubs"></script>
        <script>
            function getValue(a) {
                alert(a.innerHTML);
                $("#frndConnId").val(a.innerHTML)
    
            }
            //var userName = "";
            //var sessionVal = '';
            $(function () {
                // Reference the auto-generated proxy for the hub.
                var chat = $.connection.letsChatHub;
                //  alert("auto-generated proxy for the hub")
                debugger;
    
                // Create a function that the hub can call back to display messages.
                chat.client.addNewMessageToPage = function (name, message) {
                    //  alert("name" + name)
                    //  alert("message" + message)
                    // Add the message to the page.
    
    
                    $('#discussion').append('<li><strong>' + htmlEncode(name)
                        + '</strong>: ' + htmlEncode(message) + '</li>');
                };
    
                chat.client.addNewuserToPage = function (id) {
                    // alert(id.connId)
                    //$.each(id, function (key, value) {
                    //    alert('caste: ' + value.connId + ' | id: ' + value.name);
                    //});
                    alert(id.length)
                    var data = id;
    
                  
                    $.each(data, function (k, v) {
                        for (var prop in v) {
    
                            var userid = "";
                            var username = "";
                            if (v.hasOwnProperty(prop)) {
                                alert(prop + ' is ' + v[prop]);
                                if(prop == "Key")
                                    userid = userid + v[prop]
                                else 
                                    username = username + v[prop]
    
                            }
                            $('#online').append('<strong>' + "<a  onclick=getValue(this); href='#'>" + userid + "</a>" + "   " + username + "<BR>");
    
                        }
    
                    });
                  
                    //    alert("key value" + id)
                    //$.each(id, function () {
                    //    alert(this)
                    //    alert(htmlEncode(this.connId.to))
                    //    alert(htmlEncode(this.name))
                    //    $('#online').append('<strong>' + "<a  onclick=getValue(this); href='#'>" + htmlEncode(this.connId) + "</a>" + "   " + htmlEncode(this.name) + "<BR>");
                    //});
                    // $('#online').append('<strong>' + htmlEncode(id));
                };
    
               
                // Get the user name and store it to prepend to messages.
                swal({
                    title: "Lets Chat!",
                    text: "<span style='color:#f8bb86;font-weight:700;'>Enter your name:</span>",
                    type: "input",
                    html: true,
                    showCancelButton: true,
                    closeOnConfirm: true,
                    animation: "slide-from-top",
                    inputPlaceholder: "Your Name"
                },
                function (inputValue) {
                    userName = inputValue;
                    if (inputValue === false) return false;
                    if (inputValue === "") {
                        swal.showInputError("You need to type your name!");
                        return false;
                    }
                    $('#displayname').val(inputValue);
    
    
                    alert($('#displayname').val())
                    chat.server.send($('#displayname').val(), $.connection.hub.id);
                });
                // Set initial focus to message input box.
                $('#message').focus();
                $('#message').keypress(function (e) {
                    if (e.which == 13) {//Enter key pressed
                        $('#sendmessage').trigger('click');//Trigger search button click event
                    }
                });
                $("#smile").click(function () {
    
                });
                // Start the connection.
                $.connection.hub.start().done(function () {
                    alert("start done")
    
                    //*****************************************/
                   
            
            
            
                    /*********************************************/
    
                  //  chatHub.server.sendMessageToAll(userName, msg);
                //    alert($.connection.hub.id)
                    $("#connlbl").append("  : " + $.connection.hub.id)
                   
    
                    $('#sendmessage').click(function () {
                     //   alert("Send click")
                        // Call the Send method on the hub.
                        var connId = $("#connId").val();
                       // alert(connId)
                        var frndConnId = $("#frndConnId").val();
                        var finalConnId = frndConnId == "" ? $.connection.hub.id : frndConnId;
                        chat.server.send($('#displayname').val(), $('#message').val(), finalConnId);
                        $("#connId").val($.connection.hub.id);
                        if (frndConnId == "") {
                            swal("You connection Id", $.connection.hub.id, "success");
                        }
                        // Clear text box and reset focus for next comment.
                        $('#discussion').append('<li><strong>' + htmlEncode($('#displayname').val())
                       + '</strong>: ' + htmlEncode($('#message').val()) + '</li>');
                        $('#message').val('').focus();
                    });
                });
                @*var checkSession = false;
            $("#signIn").on('click', function () {
                sessionVal = $("#txtSession").val();
                if ($("#txtSession").val() != "") {
                    $.ajax({
                        url: "/LetsChat/CheckSession?sessionValue=" + sessionVal,
                        success: function (response) {
                            if (response === "True") {
                                alert(response);
                                $(".container").show();
                                checkSession = true;
                            }
                        }
                    });
                    
                }
                else {
    
                }
            });
            $("#createSession").on('click', function () {
                @{
                     Session["UniqueId"] = Guid.NewGuid();
                 }
                var sessionvalue =  '@Session["UniqueId"]';
                $.ajax({
                    url: "/LetsChat/SaveSession?name=" + userName + "&sessionId=" + sessionvalue,
                    success: function (response) {
                        setTimeout(function () {
                            swal({
                                title: '@Session["UniqueId"]',
                                text: "<span style='color:#f8bb86;font-weight:700;'>Your chat session! Share this session id to start chatting!'</span>",
                                html: true,
                                closeOnConfirm: true,
                                animation: "slide-from-top"
                            }, function (isConfrim) {
                                return true;
                            });
                        }, 1000);
                    }
                });
               
            });
            $("#signOut").on('click', function () {
                @{
                    Session["UniqueId"] = null;
                    Session.Abandon();
                    Session.Remove("UniqueId");
                    }
            });
        });*@
            });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
        </script>
    }
    

    can any one update or help me piece of code ,how to do this

    Friday, May 24, 2019 12:39 PM

Answers

  • User81789783 posted

    i have done like this

            function updateNotificationCount() {
               
                    value = $("#connlbl").text();
                    alert("value: " + value)
                    $.ajax({
                        type: "POST",
                        url: "/LetsChat/GetOnlineusers?connid=" + value,
                  
                        contentType: "application/json; charset=utf-8",
                   
                        dataType: "json",
                        success: function (response) {
                            debugger;
                            $('#notiContent').empty();
                            if (response.length == 0) {
                                $('#notiContent').append($('<li>Currently You Have No New users.</li>'));
                            }
                            for (var i = 0, len = response.length; i < len; i++) {
                 
                                $('#notiContent').append('<strong>'+ (i+1) + "<a  onclick=getValue(this); href='#'>" + response[i].ContextID + "</a>" + "   " + response[i].Name + "<BR>");
                              //  $('#online').append('<strong>' + "<a  onclick=getValue(this); href='#'>" + userid + "</a>" + "   " + username + "<BR>");
    
    
                            }
                            $.each(response, function (index, value) {
                              
                               // $('#notiContent').append($('<li>The User: , ' + value.Name + '&nbsp;' + 'Of ID' + ' (' + index.ContextID + ') Is Written Something.</li>'));
                            });
                        },
                        error: errorFunc
                    });
                }
    
      [HttpPost]
            public JsonResult GetOnlineusers(string connid)
            {
                NotificationComponent nc = new NotificationComponent();
                var list = nc.GetData(connid);
    
    
                return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        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;
               
            }

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

All replies

  • User61956409 posted

    Hi erum,

    i want to update prevoius window also i.e update all browser window when  new one created . 

    It seems that you'd like to update online user list/details for all connected clients, if that is the case, you can refer to the following example.

    [Mapping user to connections](https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections#in-memory-storage)

    public class ConnectionMapping<T>
    {
        private readonly Dictionary<T, HashSet<string>> _connections =
            new Dictionary<T, HashSet<string>>();
    
        public int Count
        {
            get
            {
                return _connections.Count;
            }
        }
    
        public void Add(T key, string connectionId)
        {
            lock (_connections)
            {
                HashSet<string> connections;
                if (!_connections.TryGetValue(key, out connections))
                {
                    connections = new HashSet<string>();
                    _connections.Add(key, connections);
                }
    
                lock (connections)
                {
                    connections.Add(connectionId);
                }
            }
        }
    
        public IEnumerable<string> GetConnections(T key)
        {
            HashSet<string> connections;
            if (_connections.TryGetValue(key, out connections))
            {
                return connections;
            }
    
            return Enumerable.Empty<string>();
        }
    
        public void Remove(T key, string connectionId)
        {
            lock (_connections)
            {
                HashSet<string> connections;
                if (!_connections.TryGetValue(key, out connections))
                {
                    return;
                }
    
                lock (connections)
                {
                    connections.Remove(connectionId);
    
                    if (connections.Count == 0)
                    {
                        _connections.Remove(key);
                    }
                }
            }
        }
    
        public string ToJson()
        {
            var entries = _connections.Select(d =>
                string.Format("\"{0}\": [\"{1}\"]", d.Key, string.Join(",", d.Value)));
            return "{" + string.Join(",", entries) + "}";
        }
    }

    OnConnected of hub class

    public override Task OnConnected()
    {
        name = String.IsNullOrEmpty(Context.QueryString["username"]) ? "unknow" : Context.QueryString["username"].ToString();
    
        _connections.Add(name, Context.ConnectionId);
    
        //update online user list
        Clients.All.updateList(_connections.ToJson());
    
        return base.OnConnected();
    }

    Pass user name to hub server

    //pass username to hub
    var username = prompt('Enter your name:', '');
    $('#displayname').val(username);
    $.connection.hub.qs = { 'username': username };

    Update user list on JavaScript client side

    chat.client.updateList = function (cons) {
        var userlist = JSON.parse(cons);
    
        //clear user list first
        $('#user_list').empty();
    
        //then re-populate it again with new data
        $.each(userlist, function (key, item) {
            var userinfo = "User Name: <b>" + key + "</b>, Connections: " + item;
    
            $('#user_list').append('<li>'
                + userinfo + '</li>');
    
            console.log(userinfo);
        })
                    
    };

    User List

    <h2>Online Users</h2>
    <div class="container">
        <ul id="user_list"></ul>
    </div>

    Test Result:

    With Regards,

    Fei Han

    Monday, May 27, 2019 3:23 AM
  • User81789783 posted

    Well Fei ,is this the full code , ??

    Monday, May 27, 2019 9:27 AM
  • User61956409 posted

    Hi erum,

    Well Fei ,is this the full code , ??

    The code snippet that I shared in my last reply is the main code of my application, you are using different approach to persist user-connectionIds details and different front-end html, so I just share the main code for your reference.

    In [your another thread](https://forums.asp.net/t/2155991.aspx), I shared the detail code to achieve the requirement. Besides, we are discussing similar/same problem in these two threads, I suggest that if my last reply of this thread is helpful, you can accept it as answer to close this thread, then you can post back in [another thread](https://forums.asp.net/t/2155991.aspx) for further discussion. Thanks for your understanding.

    With Regards,

    Fei Han

    Tuesday, May 28, 2019 3:12 AM
  • User81789783 posted

    well FEi ,I chnaged my code little but still not working

    here is udpated code snippt

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace LetsChatApplication
    {
        public class users
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public Nullable<System.DateTime> AddedOn { get; set; }
            public string ContextID { get; set; }
    
            public string Currentid { get; set; }
    
        }
    }
       function updateNotificationCount() {
                    alert("updateNotificationCount")
                   // alert(connid)
                    //$.ajax({
                    //    type: 'POST',
                    //   // url: '/LetsChat/GetOnlineusers',
                    //    url: '/NotificationComponent/GetData',
                    //    data: { connid: connid },
                    //    dataType: "json",
                    //    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);
                    //    }
                    //})
    
                    $.ajax({
                        type: "POST",
                        //url: "/LetsChat/GetOnlineusers?connid=" + chat.server.getConnections(),
                        url: "/LetsChat/GetOnlineusers",
                        //   data: JSON.stringify({ values: valueArray.toString() }),
                        contentType: "application/json; charset=utf-8",
                        data :  chat.server.getConnections(),
                        dataType: "json",
                        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: errorFunc
                    });
    
                }
    
               
                // Start the connection.
                $.connection.hub.start().done(function () {
                    alert("start done")
    
                    //*****************************************/
                   
            
            
            
                    /*********************************************/
    
                  //  chatHub.server.sendMessageToAll(userName, msg);
                //    alert($.connection.hub.id)
                    $("#connlbl").append("  : " + $.connection.hub.id)
                   
    
                    $('#sendmessage').click(function () {
                     //   alert("Send click")
                        // Call the Send method on the hub.
                        var connId = $("#connId").val();
                       // alert(connId)
                        var frndConnId = $("#frndConnId").val();
                        var finalConnId = frndConnId == "" ? $.connection.hub.id : frndConnId;
                        chat.server.send($('#displayname').val(), $('#message').val(), finalConnId);
    
    
                        $("#connId").val($.connection.hub.id);
                        if (frndConnId == "") {
                            swal("You connection Id", $.connection.hub.id, "success");
                        }
                        // Clear text box and reset focus for next comment.
                        $('#discussion').append('<li><strong>' + htmlEncode($('#displayname').val())
                       + '</strong>: ' + htmlEncode($('#message').val()) + '</li>');
                        $('#message').val('').focus();
                    });
                });
            function (inputValue) {
                    userName = inputValue;
                    if (inputValue === false) return false;
                    if (inputValue === "") {
                        swal.showInputError("You need to type your name!");
                        return false;
                    }
                    $('#displayname').val(inputValue);
    
    
                    alert($('#displayname').val())
    
                    //ajax call here
                    //  var serviceURL = '/LetsChat/savetodb';
                 //   alert("before $.connection.hub.id")
                    var user = {
                        Connectionid:  $.connection.hub.id,
                        Name: $('#displayname').val()
                      
                    };
                    alert("after $.connection.hub.id")
                    var connectionid = $.connection.hub.id;
                    chat.server.send($('#displayname').val(), connectionid);
    
                    $.ajax({
                        type: "POST",
                        url: "/LetsChat/savetodb?name=" + $('#displayname').val() + "&connid=" + connectionid,
                       // url: "/LetsChat/savetodb?name=" + $('#displayname').val() + "&connid=" + chat.server.getConnections(),
                      
                     //   data: JSON.stringify({ values: valueArray.toString() }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        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: errorFunc
                    });
                  
                  
                   
                    //ajax call end
                    //var connectionid= $.connection.hub.id;
                    //chat.server.send($('#displayname').val(), connectionid);
    
    
                });

    here is controller

            [HttpPost]
            public JsonResult GetOnlineusers(string connid)
            {
                NotificationComponent nc = new NotificationComponent();
                var list = nc.GetData(connid);
    
    
                return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
    
            [HttpPost]
            
                 public JsonResult savetodb(string name, string connid)
           // public ActionResult savetodb (string name,string connid)
            {
                ExecuteTsql ts = new ExecuteTsql();
            //    string str = 
                ts.IUD("insert into users(name,ContextID,[AddedOn]) values(" + "'" + name + "'," + "'" + connid + "','" + DateTime.Now +"'"+ ")");
                //  return View();
                NotificationComponent nc = new NotificationComponent();
                  nc.DataBaseInsert(connid);
    
              var list=   nc.GetData(connid);
    
    
                return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                //  Clients.AllExcept(Context.ConnectionId).addNewuserToPage(UserHandler.ConnectedIds);
                // return Json("success", JsonRequestBehavior.AllowGet);
    
            }

    and here is hub class

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Threading.Tasks;
    using Microsoft.AspNet.SignalR;
    using System.Collections.Generic;
    using System.Linq;
    
    //https://archive.codeplex.com/?p=realtimenotifications
    
    namespace LetsChatApplication
    {
       
        // public static class UserHandler
        // {
        //   public static HashSet<string> ConnectedIds = new HashSet<string>();
    
    
        //  var list = new List<KeyValuePair<string, int>>();
        //  }
      
        public class LetsChatHub : Hub
        {
            public static List<KeyValuePair<string, string>> ConnectedIds = new List<KeyValuePair<string, string>>();
            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);
                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();
            }
            //return list of all active connections
            public  string   getConnections()
            {
                users usr = new users();
                List<users> userList = new List<users>();
                //  usr.Currentid = Clients.Client(Context.ConnectionId);
             //   var c = Clients.Client(Context.ConnectionId);
                usr.Currentid = Context.ConnectionId;
                userList.Add(usr);
                // ConnectedIds.ToList();
    
                //HashSet<string> connections;
                //if (ConnectedIds.TryGetValue(key, out connections))
                //{
                //    return connections;
                //}
    
                //return Enumerable.Empty<string>();
                return usr.Currentid;
            }
        }
    }

    Wednesday, May 29, 2019 1:12 PM
  • User61956409 posted

    Hi erum,

    I have shared the replies with working code in your other threads, please refer to it.

    https://forums.asp.net/t/2155991.aspx

    https://forums.asp.net/t/2156121.aspx 

    Besides, you created new threads for your questions, as I suggested, if possible, please close this thread and post back in above two threads if you need further discussion.

    With Regards,

    Fei Han

    Friday, May 31, 2019 8:05 AM
  • User81789783 posted

    i have done like this

            function updateNotificationCount() {
               
                    value = $("#connlbl").text();
                    alert("value: " + value)
                    $.ajax({
                        type: "POST",
                        url: "/LetsChat/GetOnlineusers?connid=" + value,
                  
                        contentType: "application/json; charset=utf-8",
                   
                        dataType: "json",
                        success: function (response) {
                            debugger;
                            $('#notiContent').empty();
                            if (response.length == 0) {
                                $('#notiContent').append($('<li>Currently You Have No New users.</li>'));
                            }
                            for (var i = 0, len = response.length; i < len; i++) {
                 
                                $('#notiContent').append('<strong>'+ (i+1) + "<a  onclick=getValue(this); href='#'>" + response[i].ContextID + "</a>" + "   " + response[i].Name + "<BR>");
                              //  $('#online').append('<strong>' + "<a  onclick=getValue(this); href='#'>" + userid + "</a>" + "   " + username + "<BR>");
    
    
                            }
                            $.each(response, function (index, value) {
                              
                               // $('#notiContent').append($('<li>The User: , ' + value.Name + '&nbsp;' + 'Of ID' + ' (' + index.ContextID + ') Is Written Something.</li>'));
                            });
                        },
                        error: errorFunc
                    });
                }
    
      [HttpPost]
            public JsonResult GetOnlineusers(string connid)
            {
                NotificationComponent nc = new NotificationComponent();
                var list = nc.GetData(connid);
    
    
                return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        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;
               
            }

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