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

Introduction

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

Our application will become more interactive after adding these feature and you will learn more about SignalR and Jquery, how we can create a function in HUB class or how can we call these Hub class’s function form Client side using Jquery and how we can dynamically generate HTML Code using Jquery and append these codes with already exist in 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,

  1. <div class="row">  
  2.     <div class="col-md-12">  
  3.         <div class="row" id="PriChatDiv">  
  4.         </div>  
  5.         <!--/.private-chat -->  
  6.     </div>  
  7. </div>  
After adding the above html code in your design file, we will write code for creating and opening private chat box.  We were already given a link to the username with their respective ID’s, so on the basis of User Id it will create and open the private chat box. By adding below code in our Jquery function name “AddUser”,
  1. var UserLink = $('<a id="' + id + '" class="user" >' + name + '<a>');  
  2.                 $(code).click(function () {  
  3.   
  4.                     var id = $(UserLink).attr('id');  
  5.   
  6.                     if (userId != id) {  
  7.                         var ctrId = 'private_' + id;  
  8.                         OpenPrivateChatBox(chatHub, id, ctrId, name);  
  9.   
  10.                     }  
  11.   
  12.                 });  
Now we will write the Jquery code for generating the dynamic HTML Code for Private Chat DIV. and it will append inside the “PriChatDiv” Div. Its Create the Private Chat Box on the basis of User Ids generated by the HUB, so it will open separate Chat Box for each user while clicking on their username in online User List. JavaScript Code for Creation and Opening the Private Chat DIV,
  1. // Creation and Opening Private Chat Div  
  2. function OpenPrivateChatBox(chatHub, userId, ctrId, userName) {  
  3.   
  4.     var PWClass = $('#PWCount').val();  
  5.   
  6.     if ($('#PWCount').val() == 'info')  
  7.         PWClass = 'danger';  
  8.     else if ($('#PWCount').val() == 'danger')  
  9.         PWClass = 'warning';  
  10.     else  
  11.         PWClass = 'info';  
  12.   
  13.     $('#PWCount').val(PWClass);  
  14.     var div1 = ' <div class="col-md-4"> <div  id="' + ctrId + '" class="box box-solid box-' + PWClass + ' direct-chat direct-chat-' + PWClass + '">' +  
  15.         '<div class="box-header with-border">' +  
  16.         ' <strong class="box-title">' + userName + '</strong>' +  
  17.   
  18.         ' <div class="box-tools pull-right">' +  
  19.         ' <span data-toggle="tooltip" id="MsgCountP" title="0 New Messages" class="badge bg-' + PWClass + '">0</span>' +  
  20.         ' <button type="button" class="btn btn-box-tool" data-widget="collapse">' +  
  21.         '    <i class="fa fa-minus"></i>' +  
  22.         '  </button>' +  
  23.         '  <button id="imgDelete" type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button></div></div>' +  
  24.   
  25.         ' <div class="box-body">' +  
  26.         ' <div id="divMessage" class="direct-chat-messages">' +  
  27.   
  28.         ' </div>' +  
  29.   
  30.         '  </div>' +  
  31.         '  <div class="box-footer">' +  
  32.   
  33.   
  34.         '    <input type="text" id="txtPrivateMessage" name="message" placeholder="Type Message ..." class="form-control"  />' +  
  35.   
  36.         '  <div class="input-group">' +  
  37.         '    <input type="text" name="message" placeholder="Type Message ..." class="form-control" style="visibility:hidden;" />' +  
  38.         '   <span class="input-group-btn">' +  
  39.         '          <input type="button" id="btnSendMessage" class="btn btn-' + PWClass + ' btn-flat" value="send" />' +  
  40.         '   </span>' +  
  41.         '  </div>' +  
  42.   
  43.         ' </div>' +  
  44.         ' </div></div>';  
  45.   
  46.   
  47.   
  48.     var $div = $(div1);  
  49.   
  50.     // Closing Private Chat Box  
  51.     $div.find('#imgDelete').click(function () {  
  52.         $('#' + ctrId).remove();  
  53.     });  
  54.   
  55.     // Send Button event in Private Chat  
  56.     $div.find("#btnSendMessage").click(function () {  
  57.   
  58.         $textBox = $div.find("#txtPrivateMessage");  
  59.   
  60.         var msg = $textBox.val();  
  61.         if (msg.length > 0) {  
  62.             chatHub.server.sendPrivateMessage(userId, msg);  
  63.             $textBox.val('');  
  64.         }  
  65.     });  
  66.   
  67.     // Text Box event on Enter Button  
  68.     $div.find("#txtPrivateMessage").keypress(function (e) {  
  69.         if (e.which == 13) {  
  70.             $div.find("#btnSendMessage").click();  
  71.         }  
  72.     });  
  73.   
  74.     // Clear Message Count on Mouse over             
  75.     $div.find("#divMessage").mouseover(function () {  
  76.   
  77.         $("#MsgCountP").html('0');  
  78.         $("#MsgCountP").attr("title"'0 New Messages');  
  79.     });  
  80.   
  81.     // Append private chat div inside the main div  
  82.     $('#PriChatDiv').append($div);  

In 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 message 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 exceeds it and it will take more space in div. Also applying different CSS styles to the div each time while opening the opening the Chat box.

Code for Private Chat Message Send
  1. chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message, userimg, CurrentDateTime) {  
  2.   
  3.     var ctrId = 'private_' + windowId;  
  4.     if ($('#' + ctrId).length == 0) {  
  5.   
  6.         OpenPrivateChatBox(chatHub, windowId, ctrId, fromUserName, userimg);  
  7.   
  8.     }  
  9.   
  10.     var CurrUser = $('#hdUserName').val();  
  11.     var Side = 'right';  
  12.     var TimeSide = 'left';  
  13.   
  14.     if (CurrUser == fromUserName) {  
  15.         Side = 'left';  
  16.         TimeSide = 'right';  
  17.   
  18.     }  
  19.     else {  
  20.         var Notification = 'New Message From ' + fromUserName;  
  21.         IntervalVal = setInterval("ShowTitleAlert('SignalR Chat App', '" + Notification + "')", 800);  
  22.   
  23.         var msgcount = $('#' + ctrId).find('#MsgCountP').html();  
  24.         msgcount++;  
  25.         $('#' + ctrId).find('#MsgCountP').html(msgcount);  
  26.         $('#' + ctrId).find('#MsgCountP').attr("title", msgcount + ' New Messages');  
  27.     }  
  28.   
  29.     var divChatP = '<div class="direct-chat-msg ' + Side + '">' +  
  30.         '<div class="direct-chat-info clearfix">' +  
  31.         '<span class="direct-chat-name pull-' + Side + '">' + fromUserName + '</span>' +  
  32.         '<span class="direct-chat-timestamp pull-' + TimeSide + '"">' + CurrentDateTime + '</span>' +  
  33.         '</div>' +  
  34.   
  35.         ' <img class="direct-chat-img" src="' + userimg + '" alt="Message User Image">' +  
  36.         ' <div class="direct-chat-text" >' + message + '</div> </div>';  
  37.   
  38.     $('#' + ctrId).find('#divMessage').append(divChatP);  
  39.   
  40.     var htt = $('#' + ctrId).find('#divMessage')[0].scrollHeight;  
  41.     $('#' + ctrId).find('#divMessage').slimScroll({  
  42.         height: htt  
  43.     });  

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
  1. public void SendPrivateMessage(string toUserId, string message)  
  2. {  
  3.   
  4.     string fromUserId = Context.ConnectionId;  
  5.   
  6.     var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId);  
  7.     var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);  
  8.   
  9.     if (toUser != null && fromUser != null)  
  10.     {  
  11.         string CurrentDateTime = DateTime.Now.ToString();  
  12.         string UserImg = GetUserImage(fromUser.UserName);  
  13.         // send to   
  14.         Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message, UserImg, CurrentDateTime);  
  15.   
  16.         // send to caller user  
  17.         Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message, UserImg, CurrentDateTime);  
  18.     }  
  19.   

