Cyber Security & Dot Net Security

Wednesday, September 22, 2010

Build a Web Chat Application using ASP.Net 3.5, LINQ and AJAX (in C# 3.5)

LINQ GUI structure
LINQ Chatroom table structure
LINQ Chatroom
Technologies Used: ASP.Net 3.5, AJAX, JavaScript, C# 3.5, LINQ-to-SQL, MS SQL Server 2000/2005 

Introduction:
A Java Programmer friend of mine once asked me if I have ever built a web chat application. I said "No". He then asked me if I were to build a really simple, monitored, bare minimum, working web chat application, how long do I think will it take (something to that effect). I said, "I don't know". A few days had passed, one lazy evening, I was surfing the web looking for ASP.Net web chat applications. It seems that I can't find one that is simple enough to implement. So I decided to just build something simple from scratch. When I say simple, that just means that: I'm am going to try to build this web chat as fast as possible, with very minimal planning or architecturing. So what you will read below are my notes after I got done building the web chat application. Here's an example of how the chatroom page looks like: 


Requirements:

We will create a very simple web chat application using the latest ASP.Net 3.5 technologies from scratch just for fun. This chat application will contain 2 web pages, the login page and the chatroom page. Most of the tutorial will be focused on the chatroom page. Some of the things that I want to accomplish are as follows:
  • Must be accessible anywhere, and no need to download and install any components. This is why we're going to create a web chat.
  • Web chat must be "flicker-free". This is where AJAX will be very handy.
  • We want to be able to monitor chat conversations using a database. We will use MS SQL Server to store conversations and user information.
  • No use of frames. I read somewhere that frames are evil, and I kind of agree with that.
  • Use of dynamic SQL using LINQ-to-SQL instead of stored procedures for a super fast coding. Remember that we're doing this for fun.
  • No use of Application Variables. I've seen some examples on the web that uses application variables and I just don't like this idea.
The Fun Begins!

1. First, we need to build our database using MS SQL Server 2000/2005. Note that we will only create the bare minimum just to get the web chat application going. Listed below are the table names and their primary usage for our chat application. 

  • User: Contains user information. Feel free to add your own fields like address, city, and so on.
  • Message: Will hold the messages sent by the users while chatting.
  • Room: Contains information about different rooms. This means that you can have more than one room. But for the purposes of this tutorial, we will only use one room for now.
  • LoggedInUsers: Will hold users logged-in/chatting in the chatroom(s). In short, if a user enters in a room, we will save their information here, in this way, we can show the list of users chatting in a specific room.
2. Create an ASP.Net 3.5 website using Visual Studio 2008. For now, let's create this in C# 3.5. I should have the VB 9.0 version in a week (so check back for the VB version). 

3. Create a Login page. Our chat application will require all users to be logged in. Creation of the registration page for a new user will not be discussed in this tutorial. Although you can see that the username and password are in plain text, in the real world I recommend using hashed values instead. The login page is really simple; if you’re authenticated then you will be redirected to room 1. Again, you can customize this so that your users can pick from a number of rooms. 

4. Create the Chatroom page. 

First let's talk about the main structure of the GUI (graphical user interface). As shown on the the picture, we have the following: 

  1. Div tag for Messages: This will house/show/contain the messages that are sent by the chatters. No frames here.
  2. TextBox: This is where chatters will be typing their messages.
  3. Send Button: Sends the messages when clicked.
  4. Div tag for Chatters: Shows the chatters logged-in to the current room.
  5. Log-out Button: Logs out the user from the current room.
  6. Update Panel: This is not a visible part of the GUI, but is one of the most important part of the chat application. This panel will make sure that the messages we see is "Flicker-Free".
  7. Timer Control: This is also not visible in the GUI. The function of the timer control is to refresh our page every 7 seconds.
That's it for now, we will look at these components in more detail in a little bit. 

Now let's look at the flow of the web application.
  1. All chatters must be authenticated. In short, everyone who wants to chat must login. The Default.aspx is our login page, all unauthenticated users will be redirected here. This is easily configured in our web.config file. See code below: 

               <authentication mode="Forms">
                    <forms name=".ASPXAUTH" loginUrl="Default.aspx"/>
                </authentication>
       
              <authorization>
                  <deny users="?" />
               </authorization>


    Save the UserID in a Session before redirecting the user to the chat room page. For simplicity's sake, the user is then automatically redirected to "room 1" when authenticated. Note: You can redirect the user to a page where you have a list of chatrooms and have your user pick from the list before you redirect them to the chat room page, simply add rooms to the Room table, and list them in a page. 
       protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
             {
                   LinqChatDataContext db = new LinqChatDataContext();
       
                  var user = (from u in db.Users
                               where u.Username == Login1.UserName
                                && u.Password == Login1.Password
                                select u).SingleOrDefault();
        
                 if (user != null)
                    {
                        e.Authenticated = true;
                       Session["ChatUserID"] = user.UserID;
                       Session["ChatUsername"] = user.Username;
                    }
                    else
                  {
                       e.Authenticated = false;
                  }
               }
      
              protected void Login1_LoggedIn(object sender, EventArgs e)
               {
                   Response.Redirect("Chatroom.aspx?roomId=1");
                }


  2. The user then arrives in the chat room page. The first thing we check is the roomID from the query string. Again for simplicity's sake, the code below assumes that you passed an integer value for the roomID. You should, however, make sure that the roomID is not null and can be converted to an integer. The code below also shows that the roomID value is assigned to an invisible Label Control called lblRoomID. We could have just as easily saved this value in a Session variable, but this is my preference since we don't really need to know the roomID in other pages than the one we're currently in. We need to know the roomID value throughout the page like when we're retrieving messages for this room, or when we're inserting messages for this room, or when we're retrieving users for this room, or when we're logging users out of this room, etc., you get the idea right? 

                      // for simplity's sake we're going to assume that a
                       // roomId was passed in the query string and that
                       // it is an integer
                      // note: in reality you would check if the roomId is empty
                       // and is an integer
                      string roomId = (string)Request["roomId"];
                        lblRoomId.Text = roomId;


  3. We want to tell all chatters that this user just logged in. So we add/insert this user to the LoggedInUser table specific to this room. Then we retrieve and show all the users for this room. 

    The call to insert a message: 

      this.InsertMessage(ConfigurationManager.AppSettings["ChatLoggedInText"] + " " + DateTime.Now.ToString());


    The insert message method: Notice in line 84 that I'm removing the less than characters "<", simply because it blows up the app and I'm in no mood to make my web app a little bit insecure by setting the ValidateRequest to false. I was in a hurry when I wrote this web chat, now I'm thinking I should have used the AJAX Control Toolkit's Filtered Text Box instead of a regular text box where you type your messages. Oh well, maybe in part 2. 

               private void InsertMessage(string text)
               {
                    LinqChatDataContext db = new LinqChatDataContext();
       
                    Message message = new Message();
                    message.RoomID = Convert.ToInt32(lblRoomId.Text);
                    message.UserID= Convert.ToInt32(Session["ChatUserID"]);
        
                    if (String.IsNullOrEmpty(text))
                    {
                        message.Text = txtMessage.Text.Replace("<", "");
                        message.Color = ddlColor.SelectedValue;
                    }
                    else
                    {
                        message.Text = text;
                       message.Color = "gray";
                    }
        
             message.ToUserID = null;           
                    message.TimeStamp = DateTime.Now;
                    db.Messages.InsertOnSubmit(message);
                    db.SubmitChanges();
                }


    In the web.config file: 

            <appSettings>
               <add key="ChatLoggedInText" value="Just logged in!"/>
            </appSettings>


    Then we add/insert a message in the Message table saying that this user just logged in. We also need to retrieve the messages and show the updated messages in the messages box. And yes, we add or retrieve data specific to this room. Rather than I keep saying "specific to this room" all the time, I would like to say that everything we do in this chat room page is specific to this room, which simply means, we need to pass in the roomID. 

               /// <summary>
               /// Get the last 20 messages for this room
               /// </summary>
               private void GetMessages()
               {
                   LinqChatDataContext db = new LinqChatDataContext();
       
                   var messages = (from m in db.Messages
                              where m.RoomID == Convert.ToInt32(lblRoomId.Text)
                                  orderby m.TimeStamp descending
                                  select m).Take(20).OrderBy(m => m.TimeStamp);
       
                   if (messages != null)
                   {
                       StringBuilder sb = new StringBuilder();
                       int ctr = 0;    // toggle counter for alternating color
       
                       foreach (var message in messages)
                       {
                           // alternate background color on messages
                           if (ctr == 0)
                           {
                               sb.Append("<div style='padding: 10px;'>");
                               ctr = 1;
                           }
                           else
                          {
          sb.Append("<div style='background-color: #EFEFEF; pading: 10px;'>");
                               ctr = 0;
                           }
       
                           if (message.User.Sex.ToString().ToLower() == "m")
    sb.Append("<img src='Images/manIcon.gif' style='vertical-align:middle' alt=''>  " + message.Text + "</div>");
                           else
                             sb.Append("<img src='Images/womanIcon.gif' style='vertical-align:middle' alt=''>  " + message.Text + "</div>");
                     }
     
                       litMessages.Text = sb.ToString();
                   }
               }

  4. We also need to retrieve all the users logged in to this room so we can list them in the users div tag. Notice that users other than yourself will be clickable, this is because in part 2, I will show you how to send a private message to another chatter. 

                private void GetLoggedInUsers()
               {
                   LinqChatDataContext db = new LinqChatDataContext();
       
                   // let's check if this authenticated user exist in the
                   // LoggedInUser table (means user is logged-in to this room)
                  var user = (from u in db.LoggedInUsers
                        where u.UserID == Convert.ToInt32(Session["ChatUserID"])
                               && u.RoomID == Convert.ToInt32(lblRoomId.Text)
                               select u).SingleOrDefault();
       
                   // if user does not exist in the LoggedInUser table
                   // then let's add/insert the user to the table
                   if (user == null)
                   {
                       LoggedInUser loggedInUser = new LoggedInUser();
                       loggedInUser.UserID = Convert.ToInt32(Session["ChatUserID"]);
                       loggedInUser.RoomID = Convert.ToInt32(lblRoomId.Text);
                       db.LoggedInUsers.InsertOnSubmit(loggedInUser);
                       db.SubmitChanges();
                   }
       
                  string userIcon;
                   StringBuilder sb = new StringBuilder();
       
                  // get all logged in users to this room
                   var loggedInUsers = from l in db.LoggedInUsers
                                       where l.RoomID == Convert.ToInt32(lblRoomId.Text)
                                       select l;
       
                   // list all logged in chat users in the user list
                   foreach (var loggedInUser in loggedInUsers)
                   {
                       // show user icon based on sex
                       if (loggedInUser.User.Sex.ToString().ToLower() == "m")
                           userIcon = "<img src='Images/manIcon.gif' style='vertica-align:middle' alt=''>  ";
                       else
                           userIcon = "<img src='Images/womanIcon.gif' style='vertical-align:middle' alt=''>  ";
       
                       if (loggedInUser.User.Username != (string)Session["ChatUsername"])
                               sb.Append(userIcon + "<a href=#>" + loggedInUser.User.Username + "</a><br>");
                       else
                           sb.Append(userIcon + "<b>" + loggedInUser.User.Username + "</b><br>");
                   }
       
                   // holds the names of the users shown in the chatroom
                   litUsers.Text = sb.ToString();
               }


  5. So in simple terms this is what happens. You log-in, when authenticated you get redirected to the chatroom page, when you get to the chatroom page a message is shown on the screen to alert other chatters saying that you logged in.
Now that we know the flow of the web application, let's move on to the details of how certain things work. We will look at the events that happen when an event is triggered. 

Sending a Message:
  1. You will notice that the TextBox control where you type your messages keeps the focus even after you hit the "Enter Key" or when you directly click the send button. This is done in two (2) places: 

    In the BtnSend_Click event: 

       ScriptManager1.SetFocus(txtMessage.ClientID);


    And in the Timer1_OnTick event: 

        ScriptManager1.SetFocus(txtMessage);


  2. You will also notice that you don't have to directly click the "send button" to send a message, you can just hit the "enter key" from your keyboard and it gets the same effect as if you directly hit the send button. Code shown below. 

    <form id="form1" defaultbutton="btnSend" defaultfocus="txtMessage" runat="server" >


  3. There are a few things that happen when you send a message. Here they are in order
    • The message is inserted in the Message table.
    • The messages are retrieved from the Message table.
    • Messages are then shown on the message box. Based on the sex of the chatter, a man or woman icon is shown along with messages.
    • Users are retrieved from the LoggedInUser table.
    • Users are then reconstructed and shown in the list of chatters box. You will notice that all the other users except you is shown as a link. This is because in the next installment of this tutorial we will add on to this code and make other users clickable so that you can chat privately. For now, it's just a placeholder for future code. 

  4. You will also notice that the scroll bar on the div tag for the messages are always set to the bottom of the div, this is because we are calling a client-side function that sets the position of the div scroll to the bottom every single time the page re-loads. 

    From the body tag: 

    <body style="background-color: gainsboro;" onload="SetScrollPosition()" onunload="LogMeOut()">


    The client side function: 

    function SetScrollPosition()
    {
          var div = document.getElementById('divMessages');
          div.scrollTop = 100000000000;
    }
Logging Out:

There are two (2) ways to log out. You can log out by clicking the logout button or by closing your browser.
  1. Clicking the Log-Out button: When the user clicks the log-out button, this user is then deleted from the LoggedInUser table. A message is inserted in the Message table saying that this user logged out. 

      protected void BtnLogOut_Click(object sender, EventArgs e)
      {
      // log out the user by deleting from the LoggedInUser table
                   LinqChatDataContext db = new LinqChatDataContext();
      
      var loggedInUser = (from l in db.LoggedInUsers
      where l.UserID == Convert.ToInt32(Session["ChatUserID"])
      && l.RoomID == Convert.ToInt32(lblRoomId.Text)
      select l).SingleOrDefault();
       
      db.LoggedInUsers.DeleteOnSubmit(loggedInUser);
      db.SubmitChanges();
      
      // insert a message that this user has logged out
      this.InsertMessage("Just logged out! " + DateTime.Now.ToString());
       
                 // clean the session
                 Session.Abandon();
       
                  // redirect the user to the login page
                   Response.Redirect("Default.aspx");
      }


  2. Closing the Browser: My guess is that most users will probably NOT click the Logout button, and instead, just close their browser when they leave the chatroom. The only place where we can capture this is on the client-side. And of course my favorite script on the client side is JavaScript. We can capture this using the "onunload" function, by placing this on the body tag as shown below. 

    <body style="background-color: gainsboro;" onload="SetScrollPosition()" onunload="LogMeOut()">


    The client-side JavaScript that calls back a server-side method: 

    function LogMeOut()
    {
          LogOutUserCallBack();
    }


    We also need to call a server-side method to delete this user from the LoggedInUser table asynchronously from the client side. Of course there are many ways to do this. I used the CallBack feature of ASP.Net. To do this, we simply need to implement the "ICallbackEventHandler" explicitly in our code behind file, as shown below. 

        public partial class Chatroom : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler


    The ICallbackEventHandler have 2 members that you need to explictly implement. The "RaiseCallbackEvent" is the event that handles our callback from the client side to the server side code. This is where we delete the user from the LoggedInUser table as shown below. 

      void  System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
               {
      _callBackStatus = "failed";
      
      // log out the user by deleting from the LoggedInUser table
      LinqChatDataContext db = new LinqChatDataContext();
      
      var loggedInUser = (from l in db.LoggedInUsers
      where l.UserID == Convert.ToInt32(Session["ChatUserID"])
      && l.RoomID == Convert.ToInt32(lblRoomId.Text)
      select l).SingleOrDefault();
      
      db.LoggedInUsers.DeleteOnSubmit(loggedInUser);
      db.SubmitChanges();
      
      // insert a message that this user has logged out
      236             this.InsertMessage("Just logged out! " + DateTime.Now.ToString());
      237 
      238             _callBackStatus = "success";
      239         }


    The "GetCallbackResult" is the method where you can return a string to a JavaScript (client-side) function. So from the RaiseCallbackEvent you can assign a variable some value that is returned from the GetCallbackResult method. For our purposes, we can just return "success" or "failed" value respectively. Code is shown below. 

      string  System.Web.UI.ICallbackEventHandler.GetCallbackResult()
      return _callBackStatus;
      }


    The beauty of this asynchronous/call-back processing is possible because on the Page_Load part of the code, we registered the scripts for callback. 

       // create a call back reference so we can log-out user when user closes the browser
       string callBackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "LogOutUser", "");
       string logOutUserCallBackScript = "function LogOutUserCallBack(arg, context) { " + callBackReference + "; }";
       Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "LogOutUserCallBack", logOutUserCallBackScript, true);
Message Retrieval and Page Refresh:

Let me talk about how we retrieve the messages from the database. There are two (2) primary ways on the way we retrieve the messages from the database to show to chatters.
  1. When we send a message: Every single time you hit that send button or the enter-key, a message is inserted in the Message table. In your chat window, you will also automatically retrieve the messages from the Message table. So, for example you're chatting with someone else, and the other chatter sent a message a second ago, that message will appear on top of message you just sent, and it will look like the other user just sent you a message. If the other user constantly sends messages, to that user, it will look like he/she is getting a response back asap, and there's no dry time when chatting. 

  2. Every 7 seconds on the Timer Tick Event: If for some reason you just never send messages, the back-up is the Timer Control. The timer control will automatically refresh your window every 7 seconds to show the updated chat messages. First you would think that this is just too long. Not really, because would really just retrieve messages only when you don't send any messages for 7 seconds. The cool thing about this is; the timer counter will reset to zero (0) every single time you hit the send button or the enter key. This makes the performance of your web app a little faster.

  3. Lastly, the combination of the above mentioned retrieval process will give you better performance rather than refreshing your browser every second. It will also present the users a seemless and faster message retrieval. 

No comments: