Example #1
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;
            }
        }
Example #2
0
        private void deleteConcreteMedLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Medicament selectedItem = concreteMedTable.Rows[concreteMedTable.SelectedCells[0].RowIndex].DataBoundItem as Medicament;

            if (!TryDeleteRecord(selectedItem))
            {
                Notificator.ShowError("Неможливо видалити медикамент, тому що на нього э посилання в записах пацієнтів");
                return;
            }

            concreteMedTable.Rows.RemoveAt(concreteMedTable.SelectedCells[0].RowIndex);
        }
Example #3
0
        private void deleteAgentLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MedicamentAgent selectedItem = agentsTable.Rows[agentsTable.SelectedCells[0].RowIndex].DataBoundItem as MedicamentAgent;

            if (!TryDeleteRecord(selectedItem))
            {
                Notificator.ShowError("Неможливо видалити діючу речовину, тому що під неї створені записи про медикаменти");
                return;
            }

            agentsTable.Rows.RemoveAt(agentsTable.SelectedCells[0].RowIndex);
        }
Example #4
0
        private void deleteMedicamentLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MedicamentName selectedItem = medicamentTable.Rows[medicamentTable.SelectedCells[0].RowIndex].DataBoundItem as MedicamentName;

            if (!TryDeleteRecord(selectedItem))
            {
                Notificator.ShowError("Неможливо видалити медикамент, тому що він присутній у записах пацієнтів");
                return;
            }

            medicamentTable.Rows.RemoveAt(medicamentTable.SelectedCells[0].RowIndex);
        }
Example #5
0
        private void deletePackageButton_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MedicamentType selectedItem = medPackageTable.Rows[medPackageTable.SelectedCells[0].RowIndex].DataBoundItem as MedicamentType;

            if (!TryDeleteRecord(selectedItem))
            {
                Notificator.ShowError("Неможливо видалити цю одиницю виміру так як вона використовується в інших записах БД");
                return;
            }

            medPackageTable.Rows.RemoveAt(medPackageTable.SelectedCells[0].RowIndex);
        }
Example #6
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("Дані успішно збережені!");
            }
        }
Example #7
0
        private void deleteCommuneButton_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (DiabetContext dc = new DiabetContext())
            {
                int     selectedRow     = communesTable.CurrentCell.RowIndex;
                Commune selectedCommune = communesTable.Rows[selectedRow].DataBoundItem as Commune;

                if (TryDeleteCommune(selectedCommune))
                {
                    communesTable.Rows.RemoveAt(selectedRow);
                    communesListIsChange = true;
                }
                else
                {
                    Notificator.ShowError("Неможливо видалити громаду, так як в БД існують пацієнти записані на цю громаду");
                }
            }
        }
Example #8
0
 static void Main()
 {
     try
     {
         MainFormWaiter.BeginWaiting("Програма завантажуєтся ...");
         MainForm mf = new MainForm();
         MainFormWaiter.EndWaiting();
         Application.EnableVisualStyles();
         //Application.SetCompatibleTextRenderingDefault(false);
         mf.Activate();
         Application.Run(mf);
     }
     catch (Exception ex)
     {
         Notificator.ShowError(string.Format("{0}\n{1}", ex.Message, ex.StackTrace));
     }
     finally
     {
         MainFormWaiter.EndWaiting();
     }
 }
Example #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(histRecMsg.Text))
            {
                Notificator.ShowError("Введіть текст запису");
                return;
            }

            PatientHistoryRecord newPatHistRec = new PatientHistoryRecord();

            newPatHistRec.Description = histRecMsg.Text;
            newPatHistRec.RecordDate  = histRecDate.Value;

            patientHistoryRecordsList.Add(newPatHistRec);
            addPatHistList.Add(newPatHistRec);

            if (dbRecord.Id > 0)
            {
                newPatHistRec.PatientId = dbRecord.Id;
            }

            dataGridView1.Refresh();
        }
