//callback po kliknięciu przez użytkownika w textbox public void RaiseCallbackEvent(string eventArgument) { _callbackResult = "failed"; if (!string.IsNullOrEmpty(eventArgument)) { if (eventArgument == "FocusThisWindow") { string chatWindowToFocus = lblFromUserId.Text + "_" + lblToUserId.Text; Session["DefaultWindow"] = chatWindowToFocus; FocusThisWindow(); } if (eventArgument == "Closure") { if (!string.IsNullOrEmpty(lblMessageSent.Text)) { ChatDataContext db = new ChatDataContext(); var username = (from user in db.Users where user.UserID == Convert.ToInt32(Session["ChatUserID"]) select user.Username).SingleOrDefault(); InsertMessage(string.Format("**** Użytkownik <span style=\"font-weight:bold;color:red;\">{0}</span> zamknął okno konwersacji ****", username), true); string Closure = lblToUserId.Text + lblFromUserId.Text + "_closure"; Application[Closure] = true; } } } _callbackResult = "success"; }
//sprawdzenie zaproszen do prywatnych konwersacji private void CheckForPrivateMessages() { //sprawdzam, czy mozna, być może już jest zaproszenie, które jeszcze nie doczekało się odpowiedzi if ((bool)Session["searchForPrivate"]) { Session["searchForPrivate"] = false; ChatDataContext db = new ChatDataContext(); var inv = (from msg in db.PrivateMessages where msg.ToUserID == Convert.ToInt32(Session["ChatUserID"]) orderby msg.PrivateMessageID select msg).SingleOrDefault(); if (inv != null) { var username = (from user in db.Users where user.UserID == inv.UserID select user.Username).SingleOrDefault(); lblChatNowUser.Text = username; btnChatNow.OnClientClick = "window.open('ChatWindow.aspx?FromUserId=" + Session["ChatUserID"] + "&ToUserId=" + inv.UserID + "&Username="******"&IsReply=yes','','width=400," + "height=200'); isLostFocus = 'true';"; panelPrivateChat.Visible = true; db.PrivateMessages.DeleteOnSubmit(inv); db.SubmitChanges(); } } }
//to zostanie wywołane przez klienta przy zamknięciu przeglądarki przez użytkownika public void RaiseCallbackEvent(string eventArgument) { _callBackStatus = "failed"; if (!string.IsNullOrEmpty(eventArgument)) { if (eventArgument == "LogOut") { ChatDataContext db = new ChatDataContext(); var loggedUser = (from user in db.LoggedInUsers where user.RoomID == Convert.ToInt32(Session["roomID"]) && user.UserID == Convert.ToInt32(Session["ChatUserID"]) select user).SingleOrDefault(); db.LoggedInUsers.DeleteOnSubmit(loggedUser); db.SubmitChanges(); //usuń "ticket" forms authentication z przeglądarki i wyczyść info o autentykacji bieżącego użytkownika FormsAuthentication.SignOut(); HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null); updateTimer.Enabled = false; } else if (eventArgument == "FocusThisWindow") { FocusThisWindow(); } } _callBackStatus = "success"; }
//umieszczenie wysyłanej wiadomości w bazie danych (treść) private void InsertMessage(string messageText, bool system) { ChatDataContext db = new ChatDataContext(); Message msg = new Message(); var id = (from message in db.Messages select message.MessageID).Count(); msg.MessageID = id; msg.TimeStamp = DateTime.Now; msg.ToUserID = Convert.ToInt32(lblToUserId.Text); msg.Text = messageText; if (system) { msg.systemMsg = 1; } else { msg.systemMsg = 0; } msg.UserID = Convert.ToInt32(lblFromUserId.Text); db.Messages.InsertOnSubmit(msg); db.SubmitChanges(); }
//info o pokoju private void GetRoomInformation() { ChatDataContext db = new ChatDataContext(); var roomName = (from rooms in db.Rooms where rooms.RoomID == Convert.ToInt32(Session["roomID"]) select rooms.Name).SingleOrDefault(); lblWelcome.Text = "Czat rodzinny:)" + "<br>Witaj w pokoju: " + roomName + "<br>Zalogowano jako: " + Session["ChatUserName"]; }
//pobierz wiadomości z bazy (od momentu zalogowania, max 1000) private void GetMessages() { ChatDataContext db = new ChatDataContext(); var messages = (from message in db.Messages where (message.RoomID == Convert.ToInt32(Session["roomID"])) //&& (message.TimeStamp >= (DateTime)Session["timeStamp"]) orderby message.TimeStamp descending select message).Take(500).OrderBy(m => m.TimeStamp); if (messages != null) { StringBuilder sb = new StringBuilder(); int backCounter = 0; foreach (var message in messages) { string color = message.Color; switch (backCounter) { case 0: sb.Append("<div style='padding:10px;color:" + color + "'>"); backCounter = 1; break; case 1: sb.Append("<div style='padding:10px;background-color:#EFEFEF;color:" + color + "'>"); backCounter = 0; break; } var sexAndUsername = (from users in db.Users where users.UserID == message.UserID select new { users.Sex, users.Username }).SingleOrDefault(); if (sexAndUsername.Sex.ToLower() == "m") { sb.Append("<img src='man-icon.gif' style='vertical-align:middle;'/>" + "<span style='color:black;font-weight:bold;'>" + sexAndUsername.Username + ": </span>" + message.Text + "</div>"); } else { sb.Append("<img src='female-icon.gif' style='vertical-align:middle;'/>" + "<span style='color:black;font-weight:bold;'>" + sexAndUsername.Username + ": </span>" + message.Text + "</div>"); } } litMessages.Text = sb.ToString(); } }
//wyświetl prywatne wiadomości od bieżącego użytkownika private void DisplayPrivateMessages() { ChatDataContext db = new ChatDataContext(); var messages = (from msg in db.Messages where ((msg.UserID == Convert.ToInt32(lblFromUserId.Text) && msg.ToUserID == Convert.ToInt32(lblToUserId.Text)) || (msg.UserID == Convert.ToInt32(lblToUserId.Text) && msg.ToUserID == Convert.ToInt32(lblFromUserId.Text))) && (msg.TimeStamp >= (DateTime)Session["timeStamp"]) orderby msg.TimeStamp descending select msg).Take(200).OrderBy(msg => msg.TimeStamp); int id = Convert.ToInt32(Session["ChatUserID"]); if (messages != null) { StringBuilder sb = new StringBuilder(); int backCounter = -1; foreach (var message in messages) { if (message.systemMsg != 1) { backCounter = message.UserID; if (backCounter == Convert.ToInt32(Session["ChatUserID"])) { sb.Append("<div style='padding:10px;color:black;'>"); } else { sb.Append("<div style='padding:10px;background-color:#EFEFEF;color:gray'>"); } var username = (from users in db.Users where users.UserID == message.UserID select users.Username).SingleOrDefault(); sb.Append("<span style='color:black;font-weight:bold;'>" + username + ": </span>" + message.Text + "</div>"); } else { sb.Append("<div style='padding:10px;color:black;background-color:bisque;'>"); sb.Append(message.Text + "</div>"); } } litMessagesPrivate.Text = sb.ToString(); } }
//wstawienie wiadomości do bazy danych private void InsertMessageToDatabase(string text) { ChatDataContext db = new ChatDataContext(); var messageID = (from messages in db.Messages select messages.MessageID).Count(); Message message = new Message(); int roomID = Convert.ToInt32(Session["roomID"]); message.RoomID = roomID == 0 ? 1 : roomID; message.Text = text; message.TimeStamp = DateTime.Now; message.UserID = Convert.ToInt32(Session["ChatUserID"]); message.ToUserID = null; //bedzie sluzyc do prywatych wiadomosci message.Color = ddlColors.SelectedValue; message.MessageID = messageID; db.Messages.InsertOnSubmit(message); db.SubmitChanges(); }
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { //data context dla LINQ to SQL ChatDataContext db = new ChatDataContext(); var user = (from users in db.Users where users.Username == Login1.UserName && users.Password == Login1.Password select users).SingleOrDefault(); if (user != null) { e.Authenticated = true; Session["ChatUserID"] = user.UserID; Session["ChatUsername"] = user.Username; } else { e.Authenticated = false; } }
protected void tLogout_Click(object sender, EventArgs e) { ChatDataContext db = new ChatDataContext(); var loggedUser = (from user in db.LoggedInUsers where user.RoomID == Convert.ToInt32(Session["roomID"]) && user.UserID == Convert.ToInt32(Session["ChatUserID"]) select user).SingleOrDefault(); db.LoggedInUsers.DeleteOnSubmit(loggedUser); db.SubmitChanges(); Session.RemoveAll(); Session.Abandon(); //usuń "ticket" forms authentication z przeglądarki i wyczyść info o autentykacji bieżącego użytkownika FormsAuthentication.SignOut(); HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null); updateTimer.Enabled = false; Response.Redirect("Default.aspx"); }
//inicjalizacja rozmowy (komunikat o inicjalizacji-zapisanie do bazy tylko raz) private void InsertPrivateMessage() { CheckIfClosed(); //informacje o checi rozpoczecia konwersacji z danym uzytkownikiem zapisujemy w bazie tylko raz //to nie jest tresc wiadomosci, tylko komunikat o checi nawiazania rozmowy //spowoduje wyswietlenie okna z proba o zaakceptowania w Chatroom.aspx if (string.IsNullOrEmpty(lblMessageSent.Text)) { ChatDataContext db = new ChatDataContext(); PrivateMessage privateMessage = new PrivateMessage(); var id = (from message in db.PrivateMessages select message.PrivateMessageID).Count(); privateMessage.PrivateMessageID = id; privateMessage.ToUserID = Convert.ToInt32(lblToUserId.Text); privateMessage.UserID = Convert.ToInt32(lblFromUserId.Text); db.PrivateMessages.InsertOnSubmit(privateMessage); db.SubmitChanges(); lblMessageSent.Text = "Sent."; } }
//pobierz zalogowanych użytkowników private void GetLoggedUsers() { ChatDataContext db = new ChatDataContext(); //sprawdź, czy bieżący użytkownik jest na liście zalogowanych w tym pokoju var usr = (from user in db.LoggedInUsers where user.UserID == Convert.ToInt32(Session["ChatUserID"]) && user.RoomID == Convert.ToInt32(Session["roomID"]) select user).SingleOrDefault(); //jeśli nie, to go dodaj if (usr == null) { LoggedInUser loggedUser = new LoggedInUser(); int id = (from user in db.LoggedInUsers orderby user.LoggedInUserId descending select user.LoggedInUserId ).FirstOrDefault(); loggedUser.LoggedInUserId = id + 1; loggedUser.UserID = Convert.ToInt32(Session["ChatUserID"]); loggedUser.RoomID = Convert.ToInt32(Session["roomID"]); db.LoggedInUsers.InsertOnSubmit(loggedUser); db.SubmitChanges(); } StringBuilder sb = new StringBuilder(); //wyświetl zalogowanych użytkowników w tym pokoju var loggedUsers = from users in db.LoggedInUsers where users.RoomID == Convert.ToInt32(Session["roomID"]) select users; foreach (var loggedOne in loggedUsers) { //ikonka var thisOne = (from users in db.Users where users.UserID == loggedOne.UserID select new { users.Sex, users.Username }).SingleOrDefault(); if (thisOne.Sex.ToLower() == "m") { sb.Append("<img src='man-icon.gif' style='vertical-align:middle;'/>"); } else { sb.Append("<img src='female-icon.gif' style='vertical-align:middle;'/>"); } //do wszystkich uzytkownikow oprocz biezacego beda linki (do prywatnej rozmowy) if (thisOne.Username != (string)Session["ChatUsername"]) { sb.Append("<a href=# onclick=\"window.open('ChatWindow.aspx?FromUserID=" + Session["ChatUserID"] + "&ToUserID=" + loggedOne.UserID + "&Username="******"&isReply=no" + "'," + "'','width=400,height=200,scrollbars=no,toolbars=no,titlebar=no,menubar=no'); isLostFocus='true';\">" + thisOne.Username + "</a><br>"); } else { sb.Append("<b>" + thisOne.Username + "</b><br>"); } } litUsers.Text = sb.ToString(); }