Developing a Mini ASP.NET AJAX Server Centric Based Chat Application

In the old days, writing an AJAX-based web chat application often required developers to be quite familiar with client-side JavaScript programming, and to take later maintenance into consideration. In this article, Xianzhong Zhu will lead you through construction of a mini ASP.NET web chat application using the ASP.NET AJAX server centric mode.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 21
December 09, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Hitting the High Spots

As a chatting room module, its main functionalities involve: user login, ensuring authentication, sending chat messages, displaying chat messages dynamically, displaying the online user list dynamically, and so forth.

However, one of the most prominent requirements in developing a chat application lies in responding to the user in real time and displaying user information quickly so that users do not wait for a long time. Obviously, we have to display the online users' statuses in due course: neither permitting the display of offline users as if they were online, nor enabling the display of the already-online users (except for some special cases).

To achieve this goal, you must support in-time communications between the server side and the client side. This task used to be accomplished with the help of thesetIntervalorsetTimeoutfunction of JavaScript. However, with the emergence of various AJAX frameworks (especially ASP.NET AJAX) based upon ASP.NET platform, the above two functions were rarely used.

In the ASP.NET AJAX framework, the Timer control helps, when the requirements of in-time communications and not updating the whole page can be met with the combination of the UpdatePanel control and the Timer control.

In detail, the entity objects involved in constructing a web chat room module mainly include the chat users, the chat information, and the chat room. In object-oriented terms, we must abstract and encapsulate the three objects, which are utilized to achieve the related operations in the chat room module in this article.

One of the points worth noticing is that we've adopted a simple way to deal with the chat user information-it is persisted in the server side buffers, not in the databases and various files.

When the user logs into the system, he has to input his account name and password. If the current chat room does not contain this account information, he can log in using any temporary password. However, if the current chat room does contain this account information, the just-entered password and the one saved in the buffer will be compared. If they are the same, the current user can log in; otherwise, he will be prompted to re-enter the information or change to other account information. Figure 1 gives the main page of the web chat sample application.


Figure 1-the running-time snapshot for the main chatting interface

As you've seen, herein the valid users can send and receive messages, view the current online user list, and so forth.

A Few Words About the Timer Control

There are three ASP.NET AJAX server controls introduced to manipulate and maintain the chat application, i.e. ScriptManager, UpdatePanel and Timer. Here we're mainly interested in the Timer control, which bears the responsibility for sending the synchronous or asynchronous requests to the server at specified fixed time intervals. This control is usually used in combination with the UpdatePanel control to update some part of a page asynchronously. What's more, it can also be used to "PostBack" the whole page in regular time.

One of the important points worth noticing is that, as an Ajax control, the Timer control is different from that defined within the "System.Threading" namespace. The former is defined based upon the latter, with the main purpose of generating the client-side scripts so that the client side can send out requests to the server side on schedule.

For clearer reference, we've listed the four members of the Ajax Timer control in the table below.

Property or Event name

Description

Enabled

Indicates whether to enable the tick event.

Interval

Specifies the interval time.

Tick

Specifies the task to be executed after the tick event is triggered.


Implementing the Web Chatting Module

In this section, we will delve into the implementation of the web chat module, which mainly involves the general flow, the entity class, the login sub-module, and the main chat page, which will be examined in detail below one by one.

(1) The General Chat Flow

The chat flow is rather clear to follow. First, the user should log in and his identify should also be authenticated. Then, the user enters the chat main interface, where he can deliver his chat messages and view the current chat records and the online users. At the same time, the system will have to update the online user-related time information in good time, so that the valid online users will not be kicked out of the chat lobby. In a rough style, Figure 2 gives the related chat flow.


Figure 2-the rough chatting flow

Next, let's examine the three entity classes mention above.

(2) The Three Entity Classes

At the beginning of this article, we pointed out that the web chat room module in this sample is mainly comprised of three entity classes, i.e. the chat users, the chat information, and the chat room, where the chat room class will invoke the other two classes.

For simplicity, we've only listed the members of the above three classes in the figure form (see Figure 3, 4 and 5 below).


Figure 3-members of the ChatUser class 


Figure 4-members of the Msg class 


Figure 5-members of the Room class 


The Login Module

To identify each online user, he or she must log in first, and then enter the chat room to chat. In this case, we have merged the login and register functionalities into one module.

The Login.aspx page bears a strong similarity to most general login pages, except for the Ajax effect. Herein, three Ajax controls are utilized, i.e. ScriptManager, UpdatePanel, and UpdateProgress. Figure 6 illustrates the design-time snapshot of the Login.aspx page.


Figure 6-the design-time snapshot of page Login.aspx

Note here the "Login" button is put inside the UpdatePanel control to achieve the Ajax effect. Moreover, we've also defined an UpdateProgress control to gain more friendly interaction during the course of logging in.

Next, the ASP.NET built-in validate controls are used, all of which are located outside the UpdatePanel control. When you start this page and click the "login" button you will see a humanistic and illustrative animation appear at the upper right corner of the page until the populated data have been validated, as is shown in Figure 7.


