![]() |
Web Development »
ASP.NET »
Howto
Beginner
License: The Code Project Open License (CPOL)
Build a Web Chat Application using ASP.Net 3.5, LINQ and AJAX (in C# 3.5 or VB 9.0)By junnarkWe will create a very simple web chat application using the latest ASP.Net 3.5 technologies from scratch. |
C# (C# 3.0), VB (VB 9.0), Javascript, CSS, SQL, HTML, Windows (WinXP, Win2003, Vista), .NET (.NET 3.5), ASP.NET, SQL Server (SQL 2005), IIS (IIS 6, IIS 7), Visual Studio (VS2008), Ajax, LINQ, Architect, Dev
|
||||||||
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
ASP.Net 3.5, AJAX, JavaScript, C# 3.5 or Visual Basic (VB) 9.0, LINQ-to-SQL, MS SQL Server 2000/2005
You will also find the VB 9.0 article here.
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:

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:
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.
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:
50 <authentication mode="Forms"> 51 <forms name=".ASPXAUTH" loginUrl="Default.aspx"/> 52 </authentication> 53 54 <authorization> 55 <deny users="?" /> 56 </authorization>
13 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) 14 { 15 LinqChatDataContext db = new LinqChatDataContext(); 16 17 var user = (from u in db.Users 18 where u.Username == Login1.UserName 19 && u.Password == Login1.Password 20 select u).SingleOrDefault(); 21 22 if (user != null) 23 { 24 e.Authenticated = true; 25 Session["ChatUserID"] = user.UserID; 26 Session["ChatUsername"] = user.Username; 27 } 28 else 29 { 30 e.Authenticated = false; 31 } 32 } 33 34 protected void Login1_LoggedIn(object sender, EventArgs e) 35 { 36 Response.Redirect("Chatroom.aspx?roomId=1"); 37 }
16 // for simplity's sake we're going to assume that a 17 // roomId was passed in the query string and that 18 // it is an integer 19 // note: in reality you would check if the roomId is empty 20 // and is an integer 21 string roomId = (string)Request["roomId"]; 22 lblRoomId.Text = roomId;
26 this.InsertMessage(ConfigurationManager.AppSettings["ChatLoggedInText"] + " " + DateTime.Now.ToString());
74 private void InsertMessage(string text) 75 { 76 LinqChatDataContext db = new LinqChatDataContext(); 77 78 Message message = new Message(); 79 message.RoomID = Convert.ToInt32(lblRoomId.Text); 80 message.UserID= Convert.ToInt32(Session["ChatUserID"]); 81 82 if (String.IsNullOrEmpty(text)) 83 { 84 message.Text = txtMessage.Text.Replace("<", ""); 85 message.Color = ddlColor.SelectedValue; 86 } 87 else 88 { 89 message.Text = text; 90 message.Color = "gray"; 91 } 92 92 // in the future, we will use this value for private messages message.ToUserID = null; 94 message.TimeStamp = DateTime.Now; 95 db.Messages.InsertOnSubmit(message); 96 db.SubmitChanges(); 97 }
24 <appSettings> 25 <add key="ChatLoggedInText" value="Just logged in!"/> 26 </appSettings>
148 /// <summary> 149 /// Get the last 20 messages for this room 150 /// </summary> 151 private void GetMessages() 152 { 153 LinqChatDataContext db = new LinqChatDataContext(); 154 155 var messages = (from m in db.Messages 156 where m.RoomID == Convert.ToInt32(lblRoomId.Text) 157 orderby m.TimeStamp descending 158 select m).Take(20).OrderBy(m => m.TimeStamp); 159 160 if (messages != null) 161 { 162 StringBuilder sb = new StringBuilder(); 163 int ctr = 0; // toggle counter for alternating color 164 165 foreach (var message in messages) 166 { 167 // alternate background color on messages 168 if (ctr == 0) 169 { 170 sb.Append("<div style='padding: 10px;'>"); 171 ctr = 1; 172 } 173 else 174 { 175 sb.Append("<div style='background-color: #EFEFEF; padding: 10px;'>"); 176 ctr = 0; 177 } 178 179 if (message.User.Sex.ToString().ToLower() == "m") 180 sb.Append("<img src='Images/manIcon.gif' style='vertical-align:middle' alt=''> " + message.Text + "</div>"); 181 else 182 sb.Append("<img src='Images/womanIcon.gif' style='vertical-align:middle' alt=''> " + message.Text + "</div>"); 183 } 184 185 litMessages.Text = sb.ToString(); 186 } 187 }
99 private void GetLoggedInUsers() 100 { 101 LinqChatDataContext db = new LinqChatDataContext(); 102 103 // let's check if this authenticated user exist in the 104 // LoggedInUser table (means user is logged-in to this room) 105 var user = (from u in db.LoggedInUsers 106 where u.UserID == Convert.ToInt32(Session["ChatUserID"]) 107 && u.RoomID == Convert.ToInt32(lblRoomId.Text) 108 select u).SingleOrDefault(); 109 110 // if user does not exist in the LoggedInUser table 111 // then let's add/insert the user to the table 112 if (user == null) 113 { 114 LoggedInUser loggedInUser = new LoggedInUser(); 115 loggedInUser.UserID = Convert.ToInt32(Session["ChatUserID"]); 116 loggedInUser.RoomID = Convert.ToInt32(lblRoomId.Text); 117 db.LoggedInUsers.InsertOnSubmit(loggedInUser); 118 db.SubmitChanges(); 119 } 120 121 string userIcon; 122 StringBuilder sb = new StringBuilder(); 123 124 // get all logged in users to this room 125 var loggedInUsers = from l in db.LoggedInUsers 126 where l.RoomID == Convert.ToInt32(lblRoomId.Text) 127 select l; 128 129 // list all logged in chat users in the user list 130 foreach (var loggedInUser in loggedInUsers) 131 { 132 // show user icon based on sex 133 if (loggedInUser.User.Sex.ToString().ToLower() == "m") 134 userIcon = "<img src='Images/manIcon.gif' style='vertical-align:middle' alt=''> "; 135 else 136 userIcon = "<img src='Images/womanIcon.gif' style='vertical-align:middle' alt=''> "; 137 138 if (loggedInUser.User.Username != (string)Session["ChatUsername"]) 139 sb.Append(userIcon + "<a href=#>" + loggedInUser.User.Username + "</a><br>"); 140 else 141 sb.Append(userIcon + "<b>" + loggedInUser.User.Username + "</b><br>"); 142 } 143 144 // holds the names of the users shown in the chatroom 145 litUsers.Text = sb.ToString(); 146 }
58 ScriptManager1.SetFocus(txtMessage.ClientID);
68 ScriptManager1.SetFocus(txtMessage);
<form id="form1" defaultbutton="btnSend" defaultfocus="txtMessage" runat="server" >
<body style="background-color: gainsboro;" onload="SetScrollPosition()" onunload="LogMeOut()">
function SetScrollPosition()
{
var div = document.getElementById('divMessages');
div.scrollTop = 100000000000;
}
189 protected void BtnLogOut_Click(object sender, EventArgs e) 190 { 191 // log out the user by deleting from the LoggedInUser table 192 LinqChatDataContext db = new LinqChatDataContext(); 193 194 var loggedInUser = (from l in db.LoggedInUsers 195 where l.UserID == Convert.ToInt32(Session["ChatUserID"]) 196 && l.RoomID == Convert.ToInt32(lblRoomId.Text) 197 select l).SingleOrDefault(); 198 199 db.LoggedInUsers.DeleteOnSubmit(loggedInUser); 200 db.SubmitChanges(); 201 202 // insert a message that this user has logged out 203 this.InsertMessage("Just logged out! " + DateTime.Now.ToString()); 204 205 // clean the session 206 Session.RemoveAll(); 207 Session.Abandon(); 208 209 // redirect the user to the login page 210 Response.Redirect("Default.aspx"); 211 }
<body style="background-color: gainsboro;" onload="SetScrollPosition()" onunload="LogMeOut()">
function LogMeOut()
{
LogOutUserCallBack();
}
8 public partial class Chatroom : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
220 void System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) 221 { 222 _callBackStatus = "failed"; 223 224 // log out the user by deleting from the LoggedInUser table 225 LinqChatDataContext db = new LinqChatDataContext(); 226 227 var loggedInUser = (from l in db.LoggedInUsers 228 where l.UserID == Convert.ToInt32(Session["ChatUserID"]) 229 && l.RoomID == Convert.ToInt32(lblRoomId.Text) 230 select l).SingleOrDefault(); 231 232 db.LoggedInUsers.DeleteOnSubmit(loggedInUser); 233 db.SubmitChanges(); 234 235 // insert a message that this user has logged out 236 this.InsertMessage("Just logged out! " + DateTime.Now.ToString()); 237 238 _callBackStatus = "success"; 239 }
215 string System.Web.UI.ICallbackEventHandler.GetCallbackResult() 216 { 217 return _callBackStatus; 218 }
29 // create a call back reference so we can log-out user when user closes the browser 30 string callBackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "LogOutUser", ""); 31 string logOutUserCallBackScript = "function LogOutUserCallBack(arg, context) { " + callBackReference + "; }"; 32 Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "LogOutUserCallBack", logOutUserCallBackScript, true);
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 30 Jun 2008 Editor: Chris Maunder |
Copyright 2008 by junnark Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |