Click here to Skip to main content
13,662,923 members
Click here to Skip to main content
Add your own
alternative version

Stats

12.6K views
1.6K downloads
47 bookmarked
Posted 20 Dec 2017
Licenced CPOL

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

, 20 Dec 2017
Rate this:
Please Sign up or sign in to vote.
Integration of SignalR with ASP.NET C# WebForm Application in Real-Time Chat Application

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 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 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 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 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, 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

<span><span class="keyword">Create</span><span> </span><span class="keyword">Database</span><span> SignalRdb </span></span>

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 explaination of connection of SQL Server database; I hope you know the connectivity of database. You will get everything in 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.

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 display in chat while chatting, other user also can see the 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 function that we have created on Hub class file and calling these function 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 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,

// 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 getting user image by user name that we have stored in 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 assign a directory for user images, the images names will 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 method which append message into HTML DIV and display 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);

       }

 

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 be look like below,

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 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 would this article, I have attached Project source code you can download source code for your reference and to see the complete source, thank you for reading...

Please give your valuable feedback in the comment section.

License

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

Share

About the Author

Altaf Ansari
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)

You may also be interested in...

Comments and Discussions

 
QuestionSignalR and JQuery Library Pin
Member 138568104-Jun-18 23:50
memberMember 138568104-Jun-18 23:50 
QuestionConnClass reference is not being added Pin
Member 1379332422-Apr-18 23:17
memberMember 1379332422-Apr-18 23:17 
Questionhow to integrate VS 2013 Pin
jerin_shalini20-Apr-18 0:33
professionaljerin_shalini20-Apr-18 0:33 
Questionhow can i use signalr in 3 tier architecture Pin
Member 1286765621-Mar-18 22:57
memberMember 1286765621-Mar-18 22:57 
PraiseGood article... Pin
Uttari Anthony8-Jan-18 17:54
memberUttari Anthony8-Jan-18 17:54 
GeneralRe: Good article... Pin
Altaf Ansari8-Jan-18 17:54
memberAltaf Ansari8-Jan-18 17:54 
PraiseNice article Pin
Member 121937718-Jan-18 3:06
memberMember 121937718-Jan-18 3:06 
QuestionDangerous Sql Query Pin
digimanus5-Jan-18 1:22
memberdigimanus5-Jan-18 1:22 
AnswerRe: Dangerous Sql Query Pin
Altaf Ansari5-Jan-18 2:22
memberAltaf Ansari5-Jan-18 2:22 
Questionsome query about your signalr chat Pin
Mou_kol20-Dec-17 20:29
memberMou_kol20-Dec-17 20:29 
AnswerRe: some query about your signalr chat Pin
Altaf Ansari20-Dec-17 22:07
memberAltaf Ansari20-Dec-17 22:07 
QuestionHave a 5 Pin
Dewey20-Dec-17 12:22
memberDewey20-Dec-17 12:22 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180810.1 | Last Updated 20 Dec 2017
Article Copyright 2017 by Altaf Ansari
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid