// Обновляем данные в БД в фоновом режиме private void backgroundDbUpdateWorker_DoWork(object sender, DoWorkEventArgs e) { DbRecordChangesTask updateDbTask = e.Argument as DbRecordChangesTask; try { using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { MedicamentRemain record = updateDbTask.DbRecord as MedicamentRemain; record.UpdateDate = DateTime.Now; switch (updateDbTask.ChangesType) { case DbRecordChangesType.Create: backgroundDbUpdateWorker.ReportProgress(0, "Створення запису по медикаменту " + record.Medicament + " ..."); mc.Medicaments.Attach(record.Medicament); mc.MedicamentRemains.Add(record); mc.SaveChanges(); backgroundDbUpdateWorker.ReportProgress(0, "Запис успішно доданий до бази данних!"); break; case DbRecordChangesType.Update: backgroundDbUpdateWorker.ReportProgress(0, "Оновлення запису по медикаменту " + record.Medicament + " ..."); mc.Medicaments.Attach(record.Medicament); mc.Entry <MedicamentRemain>(record).State = System.Data.Entity.EntityState.Modified; mc.SaveChanges(); backgroundDbUpdateWorker.ReportProgress(0, "Запис успішно оновлений у базі данних!"); break; case DbRecordChangesType.Remove: backgroundDbUpdateWorker.ReportProgress(0, "Видалення запису по медикаменту " + record.Medicament + " ..."); MedicamentRemain item = mc.MedicamentRemains.Where(p => (p.Id == record.Id)).First(); mc.MedicamentRemains.Remove(item); mc.SaveChanges(); backgroundDbUpdateWorker.ReportProgress(0, "Запис успішно видалений з бази данних!"); break; } } } catch (Exception ex) { backgroundDbUpdateWorker.ReportProgress(0, "Помилка: " + ex.Message); } // Задержка, чтобы пользователь смог прочитать сообщение об успехе операции либо об ошибке System.Threading.Thread.Sleep(3000); }
private void actionButton_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(medicamentNameTextBox.Text)) { NotificationHelper.ShowError("Ви не ввели назву"); return; } try { using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { if (loadedMedicament == null) { currentMedicament = new Medicament(); } else { currentMedicament = loadedMedicament; } currentMedicament.Name = medicamentNameTextBox.Text.Trim(); currentMedicament.Meter = meterCBList.SelectedItem as Meter; currentMedicament.MeterId = Convert.ToInt32(meterCBList.SelectedValue); currentMedicament.Group = null; currentMedicament.MedicamentGroupId = Convert.ToInt32(medGroupsCBList.SelectedValue); mc.Meters.Attach(currentMedicament.Meter); if (currentMedicament.Id > 0) { mc.Medicaments.Attach(currentMedicament); mc.Entry <Medicament>(currentMedicament).State = System.Data.Entity.EntityState.Modified; } else { mc.Medicaments.Add(currentMedicament); } mc.SaveChanges(); NotificationHelper.ShowInfo("Данні успішно збережено!"); } } catch (Exception ex) { NotificationHelper.ShowError("Помилка при збережені данних до БД.\n Подробиці: \n" + ex.Message); } Close(); }
public AddEditMedicamentForm(int medicamentId) : this() { this.Text = "Змінити дані про медикамент"; actionButton.Text = "Змінити"; using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { Medicament med = mc.Medicaments.Include(p => p.Meter).Where(p => (p.Id == medicamentId)).First(); medicamentNameTextBox.Text = med.Name; meterCBList.SelectedValue = med.MeterId; medGroupsCBList.SelectedValue = med.MedicamentGroupId; loadedMedicament = med; } }
private void InitializeDepartmentCBList() { using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { List <HospitalDepartment> deps = mc.HospitalDepartments.ToList(); deps.Insert(0, new HospitalDepartment { Id = -1, Name = "- УСІ ВІДДІЛЕННЯ -" }); departmentsCBList.DataSource = deps; departmentsCBList.DisplayMember = "Name"; departmentsCBList.ValueMember = "Id"; int selectedDepartmentId = Convert.ToInt32(departmentsCBList.SelectedValue); remainsTable.ReadOnly = selectedDepartmentId < 0; } }
public AddEditMedicamentForm() { InitializeComponent(); using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { List <Meter> metersList = mc.Meters.ToList(); meterCBList.DataSource = metersList; meterCBList.DisplayMember = "Name"; meterCBList.ValueMember = "Id"; List <MedicamentGroup> medGroups = mc.MedicamentsGroups.ToList(); medGroupsCBList.DataSource = medGroups; medGroupsCBList.DisplayMember = "Name"; medGroupsCBList.ValueMember = "Id"; } }
private void loadingMedicamentsTable_DoWork(object sender, DoWorkEventArgs e) { int selectedMedGroupId = Convert.ToInt32(e.Argument); using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { if (selectedMedGroupId > 0) { medList = new BindingList <ZcrlMedicamentModels.Medicament>(mc.Medicaments .Include(p => p.Meter) .Where(p => !alreadySelectedMedicaments.Contains(p.Id) && (p.MedicamentGroupId == selectedMedGroupId)) .OrderBy(p => p.Name).ToList()); } else { medList = new BindingList <ZcrlMedicamentModels.Medicament>(mc.Medicaments.Include(p => p.Meter) .Where(p => !alreadySelectedMedicaments.Contains(p.Id)).OrderBy(p => p.Name).ToList()); } } }
private void loadingMedicametsWorker_DoWork(object sender, DoWorkEventArgs e) { using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { int medGroupId = Convert.ToInt32(e.Argument); if (medGroupId > 0) { medicamentsList = new BindingList <Medicament>(mc.Medicaments.Include(p => p.Meter) .Where(p => p.MedicamentGroupId == medGroupId) .OrderBy(p => p.Name) .ToList()); } else { medicamentsList = new BindingList <Medicament>(mc.Medicaments.Include(p => p.Meter) .OrderBy(p => p.Name) .ToList()); } } }
private void remainsLoadWorker_DoWork(object sender, DoWorkEventArgs e) { // Очищаем список выбраных в отделении медикаментов для формирования нового existingMedicamentsInTable.Clear(); using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { int selectedDepartmentId = Convert.ToInt32(e.Argument); if (selectedDepartmentId > 0) { medRemainsList = new BindingList <MedicamentRemain>(mc.MedicamentRemains.Include(p => p.Medicament).Include(p => p.Medicament.Meter) .Where(p => p.HospitalDepartmentId == selectedDepartmentId).OrderBy(p => p.Medicament.Name).ToList()); } else { // Не даём посчитать итоги пока очередь изменений в БД не обслужена while (dbUpdatesQueue.Count > 0 && !backgroundDbUpdateWorker.IsBusy) { System.Threading.Thread.Sleep(1000); } var fullMedRemains = mc.MedicamentRemains.Include(p => p.Medicament).Include(p => p.Medicament.Meter).ToList(); medRemainsList = new BindingList <MedicamentRemain>( (from item in fullMedRemains group item by item.Medicament into g select new MedicamentRemain { Medicament = g.Key, CurrentRemain = g.Sum(p => p.CurrentRemain), MedicamentId = g.Key.Id } into selection orderby selection.Medicament.Name select selection ).ToList()); } existingMedicamentsInTable = (from item in medRemainsList select item.Medicament.Id).ToList(); } }
public MedicamentsListForm() { InitializeComponent(); medicamentsTable.AutoGenerateColumns = false; listIsLoaded = false; using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { List <MedicamentGroup> medGroupsList = mc.MedicamentsGroups.ToList(); medGroupsList.Insert(0, new MedicamentGroup { Id = -1, Name = "- ВСІ ГРУППИ -" }); medGroupsCBList.DataSource = medGroupsList; medGroupsCBList.DisplayMember = "Name"; medGroupsCBList.ValueMember = "Id"; } ReloadTableData(); listIsLoaded = true; }
public SimpleElementListForm(object tableItem) { InitializeComponent(); isDepartmentListUpdated = false; dataTable.AutoGenerateColumns = false; updateDbTasksQueue = new Queue <DbRecordChangesTask>(); checkTaskQueueTimer.Start(); dbWorkResultLabel.Text = string.Empty; this.tableItem = tableItem; using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { if (tableItem is Meter) { metersList = new BindingList <Meter>(mc.Meters.ToList()); dataTable.DataSource = metersList; } else if (tableItem is HospitalDepartment) { depList = new BindingList <HospitalDepartment>(mc.HospitalDepartments.ToList()); dataTable.DataSource = depList; } else if (tableItem is MedicamentGroup) { medGroupList = new BindingList <MedicamentGroup>(mc.MedicamentsGroups.ToList()); dataTable.DataSource = medGroupList; dataTable.Columns[3].Visible = true; } else { throw new InvalidOperationException("Invalid type of object"); } } }
// TODO: Проверить удалиться ли элемент из DataGridView, если удалить его из связаного источника без вызова метода Update на DataGridView private void removeMedicamentButton_Click(object sender, EventArgs e) { Medicament selectedMedicament = medicamentsTable.SelectedRows[0].DataBoundItem as Medicament; int currentRowIndex = medicamentsTable.SelectedRows[0].Index; if (NotificationHelper.ShowQuestion(string.Format("Ви впевнені, що хочете видалити всі данні про медикамент '{0}'", selectedMedicament)) == System.Windows.Forms.DialogResult.Yes) { medicamentsList.Remove(selectedMedicament); new Task( () => { using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { mc.Medicaments.Attach(selectedMedicament); mc.Medicaments.Remove(selectedMedicament); mc.SaveChanges(); } } ).Start(); RecalculateRowsNumbers(currentRowIndex); } }
public MedicamentSelectForm(IEnumerable <int> alreadySelectedMedicaments) { InitializeComponent(); dataGridView1.AutoGenerateColumns = false; this.alreadySelectedMedicaments = alreadySelectedMedicaments; medGroupsListIsLoaded = false; using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { List <ZcrlMedicamentModels.MedicamentGroup> groupsList = mc.MedicamentsGroups.ToList(); groupsList.Insert(0, new ZcrlMedicamentModels.MedicamentGroup { Id = -1, Name = "- ВСІ ГРУПИ -" }); medGroupsCBList.DataSource = groupsList; medGroupsCBList.DisplayMember = "Name"; medGroupsCBList.ValueMember = "Id"; } medGroupsListIsLoaded = true; ReloadMedicamentsTable(); }
private void dbUpdateWorker_DoWork(object sender, DoWorkEventArgs e) { DbRecordChangesTask dbChangesTask = e.Argument as DbRecordChangesTask; try { using (MedicamentRemainsContext mc = new MedicamentRemainsContext()) { if (tableItem is Meter) { Meter record = dbChangesTask.DbRecord as Meter; switch (dbChangesTask.ChangesType) { case DbRecordChangesType.Create: dbUpdateWorker.ReportProgress(0, "Створення нової одиниці виміру..."); record.Name = record.Name.Trim(); mc.Meters.Add(record); break; case DbRecordChangesType.Update: dbUpdateWorker.ReportProgress(0, "Змінення одиниці виміру..."); record.Name = record.Name.Trim(); mc.Meters.Attach(record); mc.Entry <Meter>(record).State = System.Data.Entity.EntityState.Modified; break; case DbRecordChangesType.Remove: dbUpdateWorker.ReportProgress(0, "Видалення одиниці виміру..."); mc.Meters.Attach(record); mc.Meters.Remove(record); break; } } else if (tableItem is HospitalDepartment) { HospitalDepartment record = dbChangesTask.DbRecord as HospitalDepartment; switch (dbChangesTask.ChangesType) { case DbRecordChangesType.Create: dbUpdateWorker.ReportProgress(0, "Створення нового відділення..."); record.Name = record.Name.Trim(); mc.HospitalDepartments.Add(record); break; case DbRecordChangesType.Update: dbUpdateWorker.ReportProgress(0, "Змінення даних про відділення..."); record.Name = record.Name.Trim(); mc.HospitalDepartments.Attach(record); mc.Entry <HospitalDepartment>(record).State = System.Data.Entity.EntityState.Modified; break; case DbRecordChangesType.Remove: dbUpdateWorker.ReportProgress(0, "Видалення даних про відділення..."); mc.HospitalDepartments.Attach(record); mc.HospitalDepartments.Remove(record); break; } } else if (tableItem is MedicamentGroup) { MedicamentGroup record = dbChangesTask.DbRecord as MedicamentGroup; switch (dbChangesTask.ChangesType) { case DbRecordChangesType.Create: dbUpdateWorker.ReportProgress(0, "Створення нової группи медикаментів..."); record.Name = record.Name.Trim(); mc.MedicamentsGroups.Add(record); break; case DbRecordChangesType.Update: dbUpdateWorker.ReportProgress(0, "Змінення группи медикаментів..."); record.Name = record.Name.Trim(); mc.MedicamentsGroups.Attach(record); mc.Entry <MedicamentGroup>(record).State = System.Data.Entity.EntityState.Modified; break; case DbRecordChangesType.Remove: dbUpdateWorker.ReportProgress(0, "Видалення группи медикаментів..."); mc.MedicamentsGroups.Attach(record); mc.MedicamentsGroups.Remove(record); break; } } mc.SaveChanges(); if (tableItem is HospitalDepartment) { isDepartmentListUpdated = true; } dbUpdateWorker.ReportProgress(0, "Дані успішно збережені!"); } } catch (Exception ex) { dbUpdateWorker.ReportProgress(0, "Помилка: " + ex.Message); } Thread.Sleep(3000); }