/// <summary> /// Загружает информацию о комнате в виде строк DataGridView /// </summary> /// <param name="room">Комната</param> /// <param name="dataGridView">К какому элементу добавляются строки</param> /// <param name="row">Номер первой для добавления строки для данной комнаты</param> private void LoadRoom(Room room, DataGridView dataGridView, ref int row) { dataGridView.Rows.Add(room.Seats); for (int i = 0; i < room.Seats; i++) { dataGridView.Rows[row + i].Height = 40; dataGridView.Rows[row].Cells[0].Value = room.Number; RoomResidents roomResidents = room.RoomResidents.ElementAtOrDefault(i); Resident resident = null; if (roomResidents != null) { resident = db.GetTable <Resident>().Single(r => r.ResidentId == roomResidents.ResidentId); } dynamic tagObject = new System.Dynamic.ExpandoObject(); if (resident != null) { string fullName = resident.Surname.ToString() + " " + resident.Name.ToString() + " " + resident.Patronymic.ToString(); tagObject.residentId = resident.ResidentId; tagObject.roomId = room.RoomId; string organizationName = resident.Organization.Name.ToString(); dataGridView.Rows[row + i].Cells[1].Value = fullName; dataGridView.Rows[row + i].Cells[1].Tag = tagObject; dataGridView.Rows[row + i].Cells[2].Value = organizationName; } else { tagObject.residentId = 0; tagObject.roomId = room.RoomId; dataGridView.Rows[row + i].Cells[1].Value = "Добавить"; dataGridView.Rows[row + i].Cells[1].Tag = tagObject; dataGridView.Rows[row + i].Cells[2].Value = "Пусто"; } } row += room.Seats; }
// Удаляет запись о проживании private void deleteLivingButton_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Вы уверены, что хотите удалить выбранную запись?\n", "Предупреждение", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { try { Int32.TryParse(residentRoomsIdLabel.Text, out int residentRoomsId); if (residentRoomsId == 0) { MessageBox.Show("Выберите запись для удаления."); } else { ResidentRooms residentRooms = db.GetTable <ResidentRooms>().SingleOrDefault(r => r.ResidentRoomsId == residentRoomsId); db.GetTable <ResidentRooms>().DeleteOnSubmit(residentRooms); RoomResidents roomResidents = db.GetTable <RoomResidents>().FirstOrDefault(r => (r.ResidentId == residentId && r.RoomId == residentRooms.RoomId)); db.GetTable <RoomResidents>().DeleteOnSubmit(roomResidents); db.SubmitChanges(); LoadLivingDataGridView(); } } catch (Exception ex) { HistoryRecordsController.WriteExceptionToLogFile(ex, "Ошибка при удалении информации о проживании в deleteLivingButton_Click."); MessageBox.Show("Ошибка при удалении информации о проживании.\nВызвано исключение:" + ex.Message); } } }
/// <summary> /// Отвечает за выселения жителя из комнаты /// </summary> /// <param name="roomId">Идентификатор комнаты</param> /// <param name="residentId">Идентификатор жителя</param> private void EvictResident(int roomId, int residentId) { DialogResult dialogResult = MessageBox.Show("Вы уверены, что хотите выселить данного жителя?\n", "Предупреждение", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { try { Resident resident = db.GetTable <Resident>().FirstOrDefault(r => r.ResidentId == residentId); RoomResidents roomResidents = db.GetTable <RoomResidents>().FirstOrDefault(r => (r.ResidentId == residentId && r.RoomId == roomId)); db.GetTable <RoomResidents>().DeleteOnSubmit(roomResidents); ResidentRooms residentRooms = db.GetTable <ResidentRooms>() .FirstOrDefault(r => (r.ResidentId == residentId && r.RoomId == roomId && r.DateOfEviction == null)); residentRooms.DateOfEviction = DateTime.Now; db.SubmitChanges(); SystemSounds.Beep.Play(); MessageBox.Show("Житель успешно выселен!"); HistoryRecordsController.WriteAboutSettlement(residentRooms, false); } catch (Exception ex) { SystemSounds.Exclamation.Play(); HistoryRecordsController.WriteExceptionToLogFile(ex, "Ошибка при выселении жителя."); MessageBox.Show("Ошибка выселения жителя. \nВызвано исключение: " + ex.Message); } } }
// Удаляет выбранного жителя private void deleteButton_Click(object sender, EventArgs e) { DialogResult dialogResult = MessageBox.Show("Вы уверены, что хотите удалить выбранного жителя?\n", "Предупреждение", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { try { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; Int32.TryParse(residentIdLabel.Text, out int residentId); if (residentId == 0) { MessageBox.Show("Выберите жителя"); } else { SqlConnectionStringBuilder sConnBForOtherServer = new SqlConnectionStringBuilder() { DataSource = Properties.Settings.Default.userServer2Name, InitialCatalog = Properties.Settings.Default.userServer2Database, UserID = sqlConnectionString.UserID, Password = sqlConnectionString.Password, }; DataContext dbFromOtherServer = new DataContext(sConnBForOtherServer.ConnectionString); Resident resident2 = dbFromOtherServer.GetTable <Resident>().FirstOrDefault(r => r.ResidentId == residentId); if (resident2 != null) { dbFromOtherServer.GetTable <Resident>().DeleteOnSubmit(resident2); } Passport passport2 = dbFromOtherServer.GetTable <Passport>().FirstOrDefault(r => (r.PassportId == resident2.PassportId)); if (passport2 != null) { resident2.Passport = passport2; dbFromOtherServer.GetTable <Passport>().DeleteOnSubmit(passport2); } RoomResidents roomResidents2 = dbFromOtherServer.GetTable <RoomResidents>().FirstOrDefault(r => (r.ResidentId == residentId)); if (roomResidents2 != null) { dbFromOtherServer.GetTable <RoomResidents>().DeleteOnSubmit(roomResidents2); } ResidentRooms residentRooms2 = dbFromOtherServer.GetTable <ResidentRooms>() .FirstOrDefault(r => (r.ResidentId == residentId && r.DateOfEviction == null)); if (residentRooms2 != null) { residentRooms2.DateOfEviction = DateTime.Now; } db = new DataContext(sqlConnectionString.ConnectionString); Resident resident = db.GetTable <Resident>().FirstOrDefault(r => r.ResidentId == residentId); if (resident != null) { db.GetTable <Resident>().DeleteOnSubmit(resident); } Passport passport = db.GetTable <Passport>().FirstOrDefault(r => (r.PassportId == resident.PassportId)); if (passport != null) { resident.Passport = passport; db.GetTable <Passport>().DeleteOnSubmit(passport); } RoomResidents roomResidents = db.GetTable <RoomResidents>().FirstOrDefault(r => (r.ResidentId == residentId)); if (roomResidents != null) { db.GetTable <RoomResidents>().DeleteOnSubmit(roomResidents); } ResidentRooms residentRooms = db.GetTable <ResidentRooms>() .FirstOrDefault(r => (r.ResidentId == residentId && r.DateOfEviction == null)); if (residentRooms != null) { residentRooms.DateOfEviction = DateTime.Now; } dbFromOtherServer.SubmitChanges(); db.SubmitChanges(); LoadDataGrid(); HistoryRecordsController.WriteAboutAddDeleteResident(resident, false); } } catch (Exception ex) { HistoryRecordsController.WriteExceptionToLogFile(ex, "Ошибка при удалении жителя в deleteButton_Click."); MessageBox.Show("Ошибка при удалении жителя.\nВызвано исключение: " + ex.Message); } finally { System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } } }
// Сохраняет изменения о проживании private void saveLivingButton_Click(object sender, EventArgs e) { if (settlementDateDateTimePicker.Value.Date > dateOfEvictionDateTimePicker.NullableValue()) { SystemSounds.Exclamation.Play(); MessageBox.Show("Дата заселения должна быть раньше даты выселения."); return; } DialogResult dialogResult = MessageBox.Show("Вы уверены, что хотите сохранить изменения?\n", "Предупреждение", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { try { Int32.TryParse(residentRoomsIdLabel.Text, out int residentRoomsId); if (residentRoomsId == 0) { MessageBox.Show("Выберите запись для изменения."); } else { int sectonNumber = Int32.Parse(sectionNumberTextBox.Text); int roomNumber = Int32.Parse(roomNumberTextBox.Text); Room room = db.GetTable <Room>().SingleOrDefault(r => r.SectionNumber == sectonNumber && r.Number == roomNumber); if (room != null) { ResidentRooms residentRooms = db.GetTable <ResidentRooms>().SingleOrDefault(r => r.ResidentRoomsId == residentRoomsId); if (residentRooms.RoomId != room.RoomId) { RoomResidents roomResidents = db.GetTable <RoomResidents>().FirstOrDefault(r => (r.ResidentId == residentId && r.RoomId == residentRooms.RoomId)); db.GetTable <RoomResidents>().DeleteOnSubmit(roomResidents); RoomResidents newRoomResidents = new RoomResidents { RoomId = room.RoomId, ResidentId = residentRooms.ResidentId }; db.GetTable <RoomResidents>().InsertOnSubmit(newRoomResidents); } residentRooms.RoomId = room.RoomId; residentRooms.CashPayment = (bool)((ComboBoxItem)cashPaymentComboBox.SelectedItem).HiddenValue; residentRooms.BedClothes = (bool)((ComboBoxItem)bedClothesComboBox.SelectedItem).HiddenValue; residentRooms.SettlementDate = settlementDateDateTimePicker.Value; residentRooms.DateOfEviction = dateOfEvictionDateTimePicker.NullableValue(); db.SubmitChanges(); SystemSounds.Beep.Play(); MessageBox.Show("Успешно сохранено!"); LoadLivingDataGridView(); } else { MessageBox.Show("Введённой комнаты не существует."); } } } catch (Exception ex) { SystemSounds.Exclamation.Play(); HistoryRecordsController.WriteExceptionToLogFile(ex, "Ошибка при сохранении изменений о проживании в saveLivingButton_Click."); MessageBox.Show("Ошибка при сохранении изменений.\nВызвано исключение:" + ex.Message); } } }
// Заселяет жителя private void settleButton_Click(object sender, EventArgs e) { if (startRentDateTimePicker.Value.Date > endRentDateTimePicker.Value.Date) { SystemSounds.Exclamation.Play(); MessageBox.Show("Нельзя добавить данный прокат. Дата начала проката должна быть раньше даты окончания."); return; } DialogResult dialogResult = MessageBox.Show("Вы уверены, что хотите заселить данного жителя?\n", "Предупреждение", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { try { Int32.TryParse(residentIdLabel.Text, out int residentId); Resident resident = db.GetTable <Resident>().SingleOrDefault(r => r.ResidentId == residentId); var exist = db.GetTable <RoomResidents>().Any(r => r.ResidentId == resident.ResidentId); if (exist) { SystemSounds.Exclamation.Play(); MessageBox.Show("Данный житель уже живет в другой комнате"); } else { RoomResidents roomResidents = new RoomResidents { RoomId = roomId, ResidentId = resident.ResidentId }; db.GetTable <RoomResidents>().InsertOnSubmit(roomResidents); bool isCash = cashRadioButton.Checked ? true : false; ResidentRooms residentRooms = new ResidentRooms { ResidentId = resident.ResidentId, RoomId = roomId, CashPayment = isCash, BedClothes = bedClothesCheckBox.Checked, SettlementDate = settlementDateTimePicker.Value }; db.GetTable <ResidentRooms>().InsertOnSubmit(residentRooms); db.SubmitChanges(); if (isRentCheckBox.Checked) { RentThing rentThing = db.GetTable <RentThing>().SingleOrDefault(r => r.Name == "Телевизор"); ResidentRoomsRentThing residentRoomsRentThing = new ResidentRoomsRentThing { ResidentRoomsId = residentRooms.ResidentRoomsId, RentThingId = rentThing.RentThingId, StartRentDate = startRentDateTimePicker.Value.Date, EndRentDate = endRentDateTimePicker.Value.Date }; db.GetTable <ResidentRoomsRentThing>().InsertOnSubmit(residentRoomsRentThing); } db.SubmitChanges(); HistoryRecordsController.WriteAboutSettlement(residentRooms, true); DialogResult = DialogResult.OK; Close(); } } catch (Exception ex) { SystemSounds.Exclamation.Play(); HistoryRecordsController.WriteExceptionToLogFile(ex, "Ошибка при заселении жителя в settleButton_Click."); MessageBox.Show("Ошибка при заселении жителя.\nВызвано исключение: " + ex.Message); } } }