Create a Chat System using Ajax and ASP.NET
This article explains how to make a chat application in ASP.NET with Ajax
Introduction
I was always wondering how to make an auto refresh chat room, without flash. Since I go through a lot of articles in CodeProject, I found I should use ASP.NET with Ajax. So I combined Albert Pascual and dealarconjose's work together, and I have put in some of my own ideas and code which you will find out in this article.
Here, I am going to explain how to use JavaScript, Ajax and C# to create a chat room.
Why Ajax and How to Use it in ASP.NET?
Why Ajax?
My understanding is that you can use JavaScript code to implement C# or VB.NET code now,
and update content without refreshing the page (not really no refresh, just refresh the
page without flash).
For more details, please refer to this link.
How to Use It?
Please refer to this.
Look in the Code
1. ChatEngine.cs
Part of the idea is from Albert Pascual's article. This code is to manage the chat content in the array list.
//Part of the code is referenced from
//http://www.codeproject.com/aspnet/SimpleChat.aspx Author: Albert Pascual
//Good job~man~:)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
namespace Chat
{
/// <summary>
/// Summary description for ChatEngine
/// </summary>
public class ChatEngine
{
public ChatEngine()
{
//
// TODO: Add constructor logic here
//
}
static protected ArrayList pArray = new ArrayList();
[Ajax.AjaxMethod]
public void AddMessage(string sUser, string sMsg)
{
string sAddText = "<STRONG>" + sUser + " says :" + "</STRONG>" + sMsg;
pArray.Add(sAddText);
if (pArray.Count > 200)
{
pArray.RemoveRange(0, 10);
}
}
[Ajax.AjaxMethod]
public string GetAllMessages()
{
string sResponse = "";
for (int i = 0; i < pArray.Count; i++)
{
sResponse = sResponse + "<BR>" + pArray[i].ToString();
}
return (sResponse);
}
//add the join message to the array list
public void joinRoom(string sUser)
{
string sAddText = "<STRONG>" + sUser + " has joined the room" + "</STRONG>";
pArray.Add(sAddText);
}
//add the leave message to the array list
public void leaveRoom(string sUser)
{
string sAddText = "<STRONG>" + sUser + " has Leaved the room" + "</STRONG>";
pArray.Add(sAddText);
}
public bool check()
{
if (pArray.Count == 0)
{
return false;
}
else
{
return true;
}
}
[Ajax.AjaxMethod]
public void Clean()
{
pArray.Clear();
}
}
}
2. CustomerManagement.cs
This code is to manage the user in the array list:
//This code idea is from http://www.codeproject.com/aspnet/SimpleChat.aspx
//Author: Albert Pascual
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
namespace Chat
{
/// <summary>
/// Summary description for CustomerManagement
/// </summary>
public class CustomerManagement
{
private ChatEngine c = new ChatEngine();
public CustomerManagement()
{
//
// TODO: Add constructor logic here
//
}
static protected ArrayList cArray = new ArrayList();
[Ajax.AjaxMethod]
public void AddCustomer(string sUser)
{
string cAddText = "<STRONG>" + sUser + "</STRONG>";
cArray.Add(cAddText);
if (cArray.Count > 200)
{
cArray.RemoveRange(0, 10);
}
}
[Ajax.AjaxMethod]
public string GetAllUsers()
{
string cResponse = "";
for (int i = 0; i < cArray.Count; i++)
{
cResponse = cResponse + "<BR>" + cArray[i].ToString();
}
return (cResponse);
}
public bool CheckUser(string Username)
{
if (cArray.Contains("<STRONG>" + Username + "</STRONG>"))
{
return true;
}
else
{
return false;
}
}
[Ajax.AjaxMethod]
public void SignOut(string Username)
{
if (cArray.Contains("<STRONG>" + Username + "</STRONG>"))
{
cArray.Remove("<STRONG>" + Username + "</STRONG>");
c.leaveRoom(Username);
}
}
public void clean()
{
cArray.Clear();
}
}
}
3. Default.aspx.cs
Nothing much to explain in here, just a JavaScript code for opening the chat room in a new window without toolbar and menubar, for the purpose of stopping user from refreshing the page.
private static SqlConnection myConnection =
new SqlConnection("server=(local);database=mySystem;Trusted_Connection=true");
private SqlCommand myCommand;
private SqlDataAdapter myAdapter;
private string command;
private DataSet myDataSet;
private Chat.CustomerManagement c = new Chat.CustomerManagement();
private Chat.ChatEngine cc = new Chat.ChatEngine();
protected void btnJoin_Click(object sender, EventArgs e)
{
if (getUser(txtUserName.Text, txtPassword.Text))
{
if(c.CheckUser(txtUserName.Text))
{
lblError.Text = "You are in the chat room already!";
}
else
{
c.AddCustomer(txtUserName.Text);
cc.joinRoom(txtUserName.Text);
Session["UserName"] = txtUserName.Text;
//open a new window without toolbar and menubar
Response.Write("<script language="\""javascript\">" + "\n");
Response.Write("window.open(\"Chat.aspx\",\"chat\",
\"width=800\",\"height=600\",\"toolbar=no\",
\"menubar=no\")" + "\n</script>");
}
}
else
{
lblError.Text = "Login Failed";
}
}
private bool getUser(string UserName, string password)
{
DataTable UserInfo = new DataTable();
try
{
command = "Select * From Customer where UserName = '" +
UserName + "' and Password = '" + password + "'";
myAdapter = new SqlDataAdapter(command, myConnection);
myDataSet = new DataSet();
myAdapter.Fill(myDataSet,"User");
UserInfo = myDataSet.Tables[0];
if (UserInfo.Rows.Count != 0)
{
return true;
}
else
{
return false;
}
}
catch(Exception e)
{
UserInfo = null;
return false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
c.clean();
}
4. Chat.aspx and Chat.aspx.cs
//Chat.aspx.cs
Chat.ChatEngine engine = new Chat.ChatEngine();
protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(Chat.ChatEngine));
Ajax.Utility.RegisterTypeForAjax(typeof(Chat.CustomerManagement));
if (Session["UserName"] == null)
{
Response.Write("<script language="\""javascript\">" + "\n");
Response.Write("alert(\"Please Login First\")" + "\n</script>");
Response.Write("<script language="javascript">
window.location.href='default.aspx';</script>");
}
}
All the magic is in the JavaScript part. Please read the commands I have written in the code.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Chat System</title>
<script language="javascript" src="ajax/common.ashx"></script>
<script language="javascript" src="ajax/Chat.ChatEngine,ChatEngine.ashx"></script>
<script language="javascript"
src="ajax/Chat.CustomerManagement,CustomerManagement.ashx"></script>
<script language="JavaScript">
//No right click code start(for no refresh the page purpose)
var oLastBtn=0;
bIsMenu = false;
if (window.Event)
{
document.captureEvents(Event.MOUSEUP);
}
function nocontextmenu()
{
event.cancelBubble = true
event.returnValue = false;
return false;
}
function norightclick(e)
{
if (window.Event)
{
if (e.which !=1)
return false;
}
else
if (event.button !=1)
{
event.cancelBubble = true
event.returnValue = false;
return false;
}
}
document.oncontextmenu = nocontextmenu;
document.onmousedown = norightclick;
//no right click end
//ajax using C# function to get the chat content
function dameMsg_CallBack(response){
document.getElementById('ChatContent').innerHTML = response.value;
setTimeout("ChatEngine.GetAllMessages(dameMsg_CallBack)",1000);
}
function cleanTxt(){
document.getElementById('txtMsg').value = '';
}
//ajax using C# function to get the online users
//the idea is from simplechat.asp Autor: dealarconjose
function customer_CallBack(response){
document.getElementById('CustomerContent').innerHTML = response.value;
setTimeout("CustomerManagement.GetAllUsers(customer_CallBack)",1000);
}
function username(){
var uname = '<%= Session["UserName"]%>';
document.getElementById('HidedUserName').value = uname;
}
//auto scrolling the chat content
function scroll(){
if(document.getElementById('ckAutoScroll').checked==true)
{
var objDiv = document.getElementById('ChatContent');
objDiv.scrollTop = objDiv.scrollHeight;
}
setTimeout("scroll()",1);
}
function load() {
window.location="default.aspx";
}
//if close button clicked sign the user out **start**
var UserClicked=false;
document.onmousedown=spyclick;
function spyclick()
{
UserClicked=true;
setTimeout("UserClicked=false",1);
}
function popup()
{
if(!UserClicked)
{
CustomerManagement.SignOut
(document.getElementById('HidedUserName').value);
}
}
window.onbeforeunload=popup;
//**end**
function document.onkeydown(){
//if alt + F4 pressed sign the user out
if ((window.event.altKey)&&(window.event.keyCode==115))
{
CustomerManagement.SignOut
(document.getElementById('HidedUserName').value);
return false;
}
//block F5, no refresh
if(window.event.keyCode==116)
{
event.keyCode=0;
event.returnValue = false;
}
//block Ctrl + R, no refresh
if ((window.event.ctrlKey)&&(window.event.keyCode==82))
{
event.keyCode=0;
event.returnValue = false;
}
//if enter pressed, press Tab key instead
if (event.keyCode==13)
{
event.keyCode=9;
event.returnValue = false;
}
//block ctrl + N, no new window
if ((window.event.ctrlKey)&&(window.event.keyCode==78))
{
event.keyCode=0;
event.returnValue = false;
}
}
</script>
</head>
<body onload="ChatEngine.GetAllMessages(dameMsg_CallBack),scroll(),
CustomerManagement.GetAllUsers(customer_CallBack),
username()" oncontextmenu="event.returnValue = false">
<form id="form1" runat="server" method="post">
<div runat="server" id="ChatContent" style="height:300px;
width:600px;padding:6px;overflow-y:scroll;word-break:
break-all;overflow:auto;"></div>
<div runat="server" id="CustomerContent"
style="height:300px;width:200px;padding:6px;overflow-y:scroll;
word-break: break-all;overflow:auto; position:absolute;
left:620px;top:14px"></div>
Message:<input type="text" id="txtMsg" name="txtMsg"
size="25" onkeydown="if(window.event.keyCode==13) btnSubmit.click()"/>
<!-- ajax using C# function of AddMessage() -->
<input id="btnSubmit" type="button" value="Submit"
onclick="javascript:ChatEngine.AddMessage
(document.getElementById('HidedUserName').value,
document.getElementById('txtMsg').value),cleanTxt()"/>
Auto Scrolling<input id="ckAutoScroll" type="checkbox" checked /><br />
<input id="HidedUserName" type="hidden" value="" />
<br />
<!-- ajax using C# function of Clean() -->
<input id="btnClean" type="button"
value="Clean Screen"onclick="javascript:ChatEngine.Clean();"/>
<!-- ajax using C# function of SignOut() -->
<input id="Button1" type="button"
value="Sign Out"onclick="javascript:CustomerManagement.SignOut
(document.getElementById('HidedUserName').value);javascript:load()"/>
</form>
</body>
</html>
Conclusion
This is just a simple chat room, not a high performance magic system. Hopefully, it is going to give you some help or hints. If you have any questions, just feel free to let me know.