Creating a Chat Room Using ASP.NET Client Callbacks
By AzamSharp
Views: 3332

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

 

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Error on Web.config
Name: Scottt40
Date: 6/3/2007 3:40:03 PM
Comment:
When I try to run the sample I get an error in the:

of the web.config file. How do I fix this?
Windows xp
VS 2005
SQL Express 2005
MS Ajax 1.0
asp.net 2.0, 3.0
Subject: Error While Running
Name: Suman
Date: 6/5/2007 5:13:35 AM
Comment:
I am trying to run The Application i am getting ChatManger some assemble is missing .. Please Help me How to resolve this problem..

Its Urgent...

Thanks in Advance..

Regards,
suman
Subject: problem
Name: Bharath
Date: 2/1/2008 10:55:04 PM
Comment:
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Could not load file or assembly 'Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

Plz solve my problem
Subject: RE: problem
Name: AzamSharp
Date: 2/4/2008 8:20:36 AM
Comment:
Hi Bharath, Try removing the reference to this assembly. I don't think I am using this assembly in the application. PS: The application was created in VS 2005.
Subject: with database
Name: milts
Date: 2/14/2008 9:57:33 PM
Comment:
how do i work with these if i want to store the message after or before it would be posted? thanks! :)
Subject: RE: with database
Name: AzamSharp
Date: 2/15/2008 7:32:59 AM
Comment:
Hi milts, What problems are you facing when trying to save the chatting in the database.
Subject: 1 on 1 chat
Name: milts
Date: 2/15/2008 10:52:00 AM
Comment:
solved my earlier concern. this time i would like to ask if the code used here can also be used when creating a one on one chat. i would like to create something like these which also supports 1 on 1 chat. thanks :)
Subject: another question
Name: milts
Date: 2/19/2008 1:41:34 AM
Comment:
another thing, how can i display a div or listbox of the different users in the chatroom? is it possible? thanks!
Subject: RE: 1 on 1 chat
Name: AzamSharp
Date: 2/20/2008 8:45:48 PM
Comment:
Hi Milts, Interesting idea! Might give it a try in few days. I think you can use the Cache[key] to hold the data between the two users. The key needs to be known to only those two users.
Subject: Thanks
Name: John
Date: 3/8/2008 12:44:24 PM
Comment:
Thanks for a very good article. This has become one of my favorite websites over the last few months. Thanks so much!
Subject: RE: Thanks!
Name: AzamSharp
Date: 3/10/2008 2:28:08 PM
Comment:
Hi Jon, Thanks for the encouraging comments. I am glad you are finding the website good!



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008