Monday, September 8, 2008

Multi User Chat Room Using ASP.NET 2.0 and AJAX

By Mosalem

Describes how you can build a multi user chat room using ASP.NET 2.0 and AJAX extensions

Introduction
Building an interactive chat room requires keeping the users up to date with the messages and status of other users. Using ASP.NET AJAX to implement the chat room will remove the unnecessary post backs and will provide a seamless chat experience to the user.

Background
You can read my previous article on how to build a one to one chat room, this article was built using ASP.NET 1.1 and a third party AJAX library. Most of the Chatting Logic (rooms, users, messages sending, etc..) is used here.

Code Walkthrough
The App_Code folder contains all the classes that will be used to create our chat application. Let us start with the ChatUser

Collapse
//ChatUser.cs
public class ChatUser:IDisposable
{
#region Members
public string UserID;
public string UserName;
public bool IsActive;
public DateTime LastSeen;
public int LastMessageReceived;
#endregion

#region Constructors
public ChatUser(string id,string userName)
{
this.UserID=id;
this.IsActive=false;
this.LastSeen=DateTime.MinValue ;
this.UserName=userName;
this.LastMessageReceived=0;
}
#endregion

#region IDisposable Members
public void Dispose()
{
this.UserID="";
this.IsActive=false;
this.LastSeen=DateTime.MinValue ;
this.UserName="";
this.LastMessageReceived=0;
}
#endregion
}

This class represents the user that will join the chat room. The properties we are interested in are IsActive, LastSeen and LastMessageReceived. Note that in your application you may be using the ASP.NET membership providers. You can easily use this with our chat application. You will find that the MembershipUser class contains two properties IsOnline and LastActivityDate that can be used to replace the properties IsActive and LastSeen respectively.

Each message that appears in the chat room is represented by the following class:

Collapse
//ChatMessage.cs
public class Message
{
#region Members
public string user;
public string msg;
public MsgType type;
#endregion

#region Constructors
public Message(string _user, string _msg, MsgType _type)
{
user = _user;
msg = _msg;
type = _type;
}
public Message(string _user, MsgType _type) :
this(_user, "", _type) { }
public Message(MsgType _type) : this("", "", _type) { }
#endregion

#region Methods
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 "";
}
#endregion
}
public enum MsgType { Msg, Start, Join, Left, Action}

Each chat room contains a hashtable of users and a list of messages.

More...

http://www.codeproject.com/KB/aspnet/ASPNetChat.aspx

ASP.Net Feeds