Posted by & filed under Ajax & Atlas, ASP.NET.

Chatting with Atlas:

Create Your Own Chat Room

By Andrew Flick and Anthony Lombardo

We have to admit, we still can’t get enough of AJAX. Many of our thoughts revolve around asynchronous page behaviors, and coming up with new ways to break the tired old paradigm of “postbacks”.

When you examine AJAX as a protocol, you quickly realize that it is “chatty”, meaning that there is a lot of back and forth communication between the client and the server. Because all communication is happening asynchronously without interrupting the page, this isn’t really a concern. As a matter of fact, this chatty characteristic could be the basis of a whole new breed of Web applications. What could be better to prove the effectiveness of a chatty protocol than a chat room?

AJAX can be used to create our chat room, but to do it easily, we’ll need some type of client-side framework. Enter Atlas. By now the world has heard about Altas, Microsoft’s framework for creating rich client-side behaviors using JavaScript. Though currently still in beta, Microsoft announced at MIX06 that everyone has been granted a “go live” license for Atlas. If you haven’t yet downloaded it, you can get it from http://atlas.asp.net.

In a plain vanilla AJAX application, you would be forced to hand code most of the client-to-server interactions. With Atlas, that’s already done for you, along with many other useful features, allowing you to concentrate more on your application logic than the communication protocol. Using Atlas, creating a chat application becomes something that you can write in a few hours. You can do so by using the Atlas UpdatePanel in conjunction with PartialRendering, as well as exposing server-side methods to the client-side JavaScript world, by using the WebMethod attribute.

To begin construction of your chat room, create a new Visual Studio 2005 Web site using the Atlas project template. The project template will add all the references you need, as well as provide you with a modified web.config file.

For a functional chat room you’ll need three main features available from the client side:

  • The ability to identify yourself.
  • The ability to send messages.
  • The ability to get new messages.

The first goal of identification can be provided through a textbox for the user to enter in a username, and a button to perform the login action. In addition, a Label can be added to notify the user of any problems that may have occurred while attempting to log in.

Using an Atlas UpdatePanel and partial rendering, the login operation can be completed without requiring a full postback. When PartialRendering is enabled, the contents of the UpdatePanel will be updated asynchronously, without affecting any other part of the page:

<atlas:UpdatePanel runat=”server” ID=”updatepanel”>

<ContentTemplate>

<asp:Panel runat=”server” ID=”LoginPanel”>

<asp:Label runat=”server” ID=”MessageLabel”></asp:Label>

<div>In order to use the Chat, you must first type in a UserName.

Your UserName will be used to identify you when a message is sent.</div>

<asp:TextBox runat=”server” ID=”userName”></asp:TextBox>

<asp:Button runat=”server” ID=”loginButton” OnClick=”loginButton_Click” Text=”Login” />

</asp:Panel>

</ContentTemplate>

</atlas:UpdatePanel>

To ensure that the UpdatePanel will refresh without requiring a full postback, you must turn on PartialRendering. This can be done through the Atlas ScriptManager:

<atlas:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePartialRendering=”true” ></atlas:ScriptManager>

Now it’s time to think about how the messaging process should work. There are a few options for storing and sharing messages, but one of the easiest ways is to put them in the Application Cache. By using the Application Cache, you can provide a way for all sessions to “talk” to each other. To keep things organized, you’ll need to create two supporting classes:

  • User: used to represent a logged in user
  • Message: used to store the sender information and message text

With these two classes in place, the only thing left to do is provide a mechanism for the client to push a message up to the server, as well as a way to pull new messages down from the server. This is where it gets way too cool. Using Atlas, you can mark any Page method with the WebMethod attribute, which then gives you the ability to call that server-side method through JavaScript! For those of you who are familiar with WebServices, this is the same attribute that exposes a method on a WebService. Here’s the code for the server-side method responsible for sending messages:

[WebMethod]

public void SendMessage(string from, string message)

{

User fromUser = this.Users[from];

foreach (User user in this.Users.Values)

{

user.MessageQueue.Enqueue(new Message(fromUser, user, message));

}

}

