Click here to Skip to main content
15,887,027 members
Articles / Web Development / HTML

Create a Chat System using Ajax and ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.00/5 (6 votes)
12 Feb 2007CPOL2 min read 100.3K   3.4K   53   19
This article explains how to make a chat application in ASP.NET with Ajax
Sample image

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.

C#
//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:

C#
//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.

C#
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

C#
//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
<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.

References

License

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


Written By
Web Developer
Australia Australia
Yaya Jiang is a oversea Student of Queensland University of Technology in Australia.
Yaya Jiang is a software engineer, currently interest in Web Development.

Comments and Discussions

 
Generalcode need a db Pin
Member 912970415-Jul-12 8:21
Member 912970415-Jul-12 8:21 
GeneralMy vote of 5 Pin
meghasinghal843-Oct-10 21:41
meghasinghal843-Oct-10 21:41 
Questionremote access help Pin
slhacker30-Mar-09 1:25
slhacker30-Mar-09 1:25 
GeneralThe username and password Pin
Shwaria25-Aug-08 2:50
Shwaria25-Aug-08 2:50 
AnswerRe: The username and password Pin
sivakl_20013-Sep-08 21:01
sivakl_20013-Sep-08 21:01 
GeneralRe: The username and password Pin
baijuep7-Sep-15 6:45
baijuep7-Sep-15 6:45 
GeneralChat_system Pin
NishaDeepak7-Feb-08 19:49
NishaDeepak7-Feb-08 19:49 
GeneralRe: Chat_system Pin
MaxPayne77-Feb-08 20:07
MaxPayne77-Feb-08 20:07 
GeneralRe: Chat_system Pin
dougame7-Feb-08 22:15
dougame7-Feb-08 22:15 
GeneralRe: Chat_system Pin
dougame7-Feb-08 22:31
dougame7-Feb-08 22:31 
GeneralGreat Job man Pin
Albert Pascual21-Dec-07 17:33
sitebuilderAlbert Pascual21-Dec-07 17:33 
GeneralGreat Job man Pin
Albert Pascual21-Dec-07 17:33
sitebuilderAlbert Pascual21-Dec-07 17:33 
GeneralAJAX help needed very urgent Pin
kalh1715-Feb-07 0:35
kalh1715-Feb-07 0:35 
Generalcle was great. Pin
kalh1715-Feb-07 0:33
kalh1715-Feb-07 0:33 
GeneralRe: cle was great. Pin
dougame15-Feb-07 5:59
dougame15-Feb-07 5:59 
GeneralRe: cle was great. Pin
dougame15-Feb-07 6:58
dougame15-Feb-07 6:58 
GeneralRe: cle was great. Pin
dougame15-Feb-07 6:59
dougame15-Feb-07 6:59 
QuestionAjax Asp.net ? Pin
UnRusoDeCaracas13-Feb-07 8:46
UnRusoDeCaracas13-Feb-07 8:46 
AnswerRe: Ajax Asp.net ? Pin
dougame13-Feb-07 11:19
dougame13-Feb-07 11:19 

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.