Вы находитесь на странице: 1из 13

25/03/2019 SignalR Chat App With ASP.

NET WebForm And BootStrap - Part One - CodeProject

13,902,146
Sign up formembers
our free weekly Web Dev Newsletter. Sign in
×

Search for articles, questions, tips


articles Q&A forums stuff lounge ?

SignalR Chat App With ASP.NET WebForm And


BootStrap - Part One
Altaf Ansari, 20 Dec 2017

   5.00 (28 votes) Rate this:

Integration of SignalR with ASP.NET C# WebForm Application in Real-Time Chat Application

Download SignalRChatPart1.zip - 15.7 MB

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.

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 1/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

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

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 2/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

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.

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 3/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

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.

Hide   Copy Code

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

Hide   Copy Code

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

Hide   Copy Code


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


(
https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 4/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject
[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

Hide   Shrink   Copy Code

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
{

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 5/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject
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.

Hide   Copy Code


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.
Hide   Copy Code

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 6/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

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.
 
Hide   Copy Code
$(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,

Hide   Copy Code


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

}
}

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 7/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

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.

Hide   Copy Code


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.

Hide   Copy Code


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,

Hide   Copy Code


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;


https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 8/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject
$('#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,

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 9/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

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

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 10/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

About the Author


Altaf Ansari
Software Developer Prothious Engineering Services
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...


Visual Studio Tips - DebuggerDisplay

How To Detect Who Unfriended You on Facebook?

Comments and Discussions


 

You must Sign In to use this message board.

Search Comments

First Prev Next

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 11/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

Loose and uninformative


AtarashiiJoey 2-Nov-18 1:22

When open new IE Tab, it don't know that already login on first IE Tab
Member 12082349 14-Sep-18 6:08

Re: When open new IE Tab, it don't know that already login on first IE Tab
Altaf Ansari 18-Sep-18 22:28

SignalR and JQuery Library


Member 13856810 4-Jun-18 23:50

Re: SignalR and JQuery Library


Altaf Ansari 18-Sep-18 22:29

ConnClass reference is not being added


Member 13793324 22-Apr-18 23:17

how to integrate VS 2013


jerin_shalini 20-Apr-18 0:33

Re: how to integrate VS 2013


Altaf Ansari 18-Sep-18 22:31

how can i use signalr in 3 tier architecture


Member 12867656 21-Mar-18 22:57

Good article...
Uttari Anthony 8-Jan-18 17:54

Re: Good article...


Altaf Ansari 8-Jan-18 17:54

Nice article
Member 12193771 8-Jan-18 3:06

Re: Nice article


Altaf Ansari 18-Sep-18 22:32

Dangerous Sql Query


digimanus 5-Jan-18 1:22

Re: Dangerous Sql Query


Altaf Ansari 5-Jan-18 2:22

Re: Dangerous Sql Query


Kevin Marois 19-Sep-18 7:49

Re: Dangerous Sql Query


Altaf Ansari 19-Sep-18 20:05

some query about your signalr chat


Mou_kol 20-Dec-17 20:29

Re: some query about your signalr chat


Altaf Ansari 20-Dec-17 22:07

Have a 5
Dewey 20-Dec-17 12:22

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 12/13
25/03/2019 SignalR Chat App With ASP.NET WebForm And BootStrap - Part One - CodeProject

Re: Have a 5
Altaf Ansari 18-Sep-18 22:33

Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    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


Selecione o idioma ▼
Web02 | 2.8.190306.1 | Last Updated 20 Dec 2017
Layout: fixed | fluid Article Copyright 2017 by Altaf Ansari
Everything else Copyright © CodeProject, 1999-2019

https://www.codeproject.com/Articles/1221913/SignalR-Chat-App-With-ASP-NET-WebForm-And-BootStra 13/13