Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (38 votes)
18 Sep 2018CPOL6 min read 59.6K   5.5K   68   31
SignalR Real-Time ChatApp with Emoji / Smiley and sending file attachment

Introduction

In the previous article, we learned how to create a real-time chat application using SignalR and Bootstrap, till now 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 sending attachments through chat, in file attachment we can send pictures/images, Word, PDF, Excel and text file. 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 Packages 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” Jquery 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. The following reference files are required:

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

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

HTML
<!--EmojiOneArea -->
<link href="Content/emojionearea.min.css" rel="stylesheet" />
<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 writing the Jquery function as follows:

JavaScript
$(function () {
       $("#txtMessage").emojioneArea();
 });

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

Image 1

We have to apply the same with Private Chat Box; we are creating 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:

JavaScript
$('#PriChatDiv').append($div);
var msgTextbox = $div.find("#txtPrivateMessage");
$(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 Emojis, it get parsed, there are few methods of conversion / parsing of emojis here we are using “.unicodeToImage(str)” method for parsing emoji, it will convert smiley Unicode into image.

JavaScript
function ParseEmoji(div) {
            var input = $(div).html();
            var output = emojione.unicodeToImage(input);
            $(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:

JavaScript
//var cdn_base = "http://DomainName/Emoji/dist/emojione/";
  var cdn_base = "https://cdnjs.cloudflare.com/ajax/libs/emojione/";
// 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 follows:

Image 2

Adding Feature of Sending Picture / File Attachment

Send Picture files through the chat, it will add an extra ordinary feature to our app, we can send images, word, document, Text file, PDF File and Excel file. Here, we are adding a 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 the 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 fired, the design code for attachment button:

HTML
<span class="upload-btn-wrapper">

     <button id="btnFile" class="btn btn-default btn-flat">
     <i class="glyphicon glyphicon-paperclip"></i></button>

       <ajaxToolkit:AsyncFileUpload OnClientUploadComplete="uploadComplete" 
        runat="server" ID="AsyncFileUpload1" ThrobberID="imgLoader" 
        OnUploadedComplete="FileUploadComplete" OnClientUploadStarted="uploadStarted" />

   </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:

C#
protected void FileUploadComplete(object sender, EventArgs e)
{
    string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
    AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + filename);
}

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:

JavaScript
function uploadStarted() {
   $get("imgDisplay").style.display = "none";
}

There are two functions where we are validating upload file 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:

JavaScript
function IsValidateFile(fileF) {
    var allowedFiles = [".doc", ".docx", ".pdf", ".txt", ".xlsx", ".xls", ".png", ".jpg", ".gif"];
    var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
    if (!regex.test(fileF.toLowerCase())) {
        alert("Please upload files having extensions: " + allowedFiles.join(', ') + " only.");
        return false;
    }
    return true;
}

Here, we are separating Image file and document file as we are going to assign separate design for both, for image file, we are showing image preview in chat, and for document file, we just showing the document icon:

JavaScript
function IsImageFile(fileF) {
    var ImageFiles = [".png", ".jpg", ".gif"];
    var regex = new RegExp("(" + ImageFiles.join('|') + ")$");
    if (!regex.test(fileF.toLowerCase())) {
        return false;
    }
    return true;
}

After uploading the image/ document file we displaying in chat, and also showing file properties such as file size image dimension and file type, user can view the full image also can download the image / document.

JavaScript
function uploadComplete(sender, args) {
    var imgDisplay = $get("imgDisplay");
    imgDisplay.src = "images/loading.gif";
    imgDisplay.style.cssText = "";
    var img = new Image();
    img.onload = function () {
        imgDisplay.style.cssText = "Display:none;";
        imgDisplay.src = img.src;
    };

    imgDisplay.src = "<%# ResolveUrl(UploadFolderPath) %>" + args.get_fileName();
var chatHub = $.connection.chatHub;
var userName = $('#hdUserName').val();
var date = GetCurrentDateTime(new Date());
var sizeKB = (args.get_length() / 1024).toFixed(2);

var msg1;

if (IsValidateFile(args.get_fileName())) {
    if (IsImageFile(args.get_fileName())) {
        msg1 =
            '<div class="box-body">' +
            '<div class="attachment-block clearfix">' +
            '<a><img id="imgC" style="width:100px;" class="attachment-img" src="' + 
                 imgDisplay.src + '" alt="Attachment Image"></a>' +
            '<div class="attachment-pushed"> ' +
            '<h4 class="attachment-heading"><i class="fa fa-image">  ' + 
              args.get_fileName() + ' </i></h4> <br />' +
            '<div id="at" class="attachment-text"> Dimensions : ' + 
              imgDisplay.height + 'x' + imgDisplay.width + ', Type: ' + args.get_contentType() +

            '</div>' +
            '</div>' +
            '</div>' +
            '<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>' +
            '<button type="button" id="ShowModelImg"  value="' + imgDisplay.src + '"  
              class="btn btn-default btn-xs"><i class="fa fa-camera"></i> View</button>' +
            '<span class="pull-right text-muted">File Size : ' + sizeKB + ' Kb</span>' +
            '</div>';
    }
    else {

        msg1 =
            '<div class="box-body">' +
            '<div class="attachment-block clearfix">' +
            '<a><img id="imgC" style="width:100px;" class="attachment-img" 
             src="images/file-icon.png" alt="Attachment Image"></a>' +
            '<div class="attachment-pushed"> ' +
            '<h4 class="attachment-heading"><i class="fa fa-file-o">  ' + 
             args.get_fileName() + ' </i></h4> <br />' +
            '<div id="at" class="attachment-text"> Type: ' + args.get_contentType() +

            '</div>' +
            '</div>' +
            '</div>' +
            '<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>' +
            '<a href="' + imgDisplay.src + '" target="_blank" 
              class="btn btn-default btn-xs"><i class="fa fa-camera"></i> View</a>' +
            '<span class="pull-right text-muted">File Size : ' + sizeKB + ' Kb</span>' +
            '</div>';
    }
    chatHub.server.sendMessageToAll(userName, msg1, date);

}
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.

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

When the number of messages increase in ChatBox, the default browser vertical scrollbar will apply to the Chatbox, but here we will add something stylish scrollbar so will add Jquery “SlimScroll” in Chatbox. 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.

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

// Apply Slim Scroll Bar in Group Chat Box
$('#divChatWindow').slimScroll({
     height: height
 });
JavaScript
// Apply Slim Scroll Bar in Private Chat Box
var ScrollHeight = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').slimScroll({
    height: ScrollHeight
});

We have to apply 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:

Image 3

Output

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

Image 4

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 event. And also getting file properties and displaying uploaded file properties, display 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.

Hope this will help you and you would like this article, if you think we can add more features in our project, please suggest... if I like it, I will write another article with some more new features. Please don’t forget to download the attached project source code for your reference and to see the complete source. Thank you for reading...

Please give your valuable feedback in the comments section below.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Prothious Engineering Services
India India
Team Leader .Net Developer, Working on Microsoft Technology Asp.Net, C#, SQL, Windows Application, Web Application.

Achievements :

13th January 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part One)