Server-side methods marked with the WebMethod attribute are made available on the client-side through the PageMethods JavaScript object. So, to invoke the SendMessage method from script, simply use PageMethods.SendMessage, passing any required parameters, making the last parameter the “callback” function used to handle the response asynchronously. Here’s what the client-side function looks like:

function sendMessage(){

var text=$(”messagecomposer”).value;

var uname=$(”userName”).value;

PageMethods.SendMessage(uname,text,sendMessageComplete);

$(”sendmessagebutton”).disabled=true;

}

function sendMessageComplete(){

$(”messagecomposer”).value=””;

$(”sendmessagebutton”).disabled=false;

}

In case you’re confused, the “$” character is a shortcut to document.getElementById, provided by the Atlas framework. It took a while for me to get used to seeing dollar signs all over my code, but it sure does make writing the script a lot quicker.

At this point, you have an application that will send messages, but it isn’t set up to receive them yet. Adding the logic to receive messages requires polling the server for new messages. The polling shouldn’t happen until after the user has successfully logged in, so you’ll need to call RegisterClientScriptBlock from the server during the login process to start up the polling process on the client.

Once the polling process is started, the client will contact the server on a constant interval, calling the GetMessages server-side method. Here is the client-script responsible for that:

function getMessages(){

PageMethods.GetMessages($(”userName”).value,getMessagesComplete);

}

function getMessagesComplete(param){

if(param==””)return;

var messages=eval(param);

if(messages!=null&&messages.get_length()){

for(var i=0;i<messages.get_length();i++){

var msg = messages[i];

$(”messageviewer”).innerHTML=$(”messageviewer”).innerHTML+”<div>”+msg.from+”:

  ”+msg.message+”</div>”;

}

}

}

With writing only 25 lines of JavaScript, you have just created your very own chat room that works without ever posting back to the server. In total, this chat room consists of ~200 lines of C# code, 25 lines of JavaScript, and a simple stylesheet. There is quite a bit of work needed on the UI for this chat room, but luckily there are companies out there that focus on Presentation Layer tools, enabling you to add Spell Checking support, and HTMLInput quickly and easily. Our favorite is Infragistics, but we might be a little biased.

The code accompanying this article is available for download.

Andrew Flick is Product Manager – NetAdvantage Windows Forms Technologies & TestAdvantage for Infragistics, Inc. Prior to joining Infragistics, Andrew played an avid role in presenting on emerging .NET technologies throughout the Midwest to a variety of User Groups as well as numerous Student Groups. As an active member of the INETA Academic Committee, Andrew has authored content on building successful User Groups, as well as numerous white papers on building an effective community. A Microsoft MVP, Andrew joined Infragistics in July of 2004 as a Technology Evangelist, where he was responsible for the creation of reference applications and authoring .NET technology articles for industry leading publications, as well as the world wide delivery of Infragistics’ Technology demonstrations. Andrew currently serves as Infragistics Product Manager for NetAdvantage Windows Forms Technologies & TestAdvantage. As product manager, he spearheads the product management and strategies of Infragistics Windows Forms Product Lines — from establishing the direction through delivery. Working directly with the Director of Development, he sets the direction, plans, and manages product development. Contact Andrew at mailto:andrew@infragistics.com.

Anthony Lombardo is Product Manager of NetAdvantage – ASP.NET Technologies for Infragistics, Inc., and is responsible for spearheading product management and strategies for Infragistics’ ASP.NET product line, working directly with the Director of Engineering to set the direction, plan, and manage product development. Prior to joining Infragistics, Anthony served as a Network Administrator for North Brunswick Board of Education and worked for Rutgers University in their technical support division. Since beginning his career with Infragistics in 2000, Anthony has been involved with every aspect of the development cycle, including playing a key role in the creation of the Presentation Layer Framework for ASP.NET, assisting in the creation and implementation of Infragistics Visual Studio 2005 project plan, and determining the product feature set for NetAdvantage 2005 for Visual Studio 2005. Contact Anthony at mailto:anthony@infragistics.com.

Comments are closed.