예제 #1
0
 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (!workWasCanceled)
     {
         Notificator.ShowInfo("Формування звіту завершено!");
     }
     Close();
 }
예제 #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            int selectedCommuneId = Convert.ToInt32(comboBox1.SelectedValue);

            if (medicamentsList.Count == 0)
            {
                return;
            }

            try
            {
                this.Enabled = false;

                using (DiabetContext dc = new DiabetContext())
                {
                    var listOfAssignments = dc.MedicamentAssigantions.ToList();
                    if (selectedCommuneId > 0)
                    {
                        listOfAssignments = listOfAssignments.Where(t => t.Patient.CommuneId == selectedCommuneId).ToList();
                    }

                    foreach (var element in medicamentsList)
                    {
                        Medicament medicamentForSearch;
                        if (element.OldMedNameValue != null)
                        {
                            medicamentForSearch = element.OldMedNameValue;
                        }
                        else
                        {
                            medicamentForSearch = element.MedName;
                        }

                        var searchList = listOfAssignments.Where(t => (t.AssignMedicament.Id == medicamentForSearch.Id) &&
                                                                 (t.Dozage == element.OldDozageValue) &&
                                                                 (t.Days == element.OldDaysValue)).ToList();

                        foreach (var assMedItem in searchList)
                        {
                            assMedItem.MedicamentId = element.MedName.Id;
                            assMedItem.Dozage       = element.Dozage;
                            assMedItem.Days         = element.Days;
                            dc.Entry <MedicamentAssignation>(assMedItem).State = EntityState.Modified;
                            dc.SaveChanges();
                        }
                    }
                }
                Notificator.ShowInfo("Зміни успішно внесено!");
            }
            catch (Exception ex)
            {
                Notificator.ShowError(ex.Message);
            }
            finally
            {
                this.Enabled = true;
            }
        }
예제 #3
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(doctorFNameBox.Text))
            {
                Notificator.ShowError("Ви не вказали ім'я лікаря");
                return;
            }
            if (string.IsNullOrWhiteSpace(doctorLNameBox.Text))
            {
                Notificator.ShowError("Ви не вказали прізвище лікаря");
                return;
            }
            if (string.IsNullOrWhiteSpace(doctorMNameBox.Text))
            {
                Notificator.ShowError("Ви не вказали по-батькові лікаря");
                return;
            }
            if (string.IsNullOrWhiteSpace(doctorPositionBox.Text))
            {
                Notificator.ShowError("Ви не вказали посаду лікаря");
                return;
            }
            if (string.IsNullOrWhiteSpace(hospitalNameBox.Text))
            {
                Notificator.ShowError("Ви не вказали назву лікувального закладу");
                return;
            }
            if (string.IsNullOrWhiteSpace(adressBox.Text))
            {
                Notificator.ShowError("Ви не вказали адресу лікувального закладу");
                return;
            }

            using (DAL.DiabetContext dc = new DAL.DiabetContext())
            {
                Models.ProgramSettings ps = dc.Settings.First();
                ps.DoctorFirstName  = doctorFNameBox.Text.Trim();
                ps.DoctorLastName   = doctorLNameBox.Text.Trim();
                ps.DoctorMiddleName = doctorMNameBox.Text.Trim();
                ps.DoctorPosition   = doctorPositionBox.Text.Trim();
                ps.HospitalFullName = hospitalNameBox.Text.Trim();
                ps.HospitalAdress   = adressBox.Text.Trim();
                dc.SaveChanges();

                Notificator.ShowInfo("Дані успішно збережені!");
            }
        }
예제 #4
0
        private void addEditButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(firstNameBox.Text))
            {
                Notificator.ShowError("Ви не ввели ім'я пацієнта");
                return;
            }
            if (string.IsNullOrWhiteSpace(lastNameBox.Text))
            {
                Notificator.ShowError("Ви не ввели прізвище пацієнта");
                return;
            }
            if (string.IsNullOrWhiteSpace(middleNameBox.Text))
            {
                Notificator.ShowError("Ви не ввели ім'я по-батькові пацієнта");
                return;
            }

            if (string.IsNullOrWhiteSpace(adress.Text))
            {
                Notificator.ShowError("Ви не ввели адресу пацієнта");
                return;
            }

            if (addMedAssignList.Any(t => t.AssignMedicament == null))
            {
                Notificator.ShowError("Серед списку призначень є пусті колонки з назвою медикаменту");
                return;
            }

            if (addPatAnList.Any(t => t.Analyze == null))
            {
                Notificator.ShowError("Серед списку аналізів є пусті колонки з назвою аналізу");
                return;
            }

            if (addMedMovList.Any(t => t.Medicament == null))
            {
                Notificator.ShowError("Серед списку видачі медикаментів є пусті колонки з назвою медикаменту");
                return;
            }

            using (DiabetContext dc = new DiabetContext())
            {
                // Если пациент существовал и у него было фото, но мы его убрали - удаляём файл с фото
                if ((dbRecord.Id > 0) && (dbRecord.PhotoFile != null) && (patientPhoto.Image == null))
                {
                    if (System.IO.File.Exists(System.IO.Path.Combine(PathFinder.GetImgPath(), dbRecord.PhotoFile)))
                    {
                        System.IO.File.Delete(System.IO.Path.Combine(PathFinder.GetImgPath(), dbRecord.PhotoFile));
                    }
                    dbRecord.PhotoFile = null;
                }

                if (dbRecord.PhotoFile != null)
                {
                    // Директория файла с фото
                    string pathOfPhotoFile = System.IO.Path.GetDirectoryName(dbRecord.PhotoFile);

                    // Если директория с файлом определена - значит была произведена установка фотографии
                    if (!string.IsNullOrWhiteSpace(pathOfPhotoFile))
                    {
                        if (!string.IsNullOrWhiteSpace(oldPhotoFile))
                        {
                            if (System.IO.File.Exists(System.IO.Path.Combine(PathFinder.GetImgPath(), oldPhotoFile)))
                            {
                                System.IO.File.Delete(System.IO.Path.Combine(PathFinder.GetImgPath(), oldPhotoFile));
                            }
                        }

                        string photoFileExt     = (new System.IO.FileInfo(dbRecord.PhotoFile)).Extension;
                        string photoFileNewName = string.Empty;
                        string photoFileNewPath = string.Empty;
                        do
                        {
                            photoFileNewName = Guid.NewGuid().ToString() + photoFileExt;
                            photoFileNewPath = System.IO.Path.Combine(PathFinder.GetImgPath(), photoFileNewName);
                        }while (System.IO.File.Exists(photoFileNewPath));

                        System.IO.File.Copy(dbRecord.PhotoFile, photoFileNewPath);

                        dbRecord.PhotoFile = photoFileNewName;
                    }
                }

                dbRecord.FirstName  = firstNameBox.Text.Trim();
                dbRecord.LastName   = lastNameBox.Text.Trim();
                dbRecord.MiddleName = middleNameBox.Text.Trim();
                dbRecord.BirthDate  = birthDatePicker.Value;

                dbRecord.CommuneId      = (int)communeBox.SelectedValue;
                dbRecord.PatientCommune = communeBox.SelectedItem as Commune;
                dc.Communes.Attach(dbRecord.PatientCommune);

                dbRecord.Adress    = adress.Text.Trim();
                dbRecord.Sex       = (Sex)sexBox.SelectedValue;
                dbRecord.DType     = (DiabetType)diabetTypeBox.SelectedValue;
                dbRecord.OtherInfo = otherPatientInfo.Text.Trim();
                dbRecord.IsDead    = isDeadcheckBox.Checked;
                if (isDeadcheckBox.Checked)
                {
                    dbRecord.DeathDate = dateOfDeath.Value;
                }
                else
                {
                    dbRecord.DeathDate = null;
                }

                if (dbRecord.Id > 0)
                {
                    dc.Patients.Attach(dbRecord);
                    dc.Entry <Patient>(dbRecord).State = EntityState.Modified;
                }
                else
                {
                    dc.Patients.Add(dbRecord);
                }
                dc.SaveChanges();

                foreach (var item in addMedAssignList)
                {
                    item.AssignMedicament = null;
                    item.PatientId        = dbRecord.Id;
                    dbRecord.Medicaments.Add(item);
                    dc.Entry <MedicamentAssignation>(item).State = System.Data.Entity.EntityState.Added;
                }
                foreach (var item in editMedAssignList)
                {
                    dc.Medicaments.Attach(item.AssignMedicament);
                    dc.Patients.Attach(item.Patient);
                    dc.MedicamentAssigantions.Attach(item);
                    item.PatientId = dbRecord.Id;
                    dc.Entry <MedicamentAssignation>(item).State = System.Data.Entity.EntityState.Modified;
                }
                foreach (var item in remMedAssignList)
                {
                    dc.Medicaments.Attach(item.AssignMedicament);
                    dc.Patients.Attach(item.Patient);
                    dc.MedicamentAssigantions.Remove(item);
                    item.PatientId = dbRecord.Id;
                    dc.Entry <MedicamentAssignation>(item).State = System.Data.Entity.EntityState.Deleted;
                }
                dc.SaveChanges();

                foreach (var item in addPatAnList)
                {
                    item.Analyze = null;
                    dbRecord.PatientAnalyzes.Add(item);
                    item.PatientId = dbRecord.Id;
                    dc.Entry <PatientAnalyze>(item).State = System.Data.Entity.EntityState.Added;
                }
                foreach (var item in editPatAnList)
                {
                    dc.Analyze.Attach(item.Analyze);
                    dc.PatientAnalyzes.Attach(item);
                    item.PatientId = dbRecord.Id;
                    dc.Entry <PatientAnalyze>(item).State = System.Data.Entity.EntityState.Modified;
                }
                foreach (var item in remPatAnList)
                {
                    dc.Analyze.Attach(item.Analyze);
                    dc.PatientAnalyzes.Attach(item);
                    item.PatientId = dbRecord.Id;
                    dc.Entry <PatientAnalyze>(item).State = System.Data.Entity.EntityState.Deleted;
                }
                dc.SaveChanges();

                foreach (var item in addMedMovList)
                {
                    item.Medicament = null;
                    dbRecord.MedMovements.Add(item);
                    item.PatientId = dbRecord.Id;
                    dc.Entry <MedicamentMovement>(item).State = System.Data.Entity.EntityState.Added;
                }
                foreach (var item in editMedMovList)
                {
                    item.PatientId = dbRecord.Id;
                    dc.Medicaments.Attach(item.Medicament);
                    dc.MedicamentMovements.Attach(item);
                    dc.Entry <MedicamentMovement>(item).State = System.Data.Entity.EntityState.Modified;
                }
                foreach (var item in remMedMovList)
                {
                    item.PatientId = dbRecord.Id;
                    dc.Medicaments.Attach(item.Medicament);
                    dc.MedicamentMovements.Attach(item);
                    dc.Entry <MedicamentMovement>(item).State = System.Data.Entity.EntityState.Deleted;
                }
                dc.SaveChanges();

                foreach (var item in addPatHistList)
                {
                    item.PatientId = dbRecord.Id;
                    dbRecord.HistoryRecords.Add(item);
                    dc.Entry <PatientHistoryRecord>(item).State = System.Data.Entity.EntityState.Added;
                }
                foreach (var item in editPatHistList)
                {
                    item.PatientId = dbRecord.Id;
                    dc.PatientHistoryRecords.Attach(item);
                    dc.Entry <PatientHistoryRecord>(item).State = System.Data.Entity.EntityState.Modified;
                }
                foreach (var item in remPatHistList)
                {
                    item.PatientId = dbRecord.Id;
                    dc.PatientHistoryRecords.Attach(item);
                    dc.Entry <PatientHistoryRecord>(item).State = System.Data.Entity.EntityState.Deleted;
                }
                dc.SaveChanges();

                // Очищаем очереди на изменения в БД
                addMedAssignList.Clear();
                editMedAssignList.Clear();
                remMedAssignList.Clear();
                addPatAnList.Clear();
                editPatAnList.Clear();
                remPatAnList.Clear();
                addMedMovList.Clear();
                editMedMovList.Clear();
                remMedMovList.Clear();
                addPatHistList.Clear();
                editPatHistList.Clear();
                remPatHistList.Clear();

                Notificator.ShowInfo("Дані успішно збережені!");
                patientDataIsSaved = true;
            }
        }
