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

Introduction

In a previous article we have learned how to create a real-time chat application using SignalR and Bootstrap. So far we learned creation of group chat, Creation of Private Chat, Title Bar Notification Alert system, Message Count and Clear Chat History. And now we are going to learn the most trending feature in Chat Application which is “Emoji” or “Smiley” which makes our application more interactive. And another important and useful feature is sending attachments through chat, in file attachments we can send pictures/images, Word, PDF, Excel and text files. And also we can show/download the pictures/document files.

Emoji is a small digital image or icon used to express an idea or emotion in electronic communication, emoji livens up your text messages with tiny smiley faces. We are going to learn implementation of Emoji in the easiest way. There are a number of Emoji Package available, but here we are going to integrate “EmojinOne”. In my opinion this is the best smiley package which is easily available on the web. And also we are going to implement “SlimScroll” Jquey Plugin which provides interactive content scrollbar.

For those who missed the First article please refer to the article “SignalR Chat App With ASP.NET WebForm And BootStrap - Part One” and you can also download the project file.

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

Integration of Emoji

As we are going to continue with our last project file, first we will integrate the Emoji, and the following reference files are required:

  1. emojionearea.js
  2. emojionearea.css
  3. emojionearea.min.css

You can download Emoji Reference files which are available on cdnjs.com. Add CSS files are in “Content” directory and Javascript files in “Scripts” Folder. After adding these files in your project, add these files in “Chat.aspx” Design Page inside the header tag.

  1. <!--EmojiOneArea -->  
  2. <link href="Content/emojionearea.min.css" rel="stylesheet" />  
  3. <script src="Scripts/emojionearea.js"></script> 

After adding these files, now we have to define Emoji area from where we can add emoji, so here we are defining message textbox as Emoji area. Simply write the Jquery function as follow:

  1. $(function () {  
  2. $("#txtMessage").emojioneArea();  
  3. }); 

Now run your project you will see the Emoji Box with Message Textbox looks like as follow:

 

We have to apply the same way as Private Chat Box; we are creating a private chat Box Dynamically and embedding this code using Jquery, so we have to define the code dynamically because each time the Id of ChatBox Div will change so on the basis of dynamic id we have to find the Message Textbox and apply the function:

  1. $('#PriChatDiv').append($div);  
  2. var msgTextbox = $div.find("#txtPrivateMessage");  
  3. $(msgTextbox).emojioneArea();  

Again run the project and the see the output Emoji will apply in private chat box too. Now we have to parse these emojis in our chat, when we received the message which contains Emoji it gets parsed, there are a few methods of conversion / parsing of emojis and here we are using “.unicodeToImage(str)” method for parsing emoji, it will convert smiley Unicode into image.

  1. function ParseEmoji(div) {  
  2. var input = $(div).html();  
  3. var output = emojione.unicodeToImage(input);  
  4. $(div).html(output);  

Here we are using online Emoji image resources, if you want to use these resources locally, then you have to download the EmojiOne Smiley Package and change the resource path in “emojionearea.js” file.

Example

  1. //var cdn_base = "http://DomainName/Emoji/dist/emojione/";  
  2. var cdn_base = "https://cdnjs.cloudflare.com/ajax/libs/emojione/";  
  3. // var cdn_base = "http://localhost:49251/Emoji/dist/emojione/"; 

 

If we use these resources locally it will increase your app performance by decreasing the loading time of images. The output after adding Emoji will look like as follow:



Adding Feature of Sending Picture / File Attachment

Send Picture files through the chat, it will add an extraordinary feature to our app, we can send images, words, documents, Text files, PDF Files and Excel files. Here we are adding separate button for send attachment, we will use Ajax Tool “AsyncFileUpload”. So here we need to add AjaxToolkit in our project reference, we have already explained adding package in project using Nuget Package Manager in previous article. So add the package using Nuget Package Manager:

PM> Install-Package AjaxControlToolkit -Version 17.1.1

Now write the code for Attachment button. As we are using AsyncFileUpload for file upload but we are not showing it as we are wrapping File Upload inside the button, so user can only see the button and when it clicks on attachment button FileUpload events will be fired, the design code for attachment button is:

  1.  <span class="upload-btn-wrapper">  
  2.   
  3. <button id="btnFile" class="btn btn-default btn-flat"><i class="glyphicon glyphicon-paperclip"></i></button>  
  4.   
  5. <ajaxToolkit:AsyncFileUpload OnClientUploadComplete="uploadComplete" runat="server" ID="AsyncFileUpload1" ThrobberID="imgLoader" OnUploadedComplete="FileUploadComplete" OnClientUploadStarted="uploadStarted" />  
  6.   
  7. </span> 

There are Three Events generated by the “AsyncFileUpload” while clicking on FileUpload, in which two events are Client Side event and one is Server Side event, “OnUploadedComplete” is the server side event where we are storing files in a particular directory:

  1. protected void FileUploadComplete(object sender, EventArgs e)  
  2. {  
  3.    string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);  
  4.    AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + filename);  
  5. }  