Figure 7-using a UpdateProgress control related animation to gain better user experience


Author's Note: Some of the ASP.NET validation controls are not compatible with some of the controls shipped with the ASP.NET AJAX framework, so that you may run into problems when you put them together. To improve this situation, Microsoft has released another set of validater controls compatible with the ASP.NET AJAX framework, whose functionalities are almost the same as the ones built into ASP.NET. If you are interested in this, please refer to the ASP.NET AJAX official website.

HTML Code

The following lists the key HTML markup code of the login.aspx page:

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

<div style="text-align: center">

<span style="font-size: 14pt; color: #3300ff"><strong>

<br />

FIRST LOGIN, THEN CHAT!<br />

</strong></span>

<br />

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

<br />

<table width="400" cellpadding="0" cellspacing="2" align="center" border="0">

<tbody>

<tr>

<td>

&nbsp; &nbsp; &nbsp; &nbsp;User Name:</td>

<td>

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

</tr>

<tr>

<td>

&nbsp; &nbsp; &nbsp; &nbsp;Password:</td>

<td>

<asp:TextBox runat="server" ID="txtPassword" TextMode="Password" />

<br />

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtPassword"

ErrorMessage="The password cannot be empty" Display="Dynamic"></asp:RequiredFieldValidator></td>

</tr>

<tr>

<td>

&nbsp; &nbsp; Input your password again:</td>

<td>

<asp:TextBox runat="server" ID="txtRetypePwd" TextMode="Password" />

<br />

<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtRetypePwd"

ErrorMessage="The reentered password cannot be empty" Display="Dynamic"></asp:RequiredFieldValidator>

<br />

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtPassword"

ControlToValidate="txtRetypePwd" ErrorMessage="The two passwords must be the same" Display="Dynamic"></asp:CompareValidator></td>

</tr>

</tbody>

</table>

<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">

<ProgressTemplate>

<div class="loading">

Verifying the logging in info......</div>

</ProgressTemplate>

</asp:UpdateProgress>

<br />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:Label runat="server" ID="lblMessage" />

<br />

<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />

</ContentTemplate>

</asp:UpdatePanel>

&nbsp;&nbsp;

<ul>

<li style="text-align: center">If it's the first time that you log in , then you can enter any temporary password to enter the chat lobby.</li><li style="text-align: center">

If you've logged into the system and not been overdue, just enter your temporary password to

reenter.</li></ul>

</div>

</form>

As is shown above, when the "login" button is clicked, its related click event handler is triggered to perform the register and logging in operations. This is implemented in the following code:

protected void btnLogin_Click(object sender, EventArgs e)

{

System.Threading.Thread.Sleep(3000);

string userName = this.txtUserName.Text.Trim();//username

string password = this.txtPassword.Text.Trim();//password

string retypePwd = this.txtRetypePwd.Text.Trim();//reentered password

//The user are in the chatting room, but the password just entered is incorrect

if (Room.Instance.UserIsChatting(userName)&&Room.Instance.GetUser(userName).Password != password)

{

this.lblMessage.Text = "Please enter the right password";

}

else//login successfully

{

if (!Room.Instance.UserIsChatting(userName))//The entered username is not chatting

{

Room.Instance.AddUser(userName, password);//add the user

//send out a system message

Room.Instance.SendMessage(String.Format("{0} Enters the chatting room", userName));

}

Room.Instance.GetUser(userName).Update();

FormsAuthentication.RedirectFromLoginPage(userName, false);

}

}

First, check the chat room to see whether the user exists or not. If so, then continue to verify the password. Moreover, if the password is valid, logging in is successful; otherwise, the user is required to re-enter his password. If the current user does not reside in the chat room, then he is joined to the system, and after that, he is allowed to enter the chat room.

Note that to gain a clear impression of the prompt effect when the system is loading, we purposely let the system sleep three seconds.

Next, let us take a look at the main chat Default.aspx page information.

Designing the Default.aspx Page

The main chat functionalities are performed inside the Default.aspx page, which is mainly composed of three UpdatePanel control and three corresponding Timer controls. Here, the three UpdatePanel controls are utilized to carry out the tasks of sending out and accepting chat messages, and showing the online user information, respectively.

To reduce system resource consumption, we set all theUpdateModeproperties of each of the three UpdatePanel controls toConditional. In contrast to the three UpdatePanel controls, the three corresponding Timer controls are used to accept the chat information on schedule, acquire the online user list in real time, and update the active time information of all the online users, respectively.

In addition, to achieve more plentiful styles in terms of chat content, users can specify the color, font, and expression pictures for their own messages. You can refer to Figure 1, shown earlier, to view the running time snapshot of the main chatting page.

By the way, because the HTML code of the Default.aspx page is so long, and all of it is basic ASP.NET related operations except for the above-mentioned three types of ASP.NET AJAX server controls (ScriptManager, UpdatePanel, and Timer), we omit the code listing here. However, you can refer to the downloadable source code accompanying this article (see the link at the bottom of this page) for more detailed information.

Programming the Default.aspx.cs File

