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

In this article, I am going to share with you how to integrate and use SignalR with ASP.NET WebForm Application.

Here, we are going to learn to create a real-time chat application using SignalR, Bootstrap, and jQuery Modal Popup. There is a Login system for existing users and registration for new users. First, the user has to create an account and then they can login by using their login credentials, so the login authentications are required. After login, a user can participate in chat or discussion. The users can change their display picture after logging in the application. Before starting the explanation of functionality, please take a short overview about the SignalR as followed.

Overview of SignalR

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications, i.e., the ability to have server code push the content to connected clients instantly as it becomes available, rather than having the server to wait for a client to request new data.

SignalR can be used to add any sort of "real-time" web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see the new data, or the page implements long polling to retrieve the new data, it is a candidate for using SignalR.

Targeted Audience

The targeted audience is people with basic knowledge of ASP.NET and C#.

Explanation

Things to do,

  • Make an ASP.NET C# WebForm application.
  • Add the following packages through NuGet Package Manager.
    1. Bootstrap
    2. jQuery
    3. Font-awesome
    4. Microsoft.AspNet.SignalR
  • Create Startup.cs
  • Create ChatHub.cs
  • Create Login WebForm
  • Create Register WebFrom
  • Create Chat WebForm
  • Create a Database in SQL Server
  • Code

Create a New ASP.NET Web Project in C# and give it a suitable name as I gave the project name “SignalRChat”.

After creating the project, now, add Packages through the NuGet Package Manager like shown in the following image.

The package Console Manager will open. You can add any package just by writing Package Name and pressing the Enter button. It will get downloaded and installed in your project. You can see the reference files in your project references Or you can see the package files in their respective project directories.

Install Packages

  1. PM> Install-Package bootstrap -Version 3.3.7  
  2. PM> Install-Package FontAwesome -Version 4.7.0  
  3. PM> Install-Package jQuery -Version 3.2.1  
  4. PM> Install-Package Microsoft.AspNet.SignalR -Version 2.2.2 
After the successful installation of above packages, the above dll's or packages are installed into your project. You can see the Reference files in your project solution.
 

Other Reference files like Microsoft.owin are dependency files of Microsoft.AspNet.SignalR namespace. Since our application is an OWIN-based application, we have to create a class “Startup.cs”. In this file, the components for the application pipeline are added. The OWIN attribute which specifies the type of property specifying the project's start up and the configuration method, sets up the SignalR mapping for the App. The code for the “Startup.cs” is given below.

  1. using Microsoft.Owin;  
  2. using Owin;  
  3.   
  4. [assembly: OwinStartup(typeof(SignalRChat.Startup))]  
  5. namespace SignalRChat  
  6. {  
  7.     public class Startup  
  8.     {  
  9.         public void Configuration(IAppBuilder app)  
  10.         {  
  11.             app.MapSignalR();  
  12.         }  
  13.     }  
  14. }   

Now, create a database. As we are going to create a registration and login system, so we will use login details from database for login. When a user gets registered, it will store the User details into the database and use the same while the user logs in to the application.

Create Database

  1. Create Database SignalRdb  

