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.
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.
The targeted audience is people with basic knowledge of ASP.NET and C#.
Things to do,
- Make an ASP.NET C# WebForm application.
- Add the following packages through NuGet Package Manager.
- Bootstrap
- jQuery
- Font-awesome
- 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”.
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
- PM> Install-Package bootstrap -Version 3.3.7
- PM> Install-Package FontAwesome -Version 4.7.0
- PM> Install-Package jQuery -Version 3.2.1
- PM> Install-Package Microsoft.AspNet.SignalR -Version 2.2.2
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.
- using Microsoft.Owin;
- using Owin;
- [assembly: OwinStartup(typeof(SignalRChat.Startup))]
- namespace SignalRChat
- {
- public class Startup
- {
- public void Configuration(IAppBuilder app)
- {
- app.MapSignalR();
- }
- }
- }
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
- Create Database SignalRdb
Create a Table and insert a record for admin user.
- USE [SignalRdb]
- GO
- CREATE TABLE [dbo].[tbl_Users](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [UserName] [varchar](50) NULL,
- [Email] [varchar](50) NULL,
- [Password] [varchar](50) NULL,
- [Photo] [varchar](50) NULL,
- CONSTRAINT [PK_tbl_Users] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )
- WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- 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
- public partial class Register : System.Web.UI.Page
- {
- ConnClass ConnC = new ConnClass();
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void btnRegister_ServerClick(object sender, EventArgs e)
- {
- string Query = "insert into tbl_Users(UserName,Email,Password)Values('"+txtName.Value+"','"+txtEmail.Value+"','"+txtPassword.Value+"')";
- string ExistQ = "select * from tbl_Users where Email='"+txtEmail.Value+"'";
- if (!ConnC.IsExist(ExistQ))
- {
- if (ConnC.ExecuteQuery(Query))
- {
- ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('Congratulations!! You have successfully registered..');", true);
- Session["UserName"] = txtName.Value;
- Session["Email"] = txtEmail.Value;
- Response.Redirect("Chat.aspx");
- }
- }
- else
- {
- ScriptManager.RegisterStartupScript(this, GetType(), "Message", "alert('Email is already Exists!! Please Try Different Email..');", true);
- }
- }
- }
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,
- public partial class Login : System.Web.UI.Page
- {
- //Class Object
- ConnClass ConnC = new ConnClass();
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void btnSignIn_Click(object sender, EventArgs e)
- {
- string Query = "select * from tbl_Users where Email='" + txtEmail.Value + "' and Password='" + txtPassword.Value + "'";
- if (ConnC.IsExist(Query))
- {
- string UserName = ConnC.GetColumnVal(Query, "UserName");
- Session["UserName"] = UserName;
- Session["Email"] = txtEmail.Value;
- Response.Redirect("Chat.aspx");
- }
- else
- txtEmail.Value = "Invalid Email or Password!!";
- }
- }
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.
- namespace SignalRChat
- {
- public class ChatHub :Hub
- {
- static List<Users> ConnectedUsers = new List<Users>();
- static List<Messages> CurrentMessage = new List<Messages>();
- ConnClass ConnC = new ConnClass();
- public void Connect(string userName)
- {
- var id = Context.ConnectionId;
- if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)
- {
- string UserImg = GetUserImage(userName);
- string logintime = DateTime.Now.ToString();
- ConnectedUsers.Add(new Users { ConnectionId = id, UserName = userName, UserImage = UserImg, LoginTime = logintime });
- // send to caller
- Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage);
- // send to all except caller client
- Clients.AllExcept(id).onNewUserConnected(id, userName, UserImg, logintime);
- }
- }
- }
- }
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.
- $(function () {
- // Declare a proxy to reference the hub.
- var chatHub = $.connection.chatHub;
- registerClientMethods(chatHub);
- // Start Hub
- $.connection.hub.start().done(function () {
- registerEvents(chatHub)
- });
- });
- // Calls when user successfully logged in
- chatHub.client.onConnected = function (id, userName, allUsers, messages, times) {
- $('#hdId').val(id);
- $('#hdUserName').val(userName);
- $('#spanUser').html(userName);
- // Add All Users
- for (i = 0; i < allUsers.length; i++) {
- AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName, allUsers[i].UserImage, allUsers[i].LoginTime);
- }
- // Add Existing Messages
- for (i = 0; i < messages.length; i++) {
- AddMessage(messages[i].UserName, messages[i].Message, messages[i].Time, messages[i].UserImage);
- }
- }
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.
- public void SendMessageToAll(string userName, string message, string time)
- {
- string UserImg = GetUserImage(userName);
- // store last 100 messages in cache
- AddMessageinCache(userName, message, time, UserImg);
- // Broad cast message
- Clients.All.messageReceived(userName, message, time, UserImg);
- }
- public string GetUserImage(string username)
- {
- string RetimgName = "images/dummy.png";
- try
- {
- string query = "select Photo from tbl_Users where UserName='" + username + "'";
- string ImageName = ConnC.GetColumnVal(query, "Photo");
- if (ImageName != "")
- RetimgName = "images/DP/" + ImageName;
- }
- catch (Exception ex)
- { }
- return RetimgName;
- }
- function AddMessage(userName, message, time, userimg) {
- var CurrUser = $('#hdUserName').val();
- var Side = 'right';
- var TimeSide = 'left';
- if (CurrUser == userName) {
- Side = 'left';
- TimeSide = 'right';
- }
- var divChat = '<div class="direct-chat-msg ' + Side + '">' +
- '<div class="direct-chat-info clearfix">' +
- '<span class="direct-chat-name pull-' + Side + '">' + userName + '</span>' +
- '<span class="direct-chat-timestamp pull-' + TimeSide + '"">' + time + '</span>' +
- '</div>' +
- ' <img class="direct-chat-img" src="' + userimg + '" alt="Message User Image">' +
- ' <div class="direct-chat-text" >' + message + '</div> </div>';
- $('#divChatWindow').append(divChat);
- var height = $('#divChatWindow')[0].scrollHeight;
- $('#divChatWindow').scrollTop(height);
- }
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.