예제 #5
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Определяем файл-шаблон
            string templateFilePath = string.Empty;
            double currentProgress  = 0.0;

            if (isSafeReport)
            {
                templateFilePath = System.IO.Path.Combine(PathFinder.GetProgramPath(),
                                                          "template",
                                                          "template_printpatientssafe.xls");
            }
            else
            {
                templateFilePath = System.IO.Path.Combine(PathFinder.GetProgramPath(),
                                                          "template",
                                                          "template_printpatientsunsafe.xls");
            }

            if (!System.IO.File.Exists(templateFilePath))
            {
                Notificator.ShowError("Файл шаблону відсутній! Формування звіту неможливе!");
                return;
            }

            Excel.Application xlApp = new Excel.Application();
            if (xlApp == null)
            {
                Notificator.ShowError("Помилка при завантаженні екземпляру Excel");
                return;
            }
            backgroundWorker1.ReportProgress(Convert.ToInt32(currentProgress += 2));

            xlApp.DisplayAlerts = false;

            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(templateFilePath);
            if (xlWorkbook == null)
            {
                xlApp.Quit();
                xlApp = null;
                Notificator.ShowError("Помилка при завантаженні файлу-шаблону");
                return;
            }
            backgroundWorker1.ReportProgress(Convert.ToInt32(currentProgress += 4));

            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkbook.Worksheets[1];
            if (xlWorkSheet == null)
            {
                xlWorkbook.Close(0);
                xlApp.Quit();
                xlApp = null;
                Notificator.ShowError("Помилка при завантаженні файлу-шаблону");
                return;
            }

            try
            {
                int patientsCount   = patientsList.Count;
                int currentWritePos = START_ROW_TO_WRITE;

                // Шаг изменения прогресса
                double progressStep = (100 - currentProgress) / patientsCount;

                using (DiabetContext dc = new DiabetContext())
                {
                    for (int i = 0; i < patientsCount; i++, currentWritePos++)
                    {
                        if (isWorkCancelled)
                        {
                            throw new Exception("Операція відмінена користувачем!");
                        }

                        dc.Patients.Attach(patientsList[i]);

                        string sex = (patientsList[i].Sex == Sex.Male) ? "чол." : "жін.";

                        // Формируем список назначеных пациенту медикаментов
                        string[] medicamentsList = new string[patientsList[i].Medicaments.Count];
                        for (int j = 0; j < patientsList[i].Medicaments.Count; j++)
                        {
                            medicamentsList[j] = string.Format("{0}) {1}", (j + 1),
                                                               patientsList[i].Medicaments.ElementAt(j).AssignMedicament.FullName);
                        }

                        if (isSafeReport)
                        {
                            xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos).Value = (i + 1).ToString();
                            xlWorkSheet.get_Range(columnLettersForSafeReport[1] + currentWritePos).Value = sex;
                            xlWorkSheet.get_Range(columnLettersForSafeReport[2] + currentWritePos).Value = patientsList[i].BirthDate.ToShortDateString();
                            xlWorkSheet.get_Range(columnLettersForSafeReport[3] + currentWritePos).Value = patientsList[i].PatientCommune.ToString();
                            xlWorkSheet.get_Range(columnLettersForSafeReport[4] + currentWritePos).Value = patientsList[i].DiabetTypeStr;
                            xlWorkSheet.get_Range(columnLettersForSafeReport[5] + currentWritePos).Value = string.Join("\n", medicamentsList);
                        }
                        else
                        {
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[0] + currentWritePos).Value = (i + 1).ToString();
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[1] + currentWritePos).Value = patientsList[i].FullName;
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[2] + currentWritePos).Value = sex;
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[3] + currentWritePos).Value = patientsList[i].BirthDate.ToShortDateString();
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[4] + currentWritePos).Value = patientsList[i].PatientCommune.ToString();
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[5] + currentWritePos).Value = patientsList[i].Adress;
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[6] + currentWritePos).Value = patientsList[i].DiabetTypeStr;
                            xlWorkSheet.get_Range(columnLettersForUnsafeReport[7] + currentWritePos).Value = string.Join("\n", medicamentsList);
                        }

                        backgroundWorker1.ReportProgress(Convert.ToInt32(currentProgress += progressStep));
                    }

                    // Определяем буквы последних двух столбцов
                    string firstRangeLetter = string.Empty;
                    string lastRangeLetter  = string.Empty;
                    if (isSafeReport)
                    {
                        firstRangeLetter = columnLettersForSafeReport[columnLettersForSafeReport.Count() - 2];
                        lastRangeLetter  = columnLettersForSafeReport[columnLettersForSafeReport.Count() - 1];
                    }
                    else
                    {
                        firstRangeLetter = columnLettersForUnsafeReport[columnLettersForUnsafeReport.Count() - 2];
                        lastRangeLetter  = columnLettersForUnsafeReport[columnLettersForUnsafeReport.Count() - 1];
                    }

                    // Рисуем внешние границы таблицы отчета
                    currentWritePos--;
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + START_ROW_TO_WRITE, lastRangeLetter + currentWritePos)
                    .Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight =
                        xlWorkSheet.get_Range(columnLettersForSafeReport[0] + START_ROW_TO_WRITE, lastRangeLetter + currentWritePos)
                        .Borders[Excel.XlBordersIndex.xlEdgeTop].Weight =
                            xlWorkSheet.get_Range(columnLettersForSafeReport[0] + START_ROW_TO_WRITE, lastRangeLetter + currentWritePos)
                            .Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight =
                                xlWorkSheet.get_Range(columnLettersForSafeReport[0] + START_ROW_TO_WRITE, lastRangeLetter + currentWritePos)
                                .Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = 3d;

                    // Рисуем внутренние границы таблицы отчёта
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + START_ROW_TO_WRITE, lastRangeLetter + currentWritePos)
                    .Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =
                        xlWorkSheet.get_Range(columnLettersForSafeReport[0] + START_ROW_TO_WRITE, lastRangeLetter + currentWritePos)
                        .Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = 2d;

                    string doctorPosition   = dc.Settings.First().DoctorPosition;
                    string doctorLastName   = dc.Settings.First().DoctorLastName;
                    string doctorFirstName  = dc.Settings.First().DoctorFirstName;
                    string doctorMiddleName = dc.Settings.First().DoctorMiddleName;

                    currentWritePos += 2;
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos,
                                          columnLettersForSafeReport[2] + currentWritePos).Merge();
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos).Font.Bold           = true;
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos++).Value             = "СКЛАВ:";

                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos,
                                          columnLettersForSafeReport[2] + currentWritePos).Merge();
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos).Font.Bold           = true;
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                    xlWorkSheet.get_Range(columnLettersForSafeReport[0] + currentWritePos).Value = doctorPosition;

                    xlWorkSheet.get_Range(firstRangeLetter + currentWritePos, lastRangeLetter + currentWritePos).Merge();
                    xlWorkSheet.get_Range(firstRangeLetter + currentWritePos).Font.Bold           = true;
                    xlWorkSheet.get_Range(firstRangeLetter + currentWritePos).HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
                    xlWorkSheet.get_Range(firstRangeLetter + currentWritePos).Value
                        = string.Format("{0}.{1}. {2}", doctorFirstName.Substring(0, 1), doctorMiddleName.Substring(0, 1), doctorLastName);

                    string directoryToSave = System.Configuration.ConfigurationManager.AppSettings["ReportsSaveDirectory"];
                    string fileName        = "Звіт по пацієнтах";

                    xlWorkbook.SaveAs(System.IO.Path.Combine(directoryToSave, fileName + ".xls"));
                    Notificator.ShowInfo("Звіт успішно сформовано!");
                }
            }
            catch (Exception ex)
            {
                Notificator.ShowError(ex.Message);
                return;
            }
            finally
            {
                xlWorkbook.Close(0);
                xlApp.Quit();
            }
        }
