public List <Message> GetMessages(int id) { Connect(); var messages = new List <Message>(); try { var command = new SqlCommand( "((select Id,CONCAT('you: ',message) as msg,timeStamp from dbo.ChatMessage where fromUser=@Id)" + "union" + "(select ChatMessage.Id,CONCAT(ChatUser.userName,': ', ChatMessage.message) as msg,ChatMessage.timeStamp from ChatMessage join ChatUser on ChatMessage.fromUser=ChatUser.Id " + "where ChatMessage.Id in (select distinct messageId from MessageTo where toUser=@Id)))" + "order by ChatMessage.timeStamp", _connection); command.Parameters.AddWithValue("@Id", id); var reader = command.ExecuteReader(); while (reader.Read()) { var m = new Message { Id = (int)reader["Id"], message = reader["msg"].ToString(), fromUser = id, timestamp = Convert.ToDateTime(reader["timeStamp"], CultureInfo.InvariantCulture) }; messages.Add(m); } reader.Dispose(); return(messages); } finally { if (_connection != null) { _connection.Close(); } } }
private void btn_send_Click(object sender, EventArgs e) { if (tbox_msg.Text.Equals("")) { return; } if (lst_online.SelectedItems.Count == 0) { MessageBox.Show(Resources.ResourceManager.GetString("send_no_user_selected")); return; } var toList = new List <int>(); foreach (ListViewItem i in lst_online.SelectedItems) { toList.Add(_allUsers.FirstOrDefault(x => x.Value.Equals(i.Text)).Key); } toList.Add(_user.Id); var msg = new ChatMessage { Users = toList, Message = tbox_msg.Text }; SendMessage(msg); toList.Remove(_user.Id); var m = new Message { message = tbox_msg.Text, fromUser = _user.Id, toUser = toList, timestamp = DateTime.Now }; _messages.Add(m); }