Introduction
Here is a simple Chat application to demonstrate the use of XMLHttpRequest
(AJAX) in ASP.NET. This is a one to one user chat application, but can be easily extended to support multi user chat also.
As for a demo application, no extra user details are maintained while user registration or no CAPTCHA check or other Security is used.
The main code which is responsible for the AJAX communications is the same as is explained in my previous article which can be found at AJAXDemo.aspx.
So the function AJAXRequest()
is used for transferring all the data between the browser and the server.
Background
For all the details regarding the AJAXRequest() function,
please refer to AJAXDemo.aspx.
In this chat application, some part of data (e.g. RequestCode
, username
, password
) is sent through the HTTP headers, and some data like the message
and userlist
is sent normally in the content.
This easily explains the use of most of the AJAX data exchange possibilities.
Using the Code
The demo application is a ASP.NET web application. It uses Microsoft SQL database to store user messages and user logins.
The database .mdf is included in the APP_Data folder, and also the file "DatabaseScript.sql" contains all the database scripts to setup a new database.
Currently, I have commented out the code for maintaining the message history in Database stored procedure, but it can be enabled if one wants.
The communication between browser -> Server -> browser happens in the following way:
- Client(browser) sends the request along with the
RequestCode
. - Request code is parsed at the server to determine what the request is for. (E.g..
Login
, Logout
, SendMessage
, ReceiveMessage
, etc.) - Server Handles the request, processes it and sends the appropriate Response back, along with the requested data.
- Recipient client always polls the Server for Messages. Once Server has Message for Recipient, the message is sent in the response from server.
var MessagePollingInterval = 3000 ;
var OLUsersPollingInterval = 9000;
These are variables that hold the polling interval.
Messages are exchanged from and to server in an encrypted way. The encryption/decryption algorithm used in this application is the simple substitution cipher.
var EncryptionKey = 3;
This holds the encryption key which should be the same at the client and server end.
Following are the encryption/decryption functions:
function Encrypt(PlainText, Key) {
var to_enc = PlainText.toString().replace(/^\n+/, "").replace
(/\n+$/, "");
var xor_key=Key;
var the_res="";
for(i=0;i<to_enc.length;++i)
{
if (to_enc.charCodeAt(i) <= 32) {
the_res += String.fromCharCode((to_enc.charCodeAt(i)));
}
else {
the_res += String.fromCharCode
((to_enc.charCodeAt(i)) - Key);
}
}
return(the_res);
}
function Decrypt(CipherText, Key) {
var to_dec = CipherText;
var xor_key = Key;
var PlainText = "";
for (i = 0; i < to_dec.length; i++) {
if (to_dec.charCodeAt(i) <= 32) {
PlainText += String.fromCharCode((to_dec.charCodeAt(i)));
}
else {
PlainText += String.fromCharCode
((to_dec.charCodeAt(i)) + Key);
}
}
return (PlainText);
}
A similar function is implemented in the C# code in the server side handler to perform encryption/decryption.
Here is a code snippet of how the message is sent through an Ajax request:
function SendMessage() {
if (ValidateSendMessageWindow()) {
var URL = "SecureChatServer.ashx";
var covert = "False";
if (URL == null) { alert("Request URL is Empty"); }
else {
HTMLmessage = document.getElementById('Message').value.toString().replace
(/\r\n?/g, '<br/>');
message = Encrypt(HTMLmessage, EncryptionKey);
recepient = Encrypt
(document.getElementById('Recepient').value, EncryptionKey);
AjaxRequest(ProcessSendMessageResponse, URL, "POST",
{Message:message , Recepient:recepient}, '', { RequestCode: 'SC005'});
}}}
All the required data is passed to the 'AjaxRequest
' function which sends the data to generic handler 'SecureChatServer.ashx' .
Here is the code which is executed for the RequestCode
: SC005:
LoggedInUser = userlogin.IsUserLoggedIn(SessionID, UserIPAddress);
if (LoggedInUser != null)
{
Messages newMessage = new Messages();
Message = Decrypt(context.Request.Params["Message"],
EncryptionKey);
Recepient = Decrypt(context.Request.Params["Recepient"],
EncryptionKey);
if (newMessage.WriteMessage(LoggedInUser, Recepient,
Message))
{
context.Response.AddHeader("CustomHeaderJSON",
"ResponseStatus:'RS-OK'");
}
else
{
context.Response.AddHeader("CustomHeaderJSON",
"ResponseStatus:'RS-Failed'");
}
.
.
.
}
This response with the newly added success/failure indicators in HTTP header is sent back by the server.
And finally after the AJAX request is completed, the Handler
function is executed. All the responses from the server are available in the handler
function.
In this case, the handler
function specified is 'ProcessSendMessageResponse
', and here is its definition:
function ProcessSendMessageResponse() {
var ResponseStatus = GetHeader(ResponseHeaderJSON, 'ResponseStatus');
if (ResponseStatus == "RS-OK") {
}}
As you see, the value of 'ResponseStatus
' is extracted from the Response
HTTP headers which are readily available in the function. As the 'ResponseHeaderJSON
' is a JSon string, the function 'GetHeader
' is used to extract a particular value in JSon string.
The value of the 'ResponseStatus
' is then checked to notify Success/Failure in sending the message.
A similar process is used for all the functions such as Receive message, Login, Logout, Get Online Users list, etc.
Most of the UI features like Window dragging, tooltips, smooth show/hide, etc. are implemented using JQuery libraries.
Points of Interest
This is a basic implementation and can be extended to support other features like more detailed user Registration, multi user chat and other features of normal Chat application.
The main purpose of this application is to provide a simple and clear understanding of how XmlHttpRequest
with ASP.NET can be used for different purposes in a Web Application.