Here the integration of private chat is completed now, run the project and see the output, the output will look like as follows,

 

Creation of Title bar Alert

Here we are going to integrate Title bar alert system 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,

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

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

  1. // Show Title Alert  
  2.        function ShowTitleAlert(newMessageTitle, pageTitle) {  
  3.            if (document.title == pageTitle) {  
  4.                document.title = newMessageTitle;  
  5.            }  
  6.            else {  
  7.                document.title = pageTitle;  
  8.            }  
  9.        } 
 
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 of clearing chat.

Create a function for clearing chat in Hub Class,

  1. // Clear Chat History  
  2.         public void clearTimeout()  
  3.         {  
  4.             CurrentMessage.Clear();  
  5.         }  
JQuery code for clear chat, here we are calling the function from Class Hub and clearing Chat div,
  1. // Clear Chat  
  2.         $('#btnClearChat').click(function () {  
  3.   
  4.             var msg = $("#divChatWindow").html();  
  5.   
  6.             if (msg.length > 0) {  
  7.                 chatHub.server.clearTimeout();  
  8.                 $('#divChatWindow').html('');  
  9.   
  10.             }  
  11.         }); 
 
 
Output

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

Conclusion

Here you will learn the integration of Private Chat with SignalR and how to create a  title Bar alert using JavaScript. We have created function first in HUB class then calling these functions in Jquery functions, dynamically generated HTML Code and appended these HTML codes with existing HTML DIV and applying different CSS Styles 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 more interactive chat applications in my next article, also we will integrate sending attachments through the chat sending image file in chat and downloading or displaying image in chat.

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

Please give your valuable feedback in the comment section.

<<Click here for previous part

Author
Altaf Ansari
0 1.4k 27k
Next » SignalR Chat App With ASP.NET WebForm And BootStrap - Part Three