I was reading a very interesting article about creating a chat room using AJAX on www.codeproject.com. You can read the complete article at this link. After reading the article I thought why not implement a chat room but instead of using pure AJAX I will use ASP.NET 2.0 Client Callbacks. In this article I will demonstrate how to implement a very simple chat room.

Introduction:

I was reading a very interesting article about creating a chat room using AJAX on www.codeproject.com. You can read the complete article at this link. After reading the article I thought why not implement a chat room but instead of using pure AJAX I will use ASP.NET 2.0 Client Callbacks. In this article I will demonstrate how to implement a very simple chat room.

Creating the Login Page:

The first task is to create a simple login page. The purpose of this page is to give users some identity before they enter the chat room. Check out the code below for the login page.

<form id="form1" runat="server">

<div>

Enter User Name:

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />

<br />

<asp:Button ID="Add_User" runat="server" OnClick="Add_User_Click" Text="Begin Chat" /></div>

</form>

As, you can see from the code above that the login page is very simple and consists of a single textbox and a button control. Once, the button is clicked the username is written to the Session object, as demonstrated below:

protected void Add_User_Click(object sender, EventArgs e)

{

Session["UserName"] = txtUserName.Text;

Response.Redirect("ChatPage.aspx");

}

Implementing the Chat Page:

The ChatPage.aspx is the page where all the chatting is performed. When the page loads a check is performed to see that if the user is already in the chat room. This is because that we don't want to send the duplicate welcome messages like "John has joined the room". You can also use the same functionality to keep track of all the users in the chat room. After that a Client Callback function is registered to the page. This function is responsible for making server side calls from the client side code. Take a look at the code below:

string sbReference = ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");

string cbScript = String.Empty;

// check if the script is already registered or not

if (!ClientScript.IsClientScriptBlockRegistered("CallServer"))

{

cbScript = @" function CallServer(arg,context) { " + sbReference + "}";

ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", cbScript, true);

}

In order to use the Client Callback features the page must also inherit from the ICallbackEventHandler interface. Once, you inherited from the interface you will need to implement the GetCallbackResult and RaiseCallbackEvent methods. The method implementation is fairly simple as they in turn call some other helper methods to perform the processing.

public string GetCallbackResult()

{

// Add to the collection and then return the collection

if (!String.IsNullOrEmpty(bufferText))

{

chatManager.AddText( (string) Session["UserName"],bufferText);

}

return chatManager.BufferText;

}

public void RaiseCallbackEvent(string eventArgument)

{

if (!String.IsNullOrEmpty(eventArgument))

{

bufferText = eventArgument;

}

}

The GetCallbackResult calls the AddText method of the ChatManager class, which is responsible for handling all the messages. The AddText method is used to add the messages of the user to the static StringCollection.

public void AddText(string userName,string text)

{

chatCollection.Add(FormatMessage(userName,text));

}

There are several other methods in the ChatManager class which you can view after downloading the sample.

Updating the Messages:

Updating the messages is one of the most important feature of the chatting application. Consider this, if one user post a message on the chat room what good it will be if the message is not viewable by the other users.

So, we need some sort of the mechanism that will be call repeatedly and gets the latest messages. Fortunately, there is a setInterval JavaScript function that can call other JavaScript functions at regular intervals. You can check out the setInterval parameters below:

SetInterval("MethodName()",[Time in milliseconds]);

Now, let's implement this feature in the chatting application.

// start the timer to refresh the screen

SetTimer();

function SetTimer()

{

setInterval("UpdateChatWindow()",250);

}

function UpdateChatWindow()

{

CallServer('','');

}

The setTimer function is called when the page loads and set the UpdateChatWindow method to be called every 250 milliseconds. The UpdateChatWindow method calls the CallServer method with empty parameters. This means that we are not sending any data to the server and we are just requested the updated data.

Receiving the Updated Data:

The final task is to receive and display the updated data to the user. This is performed by the ReceiveServerData function.

function ReceiveServerData(rValue)

{

document.getElementById("panelChatPane").innerHTML = rValue;

ScrollChatPane();

}

The argument rValue contains the complete chat in the form of string which, is later displayed in the DIV element.

You can see the chatting animation below:

 

 

I hope you liked the article, happy programming!

Download Sample