Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

SignalR Chat App With ASP.NET WebForm And BootStrap - Part Two

0.00/5 (No votes)
2 Jan 2018 1  
Integration of SignalR with ASP.NET C# WebForm Application in Real-Time Chat Application

Introduction

In the previous article, we learned to create a real-time chat application using SignalR. Till now, we learned Integration of SignalR, Bootstrap and creation of group chat, so in this article, we are going to add some features like Private Chat, Notification System, Message Counting, and Clear Chat function, etc.

Our application will become more interactive after adding these features and you will learn more about SignalR and Jquery, how we can create a function in HUB class or how we can call these Hub class’s function form Client side using Jquery, how we can dynamically generate HTML Code using Jquery and append these codes with already existing HTML Div.

For those who missed the previous article, please refer to the previous article “SignalR Chat App With ASP.NET WebForm And BootStrap - Part One” and also download the project file, so we will continue with the last article’s project file.

Creation of Private Chat

As we are going to continue with our last project, first we are going to add “Private Chat”. We already have the Online User List, so here we have to create HTML design for private chat and later, we will use this design for private chat, so we will add the new DIV after the group chat DIV, the HTM Code will be:

<div class="row">
    <div class="col-md-12">
        <div class="row" id="PriChatDiv">
        </div>
        <textarea class="form-control" style="visibility: hidden;"></textarea>
        <!--/.private-chat -->
    </div>
</div>

After adding the above HTML code in your design file, we will write code for creating and opening private chat box. We have already given a link to the username with their respective IDs, so on the basis of User Id, it will create and open the private chat box. By adding the below code in our Jquery function name “AddUser”:

 var UserLink = $('<a id="' + id +
'" class="user" >' + name + '<a>');
                $(code).click(function () {

                    var id = $(UserLink).attr('id');

                    if (userId != id) {
                        var ctrId = 'private_' + id;
                        OpenPrivateChatBox(chatHub, id, ctrId, name);
                    }
                });

Now we will write the Jquery code for generating the dynamic HTML Code for Private Chat DIV and it will append inside the “PriChatDivDiv. It creates the Private Chat Box on the basis of User Ids generated by the HUB, so it will open a separate Chat Box for each user while clicking on their username in the online User List.

JavaScript Code for Creation and Opening the Private Chat DIV

// Creation and Opening Private Chat Div
        function OpenPrivateChatBox(chatHub, userId, ctrId, userName) {

            var PWClass = $('#PWCount').val();

            if ($('#PWCount').val() == 'info')
                PWClass = 'danger';
            else if ($('#PWCount').val() == 'danger')
                PWClass = 'warning';
            else
                PWClass = 'info';

            $('#PWCount').val(PWClass);
            var div1 = ' <div class="col-md-4"> <div  id="' + ctrId +
             '" class="box box-solid box-' + PWClass + ' direct-chat direct-chat-' + PWClass + '">' +
                '<div class="box-header with-border">' +
                ' <h3 class="box-title">' + userName + '</h3>' +

                ' <div class="box-tools pull-right">' +
                ' <span data-toggle="tooltip" id="MsgCountP" title="0 New Messages"
                '  class="badge bg-' + PWClass + '">0</span>' +
                ' <button type="button" class="btn btn-box-tool" data-widget="collapse">' +
                '    <i class="fa fa-minus"></i>' +
                '  </button>' +
                '  <button id="imgDelete" type="button" class="btn btn-box-tool" data-widget="remove">
                '  <i class="fa fa-times"></i></button></div></div>' +

                ' <div class="box-body">' +
                ' <div id="divMessage" class="direct-chat-messages">' +

                ' </div>' +

                '  </div>' +
                '  <div class="box-footer">' +

                '    <input type="text" id="txtPrivateMessage"
                '     name="message" placeholder="Type Message ..." class="form-control"  />' +

                '  <div class="input-group">' +
                '    <input type="text" name="message" placeholder="Type Message ..."
                '     class="form-control" style="visibility:hidden;" />' +
                '   <span class="input-group-btn">' +
                '          <input type="button" id="btnSendMessage"
                '           class="btn btn-' + PWClass + ' btn-flat" value="send" />' +
                '   </span>' +
                '  </div>' +

                ' </div>' +
                ' </div></div>';

            var $div = $(div1);

            // Closing Private Chat Box
            $div.find('#imgDelete').click(function () {
                $('#' + ctrId).remove();
            });

            // Send Button event in Private Chat
            $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 on Enter Button
            $div.find("#txtPrivateMessage").keypress(function (e) {
                if (e.which == 13) {
                    $div.find("#btnSendMessage").click();
                }
            });

            // Clear Message Count on Mouse over
            $div.find("#divMessage").mouseover(function () {

                $("#MsgCountP").html('0');
                $("#MsgCountP").attr("title", '0 New Messages');
            });

            // Append private chat div inside the main div
            $('#PriChatDiv').append($div);
        }

In the above code, we are creating a div for private chat, so here is a button for closing chat box, and also we are displaying the number of new messages in message counter which is located at the header of the chat box. And also clearing the message counter on mouse over. We are applying scroll bar to the chat div if the number of messages exceed and it will take more space in div. Also applying different CSS style to the div for each time while opening the Chat box.

Code for Private Chat Message Send

chatHub.client.sendPrivateMessage = 
function (windowId, fromUserName, message, userimg, CurrentDateTime) {

    var ctrId = 'private_' + windowId;
    if ($('#' + ctrId).length == 0) {
    
        OpenPrivateChatBox(chatHub, windowId, ctrId, fromUserName, userimg);
        
    }
    
    var CurrUser = $('#hdUserName').val();
    var Side = 'right';
    var TimeSide = 'left';
    
    if (CurrUser == fromUserName) {
        Side = 'left';
        TimeSide = 'right';
        
    }
    else {
        var Notification = 'New Message From ' + fromUserName;
        IntervalVal = setInterval("ShowTitleAlert('SignalR Chat App', 
                      '" + Notification + "')", 800);
        
        var msgcount = $('#' + ctrId).find('#MsgCountP').html();
        msgcount++;
        $('#' + ctrId).find('#MsgCountP').html(msgcount);
        $('#' + ctrId).find('#MsgCountP').attr("title", msgcount + ' New Messages');
    }
    
    var divChatP = '<div class="direct-chat-msg ' + Side + '">' +
        '<div class="direct-chat-info clearfix">' +
        '<span class="direct-chat-name pull-' + Side + '">' + fromUserName + 
        '</span>' +
        '<span class="direct-chat-timestamp pull-' + TimeSide + '"">' + CurrentDateTime + 
        '</span>' +
        '</div>' +
        
        ' <img class="direct-chat-img" src="' + userimg + 
        '" alt="Message User Image">' +
        ' <div class="direct-chat-text" >' + message + 
        '</div> </div>';
        
    $('#' + ctrId).find('#divMessage').append(divChatP);
    
    var htt = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
    $('#' + ctrId).find('#divMessage').slimScroll({
        height: htt
    });
}

Here, we are calling the “SendPrivateMessage” function through the JavaScript which we have added in Hub Class that we have already added with the name of “ChatHub.cs”.

Code for the ChatHub.cs Class File

public void SendPrivateMessage(string toUserId, string message)
{
    string fromUserId = Context.ConnectionId;
    var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId);
    var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);
    if (toUser != null && fromUser != null)
    {
        string CurrentDateTime = DateTime.Now.ToString();
        string UserImg = GetUserImage(fromUser.UserName);
        // send to
        Clients.Client(toUserId).sendPrivateMessage
             (fromUserId, fromUser.UserName, message, UserImg, CurrentDateTime);
        // send to caller user
        Clients.Caller.sendPrivateMessage
             (toUserId, fromUser.UserName, message, UserImg, CurrentDateTime);
    }
}

Here, the integration of private chat is completed now, run the project and see the output, the output will look as shown below:

Creation of Title Bar Alert

Here, we are going to integrate Title bar alert system, same like Facebook, when we received the new message from online users, it will display the notification on page title bar, here we have simply applied notification by using JavaScript:

IntervalVal = setInterval("ShowTitleAlert
('SignalR Chat App', '" + Notification + "')", 1000);

Here, we are “ShowTitleAlert” function in an interval which we are setting 1000, so it will display the message alert in set interval period. And it will break / clear the interval on focusing on the window event.

// Show Title Alert
        function ShowTitleAlert(newMessageTitle, pageTitle) {
            if (document.title == pageTitle) {
                document.title = newMessageTitle;
            }
            else {
                document.title = pageTitle;
            }
        }

Clear Chat History

User can clear the old chat history if he wants, for clearing chat history, we added the clear chat icon on the top of the group chat box header, in private chat, we can clear the chat by closing the chat box, but in group chat, we cannot close the chat box, so here we have given the option for clearing chat.

Create a function for Clear chat in Hub class:

// Clear Chat History
        public void clearTimeout()
        {
            CurrentMessage.Clear();
        }

JQuery code for clear chat, here we are calling the function from Class Hub and clearing Chat div:

// Clear Chat
       $('#btnClearChat').click(function () {

           var msg = $("#divChatWindow").html();

           if (msg.length > 0) {
               chatHub.server.clearTimeout();
               $('#divChatWindow').html('');

           }
       });

Output

Now run the project and the final output will look like below:

Conclusion

Here, you will learn the integration of Private Chat with SignalR and creating title Bar alert using JavaScript, adding Message Counter, we have created function first in HUB class, then call these function in Jquery functions, dynamically generate HTML Code and append these HTML code with existing HTM DIV. Applying CSS different CSS Style each time while creating the ChatBox. So this is the second part of “SignalR Chat App” Tutorial, I will show you the integration of “Emoji” in chat for making our chat application more interactive in my next article, also we will integrate sending attachment through the chat sending image file in chat and download or display image in chat.

Hope this will help you and you like this article. I have attached the project source code. You can download the source code for your reference and to see the complete source. Thank you for reading...

Please give your valuable feedback in the comments section.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here