The programming logic within the Default.aspx.cs file is also simple and clear. On the whole, it will perform four tasks: sending out a message, accepting a message, showing the online user list, and updating the active time of the users. In this case, the latter three tasks are done inside the Tick event function of the related Timer controls, because they need to be called repeatedly. However, the task of sending out a message is accomplished when the user clicks the "Send" button, where the above-mentioned three classed associated methods are invoked to perform the corresponding tasks.

The following gives the complete source code of the three Timer controls related to Tick event handlers:


//Get a list of the online users

protected void Timer2_Tick(object sender, EventArgs e)

{

StringBuilder sb = new StringBuilder("<ul>", 300);//

foreach (ChatUser user in Room.Instance.GetAllUsers())//iterate through every online user and construct a string

{

string temp = Server.HtmlEncode(user.Name);//encode

sb.Append("<li><a href="#" onclick="javascript:document.getElementById('mtowho').value='" + temp + "';">" + temp + "</a></li>");

}

sb.Append("</ul>");

UserList.InnerHtml = sb.ToString();

}

//acquire the chat info

protected void Timer1_Tick(object sender, EventArgs e)

{

StringBuilder sb = new StringBuilder(3000);//the string mode of the chatting info

foreach (Msg chatMessage in Room.Instance.GetAllMessages())//iterate through all the info and add them all

{

string UserName = Server.HtmlEncode(chatMessage.UserName);//the user name of the sender

string Message = Server.HtmlEncode(chatMessage.Message);//sending info

string OtherName = Server.HtmlEncode(chatMessage.OtherName);//the user name of the receiver

string Color = Server.HtmlEncode(chatMessage.Color);//the color of the message

string DateTime = Server.HtmlEncode(chatMessage.DateTime.ToLongTimeString());//sending data time

string Img = Server.HtmlEncode(chatMessage.Img);//expression symbol

sb.Append("<font color="#FF0000">" + DateTime + "</font>");

sb.Append(" [<font color="#663300">" + UserName + "</font>] talks to [<font color="#663300">");

sb.Append(OtherName + "</font>]:");

string msg = Message;

if (chatMessage.Color != "") msg = "<font color="" + chatMessage.Color + "">" + msg + "</font>";

if (chatMessage.IsBold == "1") msg = "<b>" + msg + "</b>";

if (chatMessage.IsBold == "2") msg = "<i>" + msg + "</i>";

if (Img != "") sb.Append("<img src=face/" + chatMessage.Img + ">");

sb.Append(msg);

sb.Append("<br/>");//succeed in constructing a piece of message

}

ChatContent.InnerHtml = sb.ToString();

}

//send out the chatting info

protected void Button2_Click(object sender, EventArgs e)

{

string message = UserInputTextBox.Value;//message

string userName = User.Identity.Name;//userName

string othername = mtowho.Value;//the username of the receiver

string color = mfcolor.Value; //the color of the message

string img = elist.Value;//the expression symbol

string isbold = mfont.Value;//if is bold or italic

Room.Instance.SendMessage(userName, othername, message, isbold, color, img);//send

UserInputTextBox.Value = "";

UserInputTextBox.Focus();

}

//update the online time of the user

protected void Timer3_Tick(object sender, EventArgs e)

{

string userName = User.Identity.Name;//userName

Room.Instance.GetUser(userName).Update();

}

As you've seen, we have already provided thorough explanations for each of the above lines, so we will not dwell upon them.

As of now, we've succeeded in setting up a mini chat room module of a possible larger chat project.

-DOWNLOAD SOURCE-

Summary

In this article, we have leveraged the ASP.NET AJAX server side framework to succeed in constructing a simple chat room application. Although in real scenarios things are obviously rather more complex than what we have implemented in this sample, through this demonstration we've learned the basic routine for constructing an ASP.NET AJAX server-centric-based application. In contrast to older solutions that directly manipulated the XMLHTTP object, whether considering simplicity, maintenance, or development efficiency, the more modern approach revealed here shows a real improvement. 

One last word: the sample chat application was built under VS2008; however, you be able to get it to work easily in a VS2005 environment since is uses nothing related to ASP.NET 3.5.

blog comments powered by Disqus
ASP.NET ARTICLES

- Implementing ASP.NET 4.0 Page.MetaDescriptio...
- ASP.Net Development Tips
- Intro to Sessions in ASP.Net
- Google Maps API Introduction in ASP.NET usin...
- Creating an ASP.NET 3.5 Gridview Image Galle...
- Encrypt QueryString in ASP.NET 3.5 using VB....
- ASP.NET 3.5 Drop Down List Controls
- Connect to Access Database with ASP.Net
- Secure Audio Streaming with ASP.Net and Flash
- Dynamic Sitemap and Navigation in ASP.Net
- Implement Gzip and Deflate Compression in AS...
- Run ASP.Net in Ubuntu with Apache
- ASP.Net Mono Website Contact Forms
- ASP.Net URL Rewriting Methods
- Murach`s ASP.NET 4 Web Programming with C# 2...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 9 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials