Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
20 Dec 2017 1  
Integration of SignalR with ASP.NET C# WebForm Application in Real-Time Chat Application
In this article, we are going to learn to create a real-time chat application using SignalR, Bootstrap, and jQuery Modal Popup.

Introduction

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

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

Image 1

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

Image 2

Image 3

The package Console Manager will open. You can add any package just by writing Package Name and press 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 the above packages, the above DLLs or packages are installed into your project. You can see the Reference files in your project solution.

Image 4

Other Reference files like Microsoft.owin are dependency files of Microsoft.AspNet.SignalR namespace. Since our application is OWN based application, so 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, 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','admin@admin.com','12345');

Here, I am skipping the explanation 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:

Image 5

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:

Image 6

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!!";
    }
}

Create new WebForm “Chat.aspx” - this is the main page of our application, after successful login, this page will display to the user. And here, user can chat with other online users. And there is also an option “Change Profile Picture” so user can change his profile picture, which displays in chat while chatting, other users can also see his profile image.

Now create Hub Class, create a new class named this class “ChatHub.cs”, so this is the hub class, here we are creating function which we are calling in “Chat.aspx page” by using jquery.

  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. Here, I am giving you only one example, there are many functions that we have created on Hub class file and calling these functions in 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)

           });
       });

In the above JQuery function, we are initializing hub connection and we are writing rest of the functions in hub start function. See the below function. In this function, we have called function from Hub class that is “ChatHub.cs” and pass values through the parameters:

// 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. Here, we are passing user name, message, and message time and we are getting user image by user name that we have stored in the database, if user does not have any image so here we are setting a dummy image for kind of users.

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);

        }

Images stored in Project directory, here we have to assign a directory for user images, the images names will be stored in database and image will stored in “images/DP/” directory.

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

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 a method which appends message into HTML DIV and displays on the UI to the client. The client side code would look like below:

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);
       }

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

Image 7

Output

The final output will look like below:

Image 8

Conclusion

Here, we learned the integration of SignalR and Nuget Package in project that simplify the work of our project, and also 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 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 would like this article, I have attached Project source code. You can download the 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.

History

  • 20th December, 2017: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here