Monday, September 8, 2008

Simple Chat Application in ASP.NET

By Mosalem
Implementing a simple chat application using ASP.NET and remote scripting.

Introduction
I ran into the problem of creating a chat room where two users can chat directly. I didn't like the idea of using server side code and doing all these post back which is not user friendly. I found that with the use of remote scripting, we can make a simple and fast chat application.
Background
I built this application using the Remote Scripting client and server side implementation provided by Alvaro Mendez: Remote Scripting. I also used some chat room logic from Julien Couvreur.
Code Walkthrough
I'll start by examining the ChatEngine.cs file which contains all the logic. You'll find four classes in this file:
The ChatUser that contains the user info (ID, name, active or not, last seen time, last message received): public class ChatUser : IDisposable
{
public string UserID;
public string UserName;
public bool IsActive;
public DateTime LastSeen;
public int LastMessageReceived;
public ChatUser(string id,string userName)
{
this.UserID=id;
this.IsActive=false;
this.LastSeen=DateTime.MinValue ;
this.UserName=userName;
this.LastMessageReceived=0;
}
public void Dispose()
{
this.UserID="";
this.IsActive=false;
this.LastSeen=DateTime.MinValue ;
this.UserName="";
this.LastMessageReceived=0;
}
}
The Message class contains information about the message (the message text, message type, sender ID):
Collapsepublic class Message
{
public string user;
public string msg;
public MsgType type;
public Message(string _user, string _msg, MsgType _type)
{
user = _user;
msg = _msg;
type = _type;
}
public override string ToString()
{
switch(this.type)
{
case MsgType.Msg:
return this.user+" says: "+this.msg;
case MsgType.Join :
return this.user + " has joined the room";
case MsgType.Left :
return this.user + " has left the room";
}
return "";
}
public Message(string _user, MsgType _type) : this(_user, "", _type) { }
public Message(MsgType _type) : this("", "", _type) { }
}
public enum MsgType { Msg, Start, Join, Left }
The ChatRoom class:
Each chat room can have two users only represented by the two members FirstUser and SecondUser. The messages are stored in the ArrayList messages of Message instances. The class contains the common operations for a chat room like joining, sending message and leaving the room.
The ChatEngine class: contains a HashTable of chat rooms.
Other operations in the class include creating new rooms and deleting the empty chat rooms.

More...
http://www.codeproject.com/KB/applications/AliAspNetChat.aspx

ASP.Net Feeds