Example #10
0
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Analyze selectedItem = analizesTable.Rows[analizesTable.SelectedCells[0].RowIndex].DataBoundItem as Analyze;

            if (TryDelete(selectedItem))
            {
                analizesList.Remove(selectedItem);
                analizesTable.Refresh();

                new Task(() =>
                {
                    using (DiabetContext dc = new DiabetContext())
                    {
                        dc.Meters.Attach(selectedItem.AnalizeMeter);
                        dc.Entry <Analyze>(selectedItem).State = EntityState.Deleted;
                        dc.SaveChanges();
                    }
                }).Start();
            }
            else
            {
                Notificator.ShowError("Неможливо видалити аналіз так як на нього є посилання в записах пацієнтів");
            }
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string templateFilePath = System.IO.Path.Combine(PathFinder.GetProgramPath(),
                                                             "template",
                                                             "template_yearneed.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(2);

            xlApp.DisplayAlerts = false;

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

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

            List <MedicamentAssignation> originalAssignation = new List <MedicamentAssignation>();

            using (DiabetContext dc = new DiabetContext())
            {
                originalAssignation = dc.MedicamentAssigantions
                                      .Include(t => t.AssignMedicament)
                                      .Include(t => t.AssignMedicament.AgentDozages)
                                      .Include(t => t.AssignMedicament.AgentDozages.Select(m => m.Agent))
                                      .Include(t => t.AssignMedicament.AgentDozages.Select(m => m.DozageMeter))
                                      .Include(t => t.Patient)
                                      .Include(t => t.Patient.PatientCommune)
                                      .Include(t => t.AssignMedicament.FullName)
                                      .Include(t => t.AssignMedicament.MedicamentType)
                                      .ToList();
            }
            backgroundWorker1.ReportProgress(8);

            // Заменяем медикаменты, который требуется изменить
            List <YearMedicamentNeed> medicamentsToReplace = medicamentsList.Where(t => t.OldMedNameValue != null).ToList();

            if (medicamentsToReplace.Count > 0)
            {
                foreach (var item in originalAssignation)
                {
                    foreach (var item2 in medicamentsToReplace)
                    {
                        if (item.AssignMedicament.Equals(item2.OldMedNameValue))
                        {
                            item.AssignMedicament = item2.MedName;
                        }
                    }
                }
            }
            backgroundWorker1.ReportProgress(10);

            List <ExcelYearMedicamentNeedItem> medicamentsRightList = originalAssignation
                                                                      .GroupBy(t => new { t.Patient.PatientCommune, t.AssignMedicament })
                                                                      .Select(t => new ExcelYearMedicamentNeedItem
            {
                Commune      = t.Key.PatientCommune,
                Medicament   = t.Key.AssignMedicament,
                NumOfTablets = t.Sum(m => m.YearDozage)
            }).ToList();

            backgroundWorker1.ReportProgress(12);

            var medicamentsGroupedByCommuneList = medicamentsRightList
                                                  .GroupBy(t => t.Commune)
                                                  .Select(t => new
            {
                Commune    = t.Key,
                Medicament = t.Select(m => new ExcelYearMedicamentNeedItem
                {
                    Commune      = t.Key,
                    Medicament   = m.Medicament,
                    NumOfTablets = m.NumOfTablets
                }).ToList()
            }).ToList();

            backgroundWorker1.ReportProgress(14);

            int communeGroupsCount = medicamentsGroupedByCommuneList.Count();

            int    currentWritePosition   = EXCEL_START_ROW;
            string numColumnLetter        = "A";
            string nameColumnLetter       = "B";
            string tabletsNumLetter       = "C";
            string packageNumColumnLetter = "D";
            string priceColumnLetter      = "E";
            string sumColumnLetter        = "F";

            try
            {
                xlWorkSheet.get_Range("A2").Value = "РІЧНА ПОТРЕБА В МЕДИКАМЕНТАХ НА " + reportYear + " РІК";
                Dictionary <Medicament, MedicamentTotalsForExcel> medicamentTotals = new Dictionary <Medicament, MedicamentTotalsForExcel>();
                int    progressRest           = 90 - Convert.ToInt32(progressBar1.Value);
                double progressStepForCommune = (progressRest * 1.0) / communeGroupsCount;
                for (int i = 0; i < communeGroupsCount; i++, currentWritePosition++)
                {
                    if (workWasCanceled)
                    {
                        throw new Exception("Формування звіту було відмінене користувачем!");
                    }

                    // Выводи данные (название) громады
                    xlWorkSheet.get_Range(numColumnLetter + currentWritePosition, sumColumnLetter + currentWritePosition).Merge();
                    xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Font.Bold           = true;
                    xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                    xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Value = medicamentsGroupedByCommuneList[i].Commune.ToString();

                    // Выводим список используемых медикаментов пациентами-жителями громады
                    int medicamentsCount = medicamentsGroupedByCommuneList[i].Medicament.Count();
                    currentWritePosition++;
                    for (int j = 0; j < medicamentsCount; j++, currentWritePosition++)
                    {
                        if (workWasCanceled)
                        {
                            throw new Exception("Формування звіту було відмінене користувачем!");
                        }

                        xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Value        = (j + 1).ToString();
                        xlWorkSheet.get_Range(nameColumnLetter + currentWritePosition).Value       = medicamentsGroupedByCommuneList[i].Medicament[j].Medicament.ToString();
                        xlWorkSheet.get_Range(tabletsNumLetter + currentWritePosition).Value       = medicamentsGroupedByCommuneList[i].Medicament[j].NumOfTablets.ToString();
                        xlWorkSheet.get_Range(packageNumColumnLetter + currentWritePosition).Value = medicamentsGroupedByCommuneList[i].Medicament[j].numOfPackages.ToString();
                        xlWorkSheet.get_Range(priceColumnLetter + currentWritePosition).Value      = medicamentsGroupedByCommuneList[i].Medicament[j].Medicament.Price.ToString();
                        xlWorkSheet.get_Range(sumColumnLetter + currentWritePosition).Value        = "=" + packageNumColumnLetter + currentWritePosition + "*" + priceColumnLetter + currentWritePosition;

                        // Записываем адреса ячеек с суммами по медикаментам
                        if (!medicamentTotals.ContainsKey(medicamentsGroupedByCommuneList[i].Medicament[j].Medicament))
                        {
                            medicamentTotals.Add(medicamentsGroupedByCommuneList[i].Medicament[j].Medicament,
                                                 new MedicamentTotalsForExcel());
                        }

                        medicamentTotals[medicamentsGroupedByCommuneList[i].Medicament[j].Medicament]
                        .MedicamentTabletCells.Add(tabletsNumLetter + currentWritePosition);
                        medicamentTotals[medicamentsGroupedByCommuneList[i].Medicament[j].Medicament]
                        .MedicamentPackageCells.Add(packageNumColumnLetter + currentWritePosition);
                        medicamentTotals[medicamentsGroupedByCommuneList[i].Medicament[j].Medicament]
                        .Price = medicamentsGroupedByCommuneList[i].Medicament[j].Medicament.Price;
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.Append("=");
                    for (int k = medicamentsCount; k > 0; k--)
                    {
                        sb.Append((sumColumnLetter + (currentWritePosition - k)) + "+");
                    }

                    xlWorkSheet.get_Range(nameColumnLetter + currentWritePosition).Value     = "ВСЬОГО";
                    xlWorkSheet.get_Range(nameColumnLetter + currentWritePosition).Font.Bold = true;
                    xlWorkSheet.get_Range(sumColumnLetter + currentWritePosition).Value      = sb.ToString().Substring(0, sb.ToString().Count() - 1);
                    xlWorkSheet.get_Range(sumColumnLetter + currentWritePosition).Font.Bold  = true;

                    int progressChange = Convert.ToInt32(progressRest + progressStepForCommune);
                    backgroundWorker1.ReportProgress(progressChange);
                }

                // Выводим итоги
                currentWritePosition++;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition, sumColumnLetter + currentWritePosition).Merge();
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Font.Bold           = true;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Value = "ЗАГАЛЬНА ПОТРЕБА";
                currentWritePosition++;
                foreach (Medicament key in medicamentTotals.Keys)
                {
                    if (workWasCanceled)
                    {
                        throw new Exception("Формування звіту було відмінене користувачем!");
                    }

                    xlWorkSheet.get_Range(nameColumnLetter + currentWritePosition).Value           = key.ToString();
                    xlWorkSheet.get_Range(nameColumnLetter + currentWritePosition).Font.Bold       = true;
                    xlWorkSheet.get_Range(tabletsNumLetter + currentWritePosition).Value           = medicamentTotals[key].GetTabletsSumFormula();
                    xlWorkSheet.get_Range(tabletsNumLetter + currentWritePosition).Font.Bold       = true;
                    xlWorkSheet.get_Range(packageNumColumnLetter + currentWritePosition).Value     = medicamentTotals[key].GetPackagesSumFormula();
                    xlWorkSheet.get_Range(packageNumColumnLetter + currentWritePosition).Font.Bold = true;
                    xlWorkSheet.get_Range(priceColumnLetter + currentWritePosition).Value          = medicamentTotals[key].Price;
                    xlWorkSheet.get_Range(priceColumnLetter + currentWritePosition).Font.Bold      = true;
                    xlWorkSheet.get_Range(sumColumnLetter + currentWritePosition).Value            = "=" + (priceColumnLetter + currentWritePosition) + "*" + (packageNumColumnLetter + currentWritePosition);
                    xlWorkSheet.get_Range(sumColumnLetter + currentWritePosition).Font.Bold        = true;
                    currentWritePosition++;
                }

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

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

                // Подписываемся под отчётом
                currentWritePosition += 2;

                string doctorPosition   = string.Empty;
                string doctorFirstName  = string.Empty;
                string doctorLastName   = string.Empty;
                string doctorMiddleName = string.Empty;

                using (DiabetContext dc = new DiabetContext())
                {
                    doctorPosition   = dc.Settings.First().DoctorPosition;
                    doctorFirstName  = dc.Settings.First().DoctorFirstName;
                    doctorLastName   = dc.Settings.First().DoctorLastName;
                    doctorMiddleName = dc.Settings.First().DoctorMiddleName;
                }

                // Составитель
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition, nameColumnLetter + currentWritePosition).Merge();
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Value               = "Склав:";
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Font.Bold           = true;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

                currentWritePosition++;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition, nameColumnLetter + currentWritePosition).Merge();
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Value               = doctorPosition;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Font.Bold           = true;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

                xlWorkSheet.get_Range(priceColumnLetter + currentWritePosition, sumColumnLetter + currentWritePosition).Merge();
                xlWorkSheet.get_Range(priceColumnLetter + currentWritePosition).Value               = string.Format("{1}.{2}. {0}", doctorLastName, doctorFirstName.Substring(0, 1), doctorMiddleName.Substring(0, 1));
                xlWorkSheet.get_Range(priceColumnLetter + currentWritePosition).Font.Bold           = true;
                xlWorkSheet.get_Range(priceColumnLetter + currentWritePosition).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

                // Дата составления
                currentWritePosition += 2;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition, nameColumnLetter + currentWritePosition).Merge();
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
                xlWorkSheet.get_Range(numColumnLetter + currentWritePosition).Value = string.Format("Дата складення: {0}", DateTime.Now.ToShortDateString());

                string filenameToSave = "Потреба медикаменти на " + reportYear + " рік.xls";
                string saveFilePath   = System.Configuration.ConfigurationManager.AppSettings["ReportsSaveDirectory"];
                xlWorkbook.SaveAs(System.IO.Path.Combine(saveFilePath, filenameToSave));
                backgroundWorker1.ReportProgress(100);
                workWasCanceled = false;
            }
            catch (Exception ex)
            {
                Notificator.ShowError(ex.Message);
            }
            finally
            {
                xlWorkbook.Close(0);
                xlApp.Quit();
            }
        }
