SignalR Chat App With ASP.NET WebForm And BootStrap - Part Two
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 ChatAs 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>
- <!--/.private-chat -->
- </div>
- </div>
- 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);
- }
- });
- // 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">' +
- ' <strong class="box-title">' + userName + '</strong>' +
- ' <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 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- 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 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,
- 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.
- // Show Title Alert
- function ShowTitleAlert(newMessageTitle, pageTitle) {
- if (document.title == pageTitle) {
- document.title = newMessageTitle;
- }
- else {
- document.title = pageTitle;
- }
- }
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,
- // Clear Chat History
- public void clearTimeout()
- {
- CurrentMessage.Clear();
- }
- // Clear Chat
- $('#btnClearChat').click(function () {
- var msg = $("#divChatWindow").html();
- if (msg.length > 0) {
- chatHub.server.clearTimeout();
- $('#divChatWindow').html('');
- }
- });
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