locked
Insert image avatar RRS feed

  • Question

  • User-1640697322 posted

    I friends, i'm new in this forum and i have a great problem. I have a button named "#btnStartChat" and when i click on this i'm logged. Then in a div named "divusers" appear the list of connected users. Now i would like to associate for each users connected a image avatar in "divusers" but I can not do it.  This is my code:

     <script type="text/javascript">
    
            $(function () {
    
                setScreen(false);
    
                // Declare a proxy to reference the hub. 
                var chatHub = $.connection.chatHub;
    
                registerClientMethods(chatHub);
    
                // Start Hub
                $.connection.hub.start().done(function () {
    
                    registerEvents(chatHub)
    
                });
    
            });
    
            function setScreen(isLogin) {
    
                if (!isLogin) {
    
                    $("#divChat").show();
                    $("#divLogin").hide();
                }
                else {
    
                    $("#divChat").show();
                    $("#divLogin").hide();
                }
    
            }
    
            function registerEvents(chatHub) {
    
                $("#btnStartChat").click(function () {
                    var name = $("#txtNickName").val();
                    if (name.length > 0) {
                        chatHub.server.connect(name);
                    }
                    else {
                        alert("Please enter name");
                    }
    
                });
    
    
                $('#btnSendMsg').click(function () {
    
                    var msg = $("#txtMessage").val();
                    if (msg.length > 0) {
    
                        var userName = $('#hdUserName').val();
                        chatHub.server.sendMessageToAll(userName, msg);
                        $("#txtMessage").val('');
                    }
                });
    
    
                $("#txtNickName").keypress(function (e) {
                    if (e.which == 13) {
                        $("#btnStartChat").click();
                    }
                });
    
                $("#txtMessage").keypress(function (e) {
                    if (e.which == 13) {
                        $('#btnSendMsg').click();
                    }
                });
    
    
            }
    
            function registerClientMethods(chatHub) {
    
                // Calls when user successfully logged in
                chatHub.client.onConnected = function (id, userName, allUsers, messages) {
    
                    setScreen(true);
    
                    $('#hdId').val(id);
                    $('#hdUserName').val(userName);
                    $('#spanUser').html(userName);
    
                    // Add All Users
                    for (i = 0; i < allUsers.length; i++) {
    
                        AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
                    }
    
                    // Add Existing Messages
                    for (i = 0; i < messages.length; i++) {
    
                        AddMessage(messages[i].UserName, messages[i].Message);
                    }
    
    
                }
    
                // On New User Connected
                chatHub.client.onNewUserConnected = function (id, name) {
    
                    AddUser(chatHub, id, name);
                }
    
    
                // On User Disconnected
                chatHub.client.onUserDisconnected = function (id, userName) {
    
                    $('#' + id).remove();
    
                    var ctrId = 'private_' + id;
                    $('#' + ctrId).remove();
    
    
                    var disc = $('<div class="disconnect">"' + userName + '" Disconnesso.</div>');
    
                    $(disc).hide();
                    $('#divusers').prepend(disc);
                    $(disc).fadeIn(200).delay(2000).fadeOut(200);
    
                }
    
                chatHub.client.messageReceived = function (userName, message) {
    
                    AddMessage(userName, message);
                }
    
    
                chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
    
                    var ctrId = 'private_' + windowId;
    
    
                    if ($('#' + ctrId).length == 0) {
    
                        createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
    
                    }
    
                    $('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
    
                    // set scrollbar
                    var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
                    $('#' + ctrId).find('#divMessage').scrollTop(height);
    
                }
    
            }
    
            function AddUser(chatHub, id, name) {
    
                var userId = $('#hdId').val();
    
                var code = "";
    
               if (userId == id) {
    
                    code = $('<div class="loginUser">' + name + "</div>");
    
    
                }
                else {
    
                    code = $('<a id="' + id + '" class="user" >' + name + '<a>');
    
                    $(code).dblclick(function () {
    
                        var id = $(this).attr('id');
    
                        if (userId != id)
                            OpenPrivateChatWindow(chatHub, id, name);
    
                    });
                }
    
                $("#divusers").append(code);
    
            }
    
            function AddMessage(userName, message) {
                var data = new Date();
                var mese = data.getMonth() + 1;
                if (mese < 10) {
    
                    mese = '0' + mese;
    
                } else {
    
                    mese = mese + '';
    
                }
                var giorno = data.getDate();
                var anno = data.getFullYear();
                var ora = data.getHours();
                if (ora < 10) {
    
                    ora = '0' + ora;
    
                } else {
    
                    ora = ora + '';
    
                }
                var minuti = data.getMinutes();
                if (minuti < 10) {
    
                    minuti = '0' + minuti;
    
                } else {
    
                    minuti = minuti + '';
    
                }
                var oggi = giorno + "/" + mese + "/" + anno + " " + ora + ":" + minuti;
               
            
                $('#divChatWindow').append('<div class="message"><span class="userName">' + userName + " " + "" + "(" + oggi + ")" + '</span>: ' + message + '</div>');
    
                var height = $('#divChatWindow')[0].scrollHeight;
                $('#divChatWindow').scrollTop(height);
            }
    
            function OpenPrivateChatWindow(chatHub, id, userName) {
    
                var ctrId = 'private_' + id;
    
                if ($('#' + ctrId).length > 0) return;
    
                createPrivateChatWindow(chatHub, id, ctrId, userName);
    
            }
    
            function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
    
                var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
                           '<div class="header">' +
                              '<div  style="float:right;">' +
                                  '<img id="imgDelete"  style="cursor:pointer;" src="/Images/delete.png"/>' +
                               '</div>' +
    
                               '<span class="selText" rel="0">' + userName + '</span>' +
                           '</div>' +
                           '<div id="divMessage" class="messageArea">' +
    
                           '</div>' +
                           '<div class="buttonBar">' +
                              '<input id="txtPrivateMessage" class="msgText" type="text"   />' +
                              '<input id="btnSendMessage" class="submitButton button" type="button" value="Send"   />' +
                           '</div>' +
                        '</div>';
    
                var $div = $(div);
    
                // DELETE BUTTON IMAGE
                $div.find('#imgDelete').click(function () {
                    $('#' + ctrId).remove();
                });
    
                // Send Button event
                $div.find("#btnSendMessage").click(function () {
    
                    $textBox = $div.find("#txtPrivateMessage");
                    var msg = $textBox.val();
                    if (msg.length > 0) {
    
                        chatHub.server.sendPrivateMessage(userId, msg);
                        $textBox.val('');
                    }
                });
    
                // Text Box event
                $div.find("#txtPrivateMessage").keypress(function (e) {
                    if (e.which == 13) {
                        $div.find("#btnSendMessage").click();
                    }
                });
    
                AddDivToContainer($div);
    
            }
    
            function AddDivToContainer($div) {
                $('#divContainer').prepend($div);
    
                $div.draggable({
    
                    handle: ".header",
                    stop: function () {
    
                    }
                });
    
                ////$div.resizable({
                ////    stop: function () {
    
                ////    }
                ////});
    
            }
    
        </script>
    
        <script type="text/javascript">
            function blocca_tasto_dx()
    {
       alert('Tasto destro disabilitato');
       return(false);
    }
    document.oncontextmenu = blocca_tasto_dx;
    </script>

    Now i think that the code where intervene is this and i have modified so:

    function registerEvents(chatHub) {
    
                $("#btnStartChat").click(function () {
                    var image = ("<img src='Images/tn_ball.gif' />");
                    var name = $("#txtNickName").val();
                    if (name.length > 0) {
                        chatHub.server.connect(image + ' ' + ' ' + name);
                    }
                    else {
                        alert("Please enter name");
                    }
    
                });

    Now i have a error because the first users logged it is displayed well but from the second the image in the div is too big.

    Can you help me?

    Excuse me for my bad english.

    Thanks a lot to everyone.

    Friday, February 26, 2016 6:53 PM

Answers

  • User61956409 posted

    Hi Been,

    i used that code of image only for tried because i'm not an expert. Could you post a correct example for resolve this problem???

    I don’t have a complete working sample for your problem, but I could share some idea with you. To display online users with image avatar, you could map a user to the connection id and persist that mapping, and you could specify user’s avatar for each user (connection id). Then you could get and display users with their avatars. For more information about mapping SignalR users to connections, please check this link.

    http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 1, 2016 8:16 AM

All replies

  • User61956409 posted

    Hi Been,

    var image = ("<img src='Images/tn_ball.gif' />");

    var name = $("#txtNickName").val();

    if (name.length > 0) {

    chatHub.server.connect(image + ' ' + ' ' + name);

    }

    According to your code, we could find that you call the connect method on the hub and pass image and name as parameters in “btnStartChat” click event. I’d like to know why you pass <img> tag instead of imgurl as parameter to hub method. And could you show us your hub method?

    Best Regards,

    Fei Han

    Monday, February 29, 2016 7:01 AM
  • User-1814126548 posted

    Thank you for you reply Fei Han, i used that code of image only for tried because i'm not an expert. Could you post a correct example for resolve this problem??? Many thanks.
    This is my code of Connect hub VB.NET:

    Imports Microsoft.AspNet.SignalR
    Imports System.Collections.Generic
    Imports System.Linq
    Imports System.Web
    Imports WebApplication1.SignalRChat.Common
    
    
    Namespace SignalRChat
    Public Class ChatHub
    Inherits Hub
    #Region "Data Members"
    
    
    Shared ConnectedUsers As New List(Of UserDetail)()
    Shared CurrentMessage As New List(Of MessageDetail)()
    
    
    #End Region
    
    
    #Region "Methods"
    
    
    Public Sub Connect(userName As String)
    Dim id = Context.ConnectionId
    
    
    
    
    If ConnectedUsers.Where(Function(x) x.ConnectionId = id).Count = 0 Then
    ConnectedUsers.Add(New UserDetail() With { _
    .ConnectionId = id, _
    .UserName = userName _
    })
    
    
    ' send to caller
    Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage)
    
    
    ' send to all except caller client
    
    
    Clients.AllExcept(id).onNewUserConnected(id, userName)
    End If
    
    
    End Sub
    
    
    Public Sub SendMessageToAll(userName As String, message As String)
    ' store last 100 messages in cache
    AddMessageinCache(userName, message)
    
    
    ' Broad cast message
    Clients.All.messageReceived(userName, message)
    End Sub
    
    
    Public Sub SendPrivateMessage(toUserId As String, message As String)
    
    
    Dim fromUserId As String = Context.ConnectionId
    
    
    Dim toUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = toUserId)
    Dim fromUser = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = fromUserId)
    
    
    If toUser IsNot Nothing AndAlso fromUser IsNot Nothing Then
    ' send to 
    Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message)
    
    
    ' send to caller user
    Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message)
    End If
    
    
    End Sub
    
    
    Public Overrides Function OnDisconnected(stopCalled As Boolean) As Threading.Tasks.Task
    
    
    Dim item = ConnectedUsers.FirstOrDefault(Function(x) x.ConnectionId = Context.ConnectionId)
    If item IsNot Nothing Then
    ConnectedUsers.Remove(item)
    Dim id = Context.ConnectionId
    
    
    Clients.All.onUserDisconnected(id, item.UserName)
    End If
    
    
    Return MyBase.OnDisconnected(stopCalled)
    End Function
    
    
    
    
    
    
    #End Region
    
    
    #Region "private Messages"
    
    
    Private Sub AddMessageinCache(userName As String, message As String)
    CurrentMessage.Add(New MessageDetail() With { _
    .UserName = userName, _
    .Message = message _
    })
    
    
    If CurrentMessage.Count > 100 Then
    CurrentMessage.RemoveAt(0)
    End If
    End Sub
    
    
    #End Region
    End Class
    
    
    End Namespace
    





    Monday, February 29, 2016 9:34 AM
  • User61956409 posted

    Hi Been,

    i used that code of image only for tried because i'm not an expert. Could you post a correct example for resolve this problem???

    I don’t have a complete working sample for your problem, but I could share some idea with you. To display online users with image avatar, you could map a user to the connection id and persist that mapping, and you could specify user’s avatar for each user (connection id). Then you could get and display users with their avatars. For more information about mapping SignalR users to connections, please check this link.

    http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections

    Best Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 1, 2016 8:16 AM
  • User-1814126548 posted
    Ok then I'll try and I'll make us know.
    Thank you.
    Tuesday, March 1, 2016 12:01 PM