First it will call client side event “OnClientUploadStarted”, as we are using temporary HTML image tag for display and loading the image, while loading the image we are displaying it for the time being for getting image properties which we are using further while displaying image in chat, so in this function we are clearing temporary image path:
  1. function uploadStarted() {  
  2.   
  3. $get("imgDisplay").style.display = "none";  
  4.   
  5. }  
There are two functions where we are validating upload files by checking the extension of requested file, this function validates only Image and Document files, you can add some more extensions as per your need, code for File Validation:
  1. function IsValidateFile(fileF) {  
  2.            var allowedFiles = [".doc"".docx"".pdf"".txt"".xlsx",".xls"".png"".jpg"".gif"];  
  3.            var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");  
  4.            if (!regex.test(fileF.toLowerCase())) {  
  5.                alert("Please upload files having extensions: " + allowedFiles.join(', ') + " only.");  
  6.                return false;  
  7.            }  
  8.            return true;  
  9. }  
Here we are separating Image files and document files as we are going to assign separate design for both, for image files we are showing image preview in chat, and for document files we just show the document icon:
  1. function IsImageFile(fileF) {  
  2.     var ImageFiles = [".png"".jpg"".gif"];  
  3.     var regex = new RegExp("(" + ImageFiles.join('|') + ")$");  
  4.     if (!regex.test(fileF.toLowerCase())) {  
  5.         return false;  
  6.     }  
  7.     return true;  
  8. }  
