| Chat with ASP.NET and Ajax |
| Section: ASP.NET | Rating: 3.2 |
 | CodeGod submitted this resource The member's homepage is http://www.codegod.de Visit the profile here |
Attachment
Introduction
This article describes how to implement a web-chat with ASP.NET and Ajax. In the first part I introduce the technologies I used for the application. Then I explain the concept of a chat and in the last part I present the main implementations.The goal of this article is to show the interested reader how to develop a chat without browser-plugins or java-applets, just pure HTML and javascript.
Which technology is used?
A web-chat is an application for which dynamically generated HTML is needed and client-server interaction. Therefore ASP.NET 2.0 has been used and for the client-server-intercation without postbacks of course Ajax. We could use Ajax.NET but to keep it simple we decided to use the Ajax-implementation from Mike Schwartz called AjaxPro.
To do all serverside calls from javascript with AjaxPro you need to do the following:
1. Add a reference to the Assembly AjaxPro.dll which you can download
here.
2. Add a class to your project.
3. Add a method to that class you want to call by script and mark it with the Attribute
AjaxMethod4. Register the class in the Page_Load-handler of your aspx-page from which you want to use it. With
AjaxPro.Utility.RegisterTypeForAjax(typeof(MyAjaxClass));
That's all. Other details will be explained in the implemenation-part of the article.
The design of a Chat?
There are different kind of chats. In this example I designed a chat in which users can login with their username and password. Then they can enter the chat and send messages. The messages are visible for all other chat-users. It is a public chat, where all logged in chatters can communicate together.
Figure 1The Session holds a CurrentChatter, a user that has just logged in. The chatter enters the chat (1) by navigating to the chat-page (Chat.aspx). After a chatter has entered, he has the possibility to send messages by typing text to a TextBox and pressing the enter-key. Then the chat-message is sent to a ChatMessageQueue (CMQ) which in our example is stored in the Application (2). Okay, now the message lies in the CMQ on the server. We have to get it from there, so that every client can see it. Therefore we have a javascript-timer running, that gets all new messages from the CMQ and displays it in an HTML-DIV for example (3).
Sounds simple, doesn't it? Here is what we need to do, to implement points 1 to 3.
(1) AddChatter (store chat-user)
Save the curent user after successful login to the Session.
(2) AddToMsgQueue
When sending a chat-message you need to store this in the CMQ. You will have to invoke this action from a javascript function. The scriptcode calls a serverside method via Ajax that has the ability to access the ASP.NET-Application.
(3) GetMsgsFromQueue
Here we need to check in a javascript-timer every n seconds, if there are new chat-messages for the client to display. So we poll the CMQ for new messages by an Ajax-method. If we have new messages, theses are transformed to a string that can be displayed as a list in a chatwindow.
The implementation
So far the theory, now the concrete coding. Here are the datatypes we need:
Figure 2Chatter
This class has an Id to identify a chatter internally and a name for the display. The LastMsgKey is the key of the last message a chatter received. When the timer polls for new messages, this key is used to find out, if there are messages in the CMQ after that message. The messages are stored in a list in the Application. If there are messages in the list for the chatter after his LastMsgKey, these messages have to be fetched.
ChatMsg
A chat-message has a Key (Guid), the name of the chatter who sent this message and the message itself as string.
ChatMgr
The ChatMgr handles the list of all logged in chatters and the CMQ. You can add messages to the CMQ and get them back from it. It also has methods to get a list of all available chatters as Html. The code could be optimized here: The display-logic for chatters and chat-messages could be placed to another class.
The HTML-components are located on the WebForm Chat.aspx. We have
divChatBox: A DIV for all chatmessages.
divChatters: A DIV for all logged in chatters
txtMessage: A TextArea for the text that a chatter can type and send.
When the page loads, all logged in chatters and the available messages are loaded and displayed in the corresponding HTML-elements. Here is the javascript-code which is called cause we add the calls to it in the onload-handler of the Chat.aspx-page:
function fillUsers()
{
ChatMgr.GetChattersHtml( fillUsers_CallBack );
}
function fillUsers_CallBack( res )
{
var userBox = document.getElementById('divUsers');
if( res.value == '' )
{
setTimeout( "fillUsers()", 5000 );
return;
}
userBox.innerHTML = res.value;
setTimeout( "fillUsers()", 5000 );
}
function getMsgs()
{
ChatMgr.GetMsgsFromQueue( getMsgs_CallBack );
}
function getMsgs_CallBack( res )
{
var chatBox = document.getElementById('divChatBox');
chatBox.innerHTML += res.value;
scrollContentDown();
setTimeout( "getMsgs()", 2000 );
}
The _callback-functions are asynchronous callbacks. They are initiated by the Ajax-calls of the ChatMgr. In the end of a _callback-function setTimeout is called to invoke the function again after a certain period.
Now how is the ChatMgr able to call a serverside function from script? See the examle of the call GetChattersHtml:
[ AjaxMethod( HttpSessionStateRequirement.Read ) ]
public string GetChattersHtml()
{
string result = "";
if( SessionMgr.Instance.OnlineUsers == null )
return result;
foreach (Member member in SessionMgr.Instance.OnlineUsers.Values )
{
result += "<div class='ChatUser' style='width: 280px'>";
result += "<table border=0 cellpadding=0 cellspacing=0><tr>";
result += "<td>" + UserImage.GetHtml( member.ID, "" ) + "</td>";
result += "<td> <b>" + member.Name + "</b></td>";
result += "</tr></table>";
result += "</div>";
}
return result;
}
The method of the ChatMgr is marked with the Attribute AjaxMethod. To get access to the current Session, we add the HttpSessionStateRequirement.Read to that Attribute. Now the method can read all logged in users from the Session and give back the list as HTML. If we also want to be able to write to the HttpSession we could use HttpSessionStateRequirement.ReadWrite.
For the other code-parts it's just the same: The script calls the serverside method, the method returns the return-values which are read-out in an asynchronous callback-function in script.
Here is the logic for sending messages to the queue:
function sendMessage()
{
var newMsg = '';
var chatBox = null;
var msg = document.getElementById('txtMsg').value;
if( msg == '' )
return;
document.getElementById('txtMsg').value = '';
newMsg = ChatMgr.AddToMsgQueue( msg ).value;
chatBox = document.getElementById('divChatBox');
chatBox.innerHTML += '<span class=\'ColorOwn\'><b>' +
newMsg.Name + ': </b>' + newMsg.Message + '</span><BR>';
}
On pressing return, the function sendMessage is called and adds the message to the CMQ by calling the method
AddToMsgQueue of the ChatMgr which again is an Ajax-method.
If you have further questions on how to build an ASP.NET-Ajax-Chat or want codegod to implement it for you, just send us a mail.
You can see the codegod-chat in action
here after logging in. Have fun!
Zin Ko Aung7/26/2007 10:11:00 AM  | Why don't provide source code to download?
FYI
|
Asiri7/26/2007 12:29:32 PM  | CODE PLEASE
I WANT TO SEE YOUR CODE
|
peter7/26/2007 5:49:31 PM  | jaj
Can you link your code download for studying!
|
CodeGod7/27/2007 5:00:11 AM  | Source Code
I will add a zip on Friday evening!
|
rakesh7/27/2007 12:31:59 PM  | Ajax chat
Hi ,plz display the code also
|
CodeGod7/27/2007 8:05:26 PM  | Source code added
Hi guys, I added the source-code as zip. The necessary code is included, bt without the HTML, but I think you'll get the idea. If not, add comments or shot me a mail.
|
Christian Schiffer7/27/2007 9:12:05 PM  | Seams interesting
However the zipped files did not deliver the neccecerry dll s for building the chat, yes I found and downloaded the ajaxpro.dll but there are still files missing, also you should add the sourcecode of the dll's if this chatroom should have hope to have success for open source developement.
But till now great job :)
|
CodeGod7/27/2007 9:24:16 PM  | The next project
Well, Christian, you are right, the code for the chat is just an extract of the whole project. Problem is, that the chat is included in the codegod-application and has no public interface... but this could be a future-project. Stay tuned, I'll think about it. If you have further interest just send me a mail.
|
DannyR7/27/2007 11:41:35 PM  | Compile Errors
Error 3 The name 'SessionMgr' does not exist in the current context C:\Inetpub\wwwroot\test\App_Code\ChatMgr.cs 183 29 C:\...\test\ Error 4 The type or namespace name 'Member' could not be found (are you missing a using directive or an assembly reference?) C:\Inetpub\wwwroot\test\App_Code\ChatMgr.cs 183 12 C:\...\test\ Error 5 The name 'UserImage' does not exist in the current context C:\Inetpub\wwwroot\test\App_Code\ChatMgr.cs 187 23 C:\...\test\
Should I replace SessionMgr with my own?
|
CodeGod7/28/2007 8:04:33 AM  | Types
Hi DannyR, yes, the classes Member and SessionMgr are my implementations. you have to define your own. I plan to build a separate chat-app and will provide this in some time.
|
Alessandro8/10/2007 5:17:11 AM  | Why dont you publish the whole code?
I´ve downloaded the code and the ajaxpro dll but there are files missing. Why don´t you put the complete project for download?
|
Yogendra Dubey8/13/2007 8:55:14 AM  | Please Provide Code
Please provide code to download .
|
CodeGod8/14/2007 10:23:01 PM  | Source code
Hello!
I will develop a full project for this chat, but I have not much time at the moment. I could not provide the full project cause the chat is integrated to deeply in the codegod-application. I have to extract the funtionality and provide the chat as a module. Thanks for your interest, I will see what I can do...
|
andreia2/27/2008 5:23:44 PM  | Hello
I'm Andreia, I live in Brazil and I'm a developer .... I liked your article about chat, very good! Congratulations! And sorry me my bad english..lol
|
Miles3/26/2008 7:50:35 PM  | I HAVE GOT SOME QUESTIONS & doubts
ITS A GOOD APP BUT.... 1> WHEN DO U CLEAR HttpContext.Current.Application[ CMQ + CN]?.. 2> What is maximum limit of data which HttpContext.Current.Application can store? 3> WHY DID U NOT PREFER 2 USE DATABASE? 4> YOU R SENDING REQUESTS EVERY 2 SECONDS.. WILL THIS NOT JAM UP THE NETWORK?., I HAVE ALSO OBSERVED CHAT FROM GMAIL.COM THERE CHAT DOES NOT SEND CONTINUES REQUESTS. I AM SEARCHING HOW DID THEY DO THAT?.
I AM ALSO DESIGNING A WEB-CHAT APP.. I HAVE USED DATABASE FOR SAVING MY PREVIOUS CONVERSIONS. ARE THERE ANY DRAWBACKS IN USING THAT? ONE BENEFIT I FOUND IS THAT WE CAN ALSO PROVIDE PRIVATE CHAT AND MULTIPLE ROOMS WITH USE OF DATABASE
|
vinodnit4/30/2008 12:49:29 PM  | webchat
how to download the source code
|
Aparna7/8/2008 1:24:28 PM  | Private Caht
I read your feasible code for chat application but i need to maket he application for both private and public chat can u help me plz?
|
Aparna7/8/2008 1:25:30 PM  | Private Chat
I read your feasible code for chat application but i need to make the application for both private and public chat can u help me plz?
|
Farid Moein Vaziri8/23/2008 10:13:03 AM  | SessionMgr
Hi CodeGod
Where should I declare my own SessionMgr? I mean in which class? and in what type it should be instantiated?
Cheers
|
Ajay Kumar9/2/2008 12:48:02 PM  | plz provide me detail source code for chat applicatioon
It is good,thank
|
Amit mohan11/10/2008 2:13:16 PM  | Source Code
I am trying to use chat.aspx page code. But its not working. Can you send me the complete code.
Thanx & Regards Praveen tale
|
adikam12/22/2008 4:55:20 PM  | Build Error
created a website, added ajaxpro.dll, chat.aspx, ChatMgr.cs, ChatMsg.cs, Chatter.cs But when i build solution it says "Error 1 The type or namespace name 'WebAppCodeGod' could not be found (are you missing a using directive or an assembly reference?) C:\Inetpub\wwwroot\Chat\Chat.aspx.cs 11. Where will i get the reference? Am i missing something? Any help would be appreciated..
|
RredCat9/14/2009 4:28:07 PM  | trouble with ajax?!!?
Hi, I have added Utility.RegisterTypeForAjax( typeof( ChatMgr ) ); to Load_Page method. I try to access to ChatMgr instance in init(), fillUsers() and getMsgs() methods (like in your sample). But I have trouble. JavaScript code is breaked after ChatMgr "usage". For example: when I comment ChatMgr "usage" in init() than init() completed, fillUsers() starts to applay.. but it is all.. (getMsgs() isn't applied) What is wrong with Ajax dll? I have used VS2008 and Framework 3.5..
|
vivek06851/19/2010 3:49:46 PM  | What is this....
u disappeared .....from 2 years....
|