Create a Table and insert a record for admin user.

  1. USE [SignalRdb]  
  2.   
  3. GO  
  4.   
  5. CREATE TABLE [dbo].[tbl_Users](  
  6.   
  7. [ID] [int] IDENTITY(1,1) NOT NULL,  
  8. [UserName] [varchar](50) NULL,  
  9. [Email] [varchar](50) NULL,  
  10. [Password] [varchar](50) NULL,  
  11. [Photo] [varchar](50) NULL,  
  12.   
  13. CONSTRAINT [PK_tbl_Users] PRIMARY KEY CLUSTERED  
  14. (  
  15.   [ID] ASC  
  16. )
  17. WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  18.   
  19. ON [PRIMARY]  
  20.   
  21. insert into [dbo].[tbl_Users] (UserName,Email,Password)values('admin','[email protected]','12345'); 

Here, I am skipping the explaination of connection of SQL Server database; I hope you know the connectivity of database. You will get everything in the source code that I have attached.

After creating the database, create a new WebForm Register Page (Register.aspx). Here, I am using ready CSS file to design my register page. The page will look like the below image.

Code for Register.cs

  1. public partial class Register : System.Web.UI.Page  
  2.    {  
  3.        ConnClass ConnC = new ConnClass();  
  4.        protected void Page_Load(object sender, EventArgs e)  
  5.        {  
  6.   
  7.        }  
  8.        protected void btnRegister_ServerClick(object sender, EventArgs e)  
  9.        {  
  10.            string Query = "insert into tbl_Users(UserName,Email,Password)Values('"+txtName.Value+"','"+txtEmail.Value+"','"+txtPassword.Value+"')";  
  11.            string ExistQ = "select * from tbl_Users where Email='"+txtEmail.Value+"'";  
  12.            if (!ConnC.IsExist(ExistQ))  
  13.            {  
  14.                if (ConnC.ExecuteQuery(Query))  
  15.                {  
  16.                    ScriptManager.RegisterStartupScript(this, GetType(), "Message""alert('Congratulations!! You have successfully registered..');"true);  
  17.                    Session["UserName"] = txtName.Value;  
  18.                    Session["Email"] = txtEmail.Value;  
  19.                    Response.Redirect("Chat.aspx");  
  20.                }  
  21.            }  
  22.            else  
  23.            {  
  24.                ScriptManager.RegisterStartupScript(this, GetType(), "Message""alert('Email is already Exists!! Please Try Different Email..');"true);  
  25.            }  
  26.        }   
  27.    } 

Now, create a Login Page (Login.aspx). Here, I am using ready CSS file to design my Login page. The page will look like this.



Code for Login.cs,
  1. public partial class Login : System.Web.UI.Page  
  2.     {  
  3.         //Class Object  
  4.         ConnClass ConnC = new ConnClass();  
  5.         protected void Page_Load(object sender, EventArgs e)  
  6.         {  
  7.              
  8.         }  
  9.   
  10.         protected void btnSignIn_Click(object sender, EventArgs e)  
  11.         {  
  12.             string Query = "select * from tbl_Users where Email='" + txtEmail.Value + "' and Password='" + txtPassword.Value + "'";  
  13.             if (ConnC.IsExist(Query))  
  14.             {  
  15.                 string UserName = ConnC.GetColumnVal(Query, "UserName");  
  16.                 Session["UserName"] = UserName;  
  17.                 Session["Email"] = txtEmail.Value;  
  18.                 Response.Redirect("Chat.aspx");  
  19.             }  
  20.             else  
  21.                 txtEmail.Value = "Invalid Email or Password!!";  
  22.         }  
  23.     }  
Create a new WebForm “Chat.aspx” that is the main page of our application. After successful login, this page will be displayed to the user. And here, the user can chat with other online users. There is also an option “Change Profile Picture” so that the user can change his/her profile picture, which displays in the chat while chatting. The other user also can see this profile image.

Now, create a Hub Class,i.e., create a new class and name this class “ChatHub.cs”. Here, we are creating a function which we are calling in “Chat.aspx page” by using jQuery.

  1. namespace SignalRChat  
  2. {  
  3.     public class ChatHub :Hub  
  4.     {  
  5.         static List<Users> ConnectedUsers = new List<Users>();  
  6.         static List<Messages> CurrentMessage = new List<Messages>();  
  7.         ConnClass ConnC = new ConnClass();  
  8.   
  9.         public void Connect(string userName)  
  10.         {  
  11.             var id = Context.ConnectionId;  
  12.              
  13.             if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)  
  14.             {  
  15.                 string UserImg = GetUserImage(userName);  
  16.                 string logintime = DateTime.Now.ToString();  
  17.                 ConnectedUsers.Add(new Users { ConnectionId = id, UserName = userName, UserImage = UserImg, LoginTime = logintime });  
  18.   
  19.                 // send to caller  
  20.                 Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage);  
  21.   
  22.                 // send to all except caller client  
  23.                 Clients.AllExcept(id).onNewUserConnected(id, userName, UserImg, logintime);  
  24.             }  
  25.         }  
  26.    }  
  27. }  

In Design page, we are calling this function. I am giving you only one example but there are many functions that we have created on Hub class file and calling these functions in the design page.

  1. $(function () {  
  2.   
  3.            // Declare a proxy to reference the hub.   
  4.            var chatHub = $.connection.chatHub;  
  5.            registerClientMethods(chatHub);  
  6.            // Start Hub  
  7.            $.connection.hub.start().done(function () {  
  8.   
  9.                registerEvents(chatHub)  
  10.                 
  11.            });  
  12.        });  