After uploading the image/ document file we displayed in chat, and also showing file properties such as file size image dimension and file type, user can view the full image and also can download the image / document.
  1. function uploadComplete(sender, args) {  
  2.     var imgDisplay = $get("imgDisplay");  
  3.     imgDisplay.src = "images/loading.gif";  
  4.     imgDisplay.style.cssText = "";  
  5.     var img = new Image();  
  6.     img.onload = function () {  
  7.         imgDisplay.style.cssText = "Display:none;";  
  8.         imgDisplay.src = img.src;  
  9.     };  
  10.   
  11.         imgDisplay.src = "<%# ResolveUrl(UploadFolderPath) %>" + args.get_fileName();  
  12.     var chatHub = $.connection.chatHub;  
  13.     var userName = $('#hdUserName').val();  
  14.     var date = GetCurrentDateTime(new Date());  
  15.     var sizeKB = (args.get_length() / 1024).toFixed(2);  
  16.   
  17.     var msg1;  
  18.   
  19.     if (IsValidateFile(args.get_fileName())) {  
  20.         if (IsImageFile(args.get_fileName())) {  
  21.             msg1 =  
  22.                 '<div class="box-body">' +  
  23.                 '<div class="attachment-block clearfix">' +  
  24.                 '<a><img id="imgC" style="width:100px;" class="attachment-img" src="' + imgDisplay.src + '" alt="Attachment Image"></a>' +  
  25.                 '<div class="attachment-pushed"> ' +  
  26.                 '<h4 class="attachment-heading"><i class="fa fa-image">  ' + args.get_fileName() + ' </i></h4> <br />' +  
  27.                 '<div id="at" class="attachment-text"> Dimensions : ' + imgDisplay.height + 'x' + imgDisplay.width + ', Type: ' + args.get_contentType() +  
  28.   
  29.                 '</div>' +  
  30.                 '</div>' +  
  31.                 '</div>' +  
  32.                 '<a id="btnDownload" href="' + imgDisplay.src + '" class="btn btn-default btn-xs" download="' + args.get_fileName() + '"><i class="fa fa fa-download"></i> Download</a>' +  
  33.                 '<button type="button" id="ShowModelImg"  value="' + imgDisplay.src + '"  class="btn btn-default btn-xs"><i class="fa fa-camera"></i> View</button>' +  
  34.                 '<span class="pull-right text-muted">File Size : ' + sizeKB + ' Kb</span>' +  
  35.                 '</div>';  
  36.         }  
  37.         else {  
  38.   
  39.             msg1 =  
  40.                 '<div class="box-body">' +  
  41.                 '<div class="attachment-block clearfix">' +  
  42.                 '<a><img id="imgC" style="width:100px;" class="attachment-img" src="images/file-icon.png" alt="Attachment Image"></a>' +  
  43.                 '<div class="attachment-pushed"> ' +  
  44.                 '<h4 class="attachment-heading"><i class="fa fa-file-o">  ' + args.get_fileName() + ' </i></h4> <br />' +  
  45.                 '<div id="at" class="attachment-text"> Type: ' + args.get_contentType() +  
  46.   
  47.                 '</div>' +  
  48.                 '</div>' +  
  49.                 '</div>' +  
  50.                 '<a id="btnDownload" href="' + imgDisplay.src + '" class="btn btn-default btn-xs" download="' + args.get_fileName() + '"><i class="fa fa fa-download"></i> Download</a>' +  
  51.                 '<a href="' + imgDisplay.src + '" target="_blank" class="btn btn-default btn-xs"><i class="fa fa-camera"></i> View</a>' +  
  52.                 '<span class="pull-right text-muted">File Size : ' + sizeKB + ' Kb</span>' +  
  53.                 '</div>';  
  54.         }  
  55.         chatHub.server.sendMessageToAll(userName, msg1, date);  
  56.                  
  57.     }  
  58.   
  59.   
  60.     imgDisplay.src = '';  

When we click view button the image file will open in Modal popup, for this we are using Booststrap Modal, we are passing image path in button value and applying this path to the image inside the modal and then showing the modal.

  1. $(document).on('click''#ShowModelImg'function () {  
  2.     $get("ImgModal").src = this.value;  
  3.     $('#ShowPictureModal').modal('show');  
  4. }); 

When the number of messages increases in ChatBox the default browser vertical scrollbar will apply to the Chatbox, but here we will add a  stylish scrollbar so we will add Jquery “SlimScroll” in Chatbox. We will add this through the Nuget Package Manager:

PM> Install-Package Jquery.slimScroll -Version 1.3.1

Add SlimScroll JavaScript file in header tag of design page.

<!--Jquery slimScroll -->
<script type="text/javascript" src="Scripts/jquery.slimscroll.min.js"></script>

  1. // Apply Slim Scroll Bar in Group Chat Box  
  2.   
  3. $('#divChatWindow').slimScroll({  
  4.   
  5. height: height  
  6.   
  7. }); 
  1. // Apply Slim Scroll Bar in Private Chat Box  
  2.   
  3. var ScrollHeight = $('#' + ctrId).find('#divMessage')[0].scrollHeight;  
  4.   
  5. $('#' + ctrId).find('#divMessage').slimScroll({  
  6.   
  7. height: ScrollHeight  
  8.   
  9. });  
We have applied SlimScroll in both chat boxes in private chat box as well as in group chat box, after applying you can see the effect of SlimScroll looks like:



Output

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

 

Conclusion

Here we learned the integration of Emoji in Private Chat and Group Chat with SignalR and sending attachment through chat by using Ajax Toolkit component “AsyncFileUpload”. So we learned the integration of AsyncFileUpload and its concepts such as client side events and server side events. And also Getting file Properties and displaying uploaded file properties, displaying image file in Modal popup, downloading files and also Jquery Plugin “SlimScroll” Integration in Scroll bar. So this is the final article of Chat application.

I hope this will help you and you lke this article, if you think we can add more features in this project please make a suggestion. If I like it I will write another article with some more new features, please don’t forget to download attached Project source code for your reference and to see the complete source, thank you for reading...

Please give your valuable feedback in the comment section.

Up Next
    Ebook Download
    View all
    Learn
    View all