14th February 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part Two)

3rd March 2018 - Article of the Day - ASP.NET Community (SignalR Chat App With ASP.NET WebForm And BootStrap - Part Three)

Comments and Discussions

 
Questionpublic override Task OnDisconnected(bool stopCalled) Pin
krakoss@mail.ru18-Dec-23 23:27
professionalkrakoss@mail.ru18-Dec-23 23:27 
QuestionSend mesager when press key Enter Pin
Sơ Mi Tv2-Feb-21 15:07
Sơ Mi Tv2-Feb-21 15:07 
QuestionMobile version Pin
Member 102339510-Oct-20 3:56
Member 102339510-Oct-20 3:56 
Questionunable to extract file properly pl help Pin
paragp124-Jul-20 23:26
paragp124-Jul-20 23:26 
unable to extract  file properly pl help

jjhjhjhjhjhj

QuestionCan not able to extract zip file Pin
frabbibd7-May-19 0:22
frabbibd7-May-19 0:22 
QuestionEnter key and clear text not working Pin
Hien Nguyen16-Apr-19 0:10
Hien Nguyen16-Apr-19 0:10 
AnswerRe: Enter key and clear text not working Pin
Draret15-Oct-19 21:11
Draret15-Oct-19 21:11 
GeneralRe: Enter key and clear text not working Pin
Sơ Mi Tv2-Feb-21 19:43
Sơ Mi Tv2-Feb-21 19:43 
QuestionLink -> ¡¡download does not exist!! Pin
AndyHo25-Sep-18 5:13
professionalAndyHo25-Sep-18 5:13 
Questionlink to download code doesnt work Pin
skaus12321-Sep-18 0:04
professionalskaus12321-Sep-18 0:04 
Questionon page refresh or like website chat not on singlr page chat Pin
MukeshKamboj2819-Sep-18 21:12
MukeshKamboj2819-Sep-18 21:12 
QuestionCannot Download SOurce Code on Part 3 Pin
Member 1208234919-Sep-18 6:43
Member 1208234919-Sep-18 6:43 
BugAttached file is corrupted Pin
Member 104061362-Aug-18 6:16
Member 104061362-Aug-18 6:16 
GeneralRe: Attached file is corrupted Pin
Altaf Ansari18-Sep-18 22:18
Altaf Ansari18-Sep-18 22:18 
QuestionAttached file Pin
Member 1056749829-Jun-18 13:16
Member 1056749829-Jun-18 13:16 
QuestionDownload is corrupt Pin
Paul Groetzner10-Jun-18 5:40
Paul Groetzner10-Jun-18 5:40 
AnswerRe: Download is corrupt Pin
Altaf Ansari18-Sep-18 22:19
Altaf Ansari18-Sep-18 22:19 
QuestionGreat Job Pin
Member 137055352-Mar-18 8:11
Member 137055352-Mar-18 8:11 
AnswerRe: Great Job Pin
Altaf Ansari18-Sep-18 22:45
Altaf Ansari18-Sep-18 22:45 
QuestionFile Transfer thru the Private Chat Box Pin
George Vrakas13-Jan-18 20:28
George Vrakas13-Jan-18 20:28 
AnswerRe: File Transfer thru the Private Chat Box Pin
Altaf Ansari14-Jan-18 17:20
Altaf Ansari14-Jan-18 17:20 
GeneralRe: File Transfer thru the Private Chat Box Pin
George Vrakas16-Jan-18 4:34
George Vrakas16-Jan-18 4:34 
GeneralRe: File Transfer thru the Private Chat Box Pin
Shamsadali8-Apr-18 4:41
Shamsadali8-Apr-18 4:41 
GeneralMy vote of 5 Pin
Mou_kol10-Jan-18 21:09
Mou_kol10-Jan-18 21:09 
GeneralRe: My vote of 5 Pin
Altaf Ansari10-Jan-18 21:18
Altaf Ansari10-Jan-18 21:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.