public async Task <ConcurrentStack <string> > GetPatientsFromCache(CacheDB cacheDB, int stackLimitCount, bool stopIfStackLimitReached = false) //определяет полные ФИО из БД кэша { return(await Task.Run(() => { var patients = new ConcurrentStack <string>(); int polisColumn = FindColumnIndex("ENP", 1); int fioColumn = FindColumnIndex("FIO", 1); if ((polisColumn == -1) || (fioColumn == -1)) { return patients; } //поиск полного ФИО или добавление в лист обработки cacheDB.PrepareGetPatients(); Parallel.For(2, maxRow + 1, (i, state) => { lock (this) if (ws.Cells[i, polisColumn].Value == null) { return; } Patient patient; lock (this) patient.fioShort = ws.Cells[i, fioColumn].Value.ToString(); if (patient.fioShort.Length > 3) //если ФИО уже полные { return; } patient.fioFull = ""; lock (this) patient.polis = ws.Cells[i, polisColumn].Value.ToString(); patient.fioFull = cacheDB.GetPatient(patient).fioFull; if (patient.fioFull != null) //если фио найдено в кэше { lock (this) ws.Cells[i, fioColumn].Value = patient.fioFull; } else if (patients.Count < stackLimitCount) //если фио не найдено в кэше добавляем в лист поиска через сайт { patients.Push(patient.polis); } else if (stopIfStackLimitReached) { state.Break(); } }); while (patients.Count > stackLimitCount) //из-за асинхронного выполнения, размер стэка может получиться больше чем надо, выкидываем лишнее { patients.TryPop(out string _); } return patients; })); }
private void button1_Click(object sender, EventArgs e) //Оптимизация БД кэша { if (File.Exists("CacheDB.sdf")) { toolStripStatusLabel1.Text = "Выполняется, ждите..."; using (CacheDB cacheDB = new CacheDB()) cacheDB.Optimize(); toolStripStatusLabel1.Text = "Готово. БД кэша оптимизрована."; } else { toolStripStatusLabel1.Text = "БД кэша отсутствует. Оптимизация не требуется."; } }
private async void button2_Click(object sender, EventArgs e) //Добавить в кэш из xlsx { try { DisableButtons(); toolStripStatusLabel1.Text = "Выполняется, ждите..."; OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.InitialDirectory = Path.GetDirectoryName(settings.Path); fileDialog.Filter = "xlsx files (*.xslx)|*.xlsx"; if (fileDialog.ShowDialog() == DialogResult.OK) { bool overrideMode = (DialogResult.Yes == MessageBox.Show("Загружаемые данные новее чем в кэше? \r\nЕсли не уверены, нажмите \"Нет\"", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)); using (CacheDB cacheDB = new CacheDB()) using (ExcelFile excel = new ExcelFile()) { await excel.Open(fileDialog.FileName); var patients = await excel.ToList(); int n = await cacheDB.AddPatients(patients, overrideMode); toolStripStatusLabel1.Text = string.Format("Готово. В кэш добавлено {0} записи(ей).", n); } } else { toolStripStatusLabel1.Text = "Отменено."; } EnableButtons(); } catch (Exception) { toolStripStatusLabel1.Text = "Произошла непредвиденная ошибка. Операция завершена некорректно."; throw; } finally { EnableButtons(); } }
private async void button6_Click(object sender, EventArgs e) //начать определение ФИО { try { DisableButtons(); if (settings.TestPassed == false) { await TestSetting(); } if (settings.TestPassed) { int maxReq = 0, madeReq = 0, step = 2; string xlsxStatus; if (settings.DownloadFile) { toolStripStatusLabel1.Text = string.Format("{0}. Выполняется загрузка файла из СРЗ, ждите...", step++); using (WebSiteSRZ site = new WebSiteSRZ(settings.Site, settings.ProxyAddress, settings.ProxyPort)) { await site.Authorize(settings.Accounts[0]); await site.DownloadFile(settings.Path, dateTimePicker1.Value); site.Logout(); } } toolStripStatusLabel1.Text = string.Format("{0}. Выполняется обработка из кэша, ждите...", step++); foreach (Credential cred in settings.Accounts) { maxReq += cred.Requests; } using (CacheDB cacheDB = new CacheDB()) using (var excel = new ExcelFile()) { await excel.Open(settings.Path, settings.ColumnSynonims); ConcurrentStack <string> listJobs = await excel.GetPatientsFromCache(cacheDB, maxReq, true); if (listJobs.Count > 0) { toolStripStatusLabel1.Text = string.Format("{0}. Выполняется поиск пациентов в СРЗ, ждите...", step++); List <Patient> patients = await WebSiteSRZ.GetPatients(listJobs, settings.CopyAccounts(), settings.Threads, settings); madeReq = patients.Count; toolStripStatusLabel1.Text = string.Format("{0}. Выполняется добавление в кэш, ждите...", step++); await cacheDB.AddPatients(patients, true); toolStripStatusLabel1.Text = string.Format("{0}. Выполняется обработка из кэша, ждите...", step++); listJobs = await excel.GetPatientsFromCache(cacheDB, int.MaxValue); } if (listJobs.Count == 0) { if (settings.RenameGender) { await excel.RenameSex(); } if (settings.RenameColumnNames) { await excel.ProcessColumns(); } if (settings.ColumnOrder) { await excel.SetColumnsOrder(); } if (settings.ColumnAutoWidth) { await excel.FitColumnWidth(); } if (settings.AutoFilter) { await excel.AutoFilter(); } xlsxStatus = "Файл готов, найдены все ФИО."; } else { xlsxStatus = String.Format("Файл не готов, осталось запросить в СРЗ {0} ФИО.", listJobs.Count); } await excel.Save(); toolStripStatusLabel1.Text = String.Format("Готово. Запрошено пациентов в СРЗ: {0} из {1} разрешенных. {2}", madeReq, maxReq, xlsxStatus); if (autoStart) { Environment.Exit(0); //выход с кодом 0 если запущено с командной строки } } } } catch (Exception) { toolStripStatusLabel1.Text = "Произошла непредвиденная ошибка. Операция завершена некорректно."; if (autoStart) { Environment.Exit(1); //выход с кодом 1 если запущено с командной строки } throw; } finally { EnableButtons(); } }