Example #12
0
 private void medicamentsTable_DataError(object sender, DataGridViewDataErrorEventArgs e)
 {
     Notificator.ShowError(e.Exception.Message + "\nStack trace: " + e.Exception.StackTrace);
 }
Example #13
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;
            }
        }
Example #14
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();
            }
        }
Example #15
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("Дані успішно збережені!");
            }
        }
Example #16
0
        public AppBarModel()
        {
            MenuItems = new SafeObservable <BindableAppBarMenuItem>();
            Buttons   = new SafeObservable <BindableAppBarButton>();

            AddButton = new DelegateCommand(() =>
            {
                if (Buttons.Count < 4)
                {
                    Buttons.Add(new BindableAppBarButton {
                        Text = NewItemText, IconUri = new Uri("/Toolkit.Content/ApplicationBar.Select.png", UriKind.Relative)
                    });
                }
                else
                {
                    Notificator.ShowError("Woops, too many buttons.");
                }
            });

            AddMenuItem = new DelegateCommand(() => MenuItems.Add(new BindableAppBarMenuItem {
                Text = NewItemText
            }));

            var button = new BindableAppBarToggleButton
            {
                Text1    = "not toggled",
                Text2    = "toggled",
                IconUri1 = new Uri("/Toolkit.Content/ApplicationBar.Add.png", UriKind.Relative),
                IconUri2 = new Uri("/Toolkit.Content/ApplicationBar.Delete.png", UriKind.Relative)
            };

            var hlButton = new BindableAppBarHyperlinkButton
            {
                Text    = "external link",
                IconUri = new Uri("/Toolkit.Content/ApplicationBar.Check.png", UriKind.Relative),
                Uri     = "http://github.com/gjulianm/AncoraMVVM"
            };

            var hlIButton = new BindableAppBarHyperlinkButton
            {
                Text    = "internal link",
                IconUri = new Uri("/Toolkit.Content/ApplicationBar.Check.png", UriKind.Relative),
                Uri     = "/Views/MainPage.xaml"
            };

            Buttons.Add(button);
            Buttons.Add(hlButton);
            Buttons.Add(hlIButton);

            MenuItems.Add(new BindableAppBarHyperlinkMenuItem {
                Text = "external link", Uri = "http://github.com/gjulianm/AncoraMVVM"
            });

            this.PropertyChanged += (sender, e) =>
            {
                if (e.PropertyName == "Toggled")
                {
                    button.Toggled = Toggled;
                }
            };

            Opacity = 0.5;
        }