예제 #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (numInPackage.Value == 0)
            {
                Notificator.ShowError("В упаковці не може бути 0 од.");
                return;
            }

            if (dozages.Where(t => t.Agent == null).Count() > 0)
            {
                Notificator.ShowError("Ви не вибрали діючу речовину");
                return;
            }

            using (DiabetContext dc = new DiabetContext())
            {
                if (currentMedicament == null)
                {
                    currentMedicament = new Medicament();
                }

                // Обнуляем навигационные свойства для избежания ошибок
                currentMedicament.FullName       = null;
                currentMedicament.MedicamentType = null;
                currentMedicament.AgentDozages.Clear();

                currentMedicament.MedicamentNameId = (int)medNameBox.SelectedValue;
                currentMedicament.MedicamentTypeId = (int)packageType.SelectedValue;
                currentMedicament.NumInPack        = (int)numInPackage.Value;
                currentMedicament.Price            = priceField.Value;

                if (currentMedicament.Id > 0)
                {
                    dc.Medicaments.Attach(currentMedicament);
                    dc.Entry <Medicament>(currentMedicament).State = EntityState.Modified;
                }
                else
                {
                    dc.Medicaments.Add(currentMedicament);
                }
                dc.SaveChanges();

                foreach (var item in dozages)
                {
                    item.DozageMeter  = null;
                    item.MedicamentId = currentMedicament.Id;
                    dc.MedicamentGroups.Attach(item.Agent);
                    if (item.Id > 0)
                    {
                        dc.AgentDozages.Attach(item);
                        dc.Entry <AgentDozage>(item).State = EntityState.Modified;
                    }
                    else
                    {
                        dc.AgentDozages.Add(item);
                    }
                    dc.SaveChanges();
                }

                // Эти изменения не попадут в БД, а нужны лишь для отображения изменения по медикаменту в интерфейсе
                currentMedicament.FullName       = medNameBox.SelectedItem as MedicamentName;
                currentMedicament.MedicamentType = packageType.SelectedItem as MedicamentType;

                idDataChanged = true;

                Notificator.ShowInfo("Дані успішно збережені!");
            }
        }