In the above jQuey function, we are initializing hub connection and we are writing rest of functions in hub start function. See the below function. In this function, we have called function from Hub class that is “ChatHub.cs” and passing values through the parameters.
  1. // Calls when user successfully logged in  
  2. chatHub.client.onConnected = function (id, userName, allUsers, messages, times) {  
  3.   
  4.     $('#hdId').val(id);  
  5.     $('#hdUserName').val(userName);  
  6.     $('#spanUser').html(userName);  
  7.      
  8.     // Add All Users  
  9.     for (i = 0; i < allUsers.length; i++) {  
  10.   
  11.         AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName, allUsers[i].UserImage, allUsers[i].LoginTime);  
  12.     }  
  13.   
  14.     // Add Existing Messages  
  15.     for (i = 0; i < messages.length; i++) {  
  16.         AddMessage(messages[i].UserName, messages[i].Message, messages[i].Time, messages[i].UserImage);  
  17.        
  18.     }  

This method is used to send message where we are passing user name, message, and message time. We are getting user image by user name that we have stored in the database. If the user does not have any image, we are setting a dummy image for them.

  1. public void SendMessageToAll(string userName, string message, string time)  
  2. {  
  3.    string UserImg = GetUserImage(userName);  
  4.     // store last 100 messages in cache  
  5.     AddMessageinCache(userName, message, time, UserImg);  
  6.   
  7.     // Broad cast message  
  8.     Clients.All.messageReceived(userName, message, time, UserImg);  
  9.   
  10. }  
Images are stored in Project directory. Here, we have assigned a directory of user images and the image names will be stored in database and image will be stored in “images/DP/” directory.
  1. public string GetUserImage(string username)  
  2.        {  
  3.            string RetimgName = "images/dummy.png";  
  4.            try  
  5.            {  
  6.                string query = "select Photo from tbl_Users where UserName='" + username + "'";  
  7.                string ImageName = ConnC.GetColumnVal(query, "Photo");  
  8.   
  9.                if (ImageName != "")  
  10.                    RetimgName = "images/DP/" + ImageName;  
  11.            }  
  12.            catch (Exception ex)  
  13.            { }  
  14.            return RetimgName;  
  15.        }  
The SendMessageToAll method is requested from the client with the parameters after the connection is set on the client side and once the server receives the request, it processes and sends back the response to the client. There is method which appends the message into HTML DIV and displays on the UI to the client. The client side code would look like below.
  1. function AddMessage(userName, message, time, userimg) {  
  2.   
  3.             var CurrUser = $('#hdUserName').val();  
  4.             var Side = 'right';  
  5.             var TimeSide = 'left';  
  6.   
  7.             if (CurrUser == userName) {  
  8.                 Side = 'left';  
  9.                 TimeSide = 'right';  
  10.   
  11.             }  
  12.   
  13.             var divChat = '<div class="direct-chat-msg ' + Side + '">' +  
  14.                 '<div class="direct-chat-info clearfix">' +  
  15.                 '<span class="direct-chat-name pull-' + Side + '">' + userName + '</span>' +  
  16.                 '<span class="direct-chat-timestamp pull-' + TimeSide + '"">' + time + '</span>' +  
  17.                 '</div>' +  
  18.   
  19.                 ' <img class="direct-chat-img" src="' + userimg + '" alt="Message User Image">' +  
  20.                 ' <div class="direct-chat-text" >' + message + '</div> </div>';  
  21.   
  22.             $('#divChatWindow').append(divChat);  
  23.            
  24.             var height = $('#divChatWindow')[0].scrollHeight;  
  25.             $('#divChatWindow').scrollTop(height);  
  26.   
  27.         }  

User can set their profile Picture and also can change their picture so here is option to change profile picture for users. Here, we have used Bootstrap Modal Popup.

Output

The final output will look like below.

Conclusion

Here, we have learned the integration of SignalR and NuGet Package in a project that simplifies the work of our project, and also, the web page designing using Bootstrap. Basically, this is just a simple chat application which you can use to chat with your friends. SignalR is not just this much. There are a lot of other effective uses of SignalR. So this is the first part of “SignalR Chat App” tutorial. I will explain you the integration of private chat in my next article. We are going to add some more effective features of chat in our next article.

Hope this will help you and you  liked this article. I have attached the Project source code that you can download for your reference.

Please share your valuable feedback in the comments section.


Similar Articles