private async Task <bool> LoadTreeItemData() { if (MainViewModel.Instance.SelectedElement == null) { return(false); } // отменяем выполняюшиеся задачи if (cancelTokenSource != null) { cancelTokenSource.Cancel(); } await ShowProgress("Пожалуйста, подождите...", "Получение данных..."); string data = string.Empty; try { bool result = await Task.Run <bool>(() => { /*PageResult<AllTariffsExportIndicationViewItem> pageResult = armtes.GetSmallEngineExportIndications(MainViewModel.Instance.StartDate); * if (pageResult != null) * { * List<AllTariffsExportIndicationViewItem> items = pageResult.Items; * if (items != null) * { * var accounts = armtes.GetPersonalAccounts(); * if (accounts != null) * { * var list = accounts.Items; * var accountsReses = list.GroupBy(i => i.ResName); * * var entp = armtes.GetEnterprises(); * var enterprises = entp.Items; * * var flat = enterprises.SelectMany(i => i.ChildEnterprises); * * var fes = flat.Where(i => i.EnterpriseName == "ОЭС"); * var reses = fes.SelectMany(i => i.ChildEnterprises); * * foreach (var res in reses) * { * var resAccounts = accountsReses.Where(a => a.Key == res.EnterpriseName).Select(i => i.ToList()).ToList(); * if (resAccounts != null && resAccounts.Count > 0) * foreach (var item in resAccounts[0]) * { * var viewitem = items.Where(i => i.PersonalAccount == item.PersonalAccount).ToList(); * if (viewitem != null) * { * ; * } * else * { * ; * } * } * } * * } * * * var c = pageResult.Count; * } * }*/ data = armtes.SelectElement( MainViewModel.Instance.SelectedElement.Value, MainViewModel.Instance.StartDate, MainViewModel.Instance.EndDate, MainViewModel.Instance.ProfileType, MainViewModel.Instance.SectorType); if (String.IsNullOrEmpty(data)) { return(false); } // убираем лишнее data = ClearString(data); SelectElementModel elementModel = null; elementModel = HtmlParser.ViewElement(data, MainViewModel.Instance.SelectedElement.Value, progressController); MainViewModel.Instance.Collectors = new System.Collections.ObjectModel.ObservableCollection <Collector>(elementModel.Collectors); MainViewModel.Instance.Statistics = elementModel.Statistics; return(true); }); if (result == false) { string errorDescription = this.GetNetErrorDescription(armtes.LastException); await this.ShowErrorMessageAsync(errorDescription); return(false); } MainViewModel.Instance.IsFullDataLoaded = false; await CloseProgress(); cancelTokenSource = new System.Threading.CancellationTokenSource(); cancelToken = cancelTokenSource.Token; try { // теперь обновляем информацию по всем системам MainViewModel.Instance.UpdatingProcessStarted = true; await Task.Factory.StartNew(() => { int collectorsCount = MainViewModel.Instance.Collectors.Count; string info = "Обновляем информацию по всем системам ... {0}%"; int processed = 0; object sync = new object(); ParallelOptions po = new ParallelOptions(); po.MaxDegreeOfParallelism = 4; Parallel.For(0, collectorsCount, po, (i, state) => { if (state.ShouldExitCurrentIteration) { if (state.LowestBreakIteration < i) { return; } } if (cancelToken.IsCancellationRequested) { this.DebugPrint("Отмена на {0}-й системе.)", i); state.Stop(); return; } Collector collector = MainViewModel.Instance.Collectors[i]; data = String.Empty; foreach (var obj in collector.Objects) { if (cancelToken.IsCancellationRequested) { this.DebugPrint("Отмена на {0}-й системе.)", i); state.Stop(); return; } data = null; int attempts = 1; while (data == null && attempts <= 3) { data = armtes.ViewObject( obj.Id, MainViewModel.Instance.SelectedElement.Value, MainViewModel.Instance.StartDate, MainViewModel.Instance.EndDate, MainViewModel.Instance.ProfileType, MainViewModel.Instance.SectorType); attempts++; } if (data != null) { // убираем лишнее data = ClearString(data); ViewDeviceModel viewDeviceModel = HtmlParser.ViewDevice(data, null); if (viewDeviceModel != null) { obj.ViewModel = viewDeviceModel; } foreach (var counter in obj.Counters) { if (cancelToken.IsCancellationRequested) { this.DebugPrint("Отмена на {0}-й системе.)", i); state.Stop(); return; } data = null; attempts = 1; while (data == null && attempts <= 3) { data = armtes.ViewMeter( counter.Id, MainViewModel.Instance.SelectedElement.Value, counter.ParentId, MainViewModel.Instance.StartDate, MainViewModel.Instance.EndDate, MainViewModel.Instance.ProfileType, MainViewModel.Instance.SectorType); attempts++; } if (data == null) { continue; } // убираем лишнее data = ClearString(data); ViewCounterModel vm = HtmlParser.ViewCounter(data, progressController); counter.ViewModel = vm; counter.PreviousIndications = vm.IndicationViewItem.PreviousIndications; counter.NextIndications = vm.IndicationViewItem.NextIndications; } } } lock (sync) { processed++; Dispatcher.BeginInvoke(new Action(() => SetAppStatus(String.Format(info, 100 * processed / collectorsCount))), System.Windows.Threading.DispatcherPriority.Send); } }); }, cancelTokenSource.Token) .ContinueWith((_) => { DebugPrint("Обновление информации по системам завершено."); MainViewModel.Instance.IsFullDataLoaded = true; MainViewModel.Instance.UpdatingProcessStarted = false; SetAppStatus(); if (cancelTokenSource != null) { cancelTokenSource.Dispose(); } cancelTokenSource = null; MainViewModel.Instance.FilteredCollectors.Refresh(); return(true); }); } catch (OperationCanceledException) { cancelTokenSource.Cancel(); MainViewModel.Instance.ShowMessage("Операция отменена.", MessageBoxButton.OK, MessageBoxImage.Information); } catch (AggregateException ae) { cancelTokenSource.Cancel(); foreach (Exception exception in ae.InnerExceptions) { if (exception is TaskCanceledException) { this.ShowErrorMessage(String.Format("Возникла ошибка!\nException: {0}", ((TaskCanceledException)exception).Message)); } else { this.ShowErrorMessage("Возникла ошибка!\nException: " + exception.GetType().Name); } } cancelTokenSource = null; } } catch (Exception ex) { cancelTokenSource.Cancel(); cancelTokenSource = null; this.ShowErrorMessage(ex.Message); } return(true); }
public static ViewDeviceModel ViewDevice(string data, ProgressDialogController progressController) { ViewDeviceModel result = new ViewDeviceModel(); try { HtmlNode td; string text; //data = System.IO.File.ReadAllText("data"); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); if (doc == null) { return(null); } doc.LoadHtml(data); if (doc.DocumentNode == null && doc.DocumentNode.ChildNodes == null) { return(null); } if (doc.DocumentNode.ChildNodes.Count > 1) { #region азбор секции с информацией о канале связи HtmlAgilityPack.HtmlNode jqTabsDevices = doc.DocumentNode.SelectNodes("//div[@id='jqTabsDevices']").Single(); if (jqTabsDevices == null) { return(null); } HtmlNodeCollection sessionInformation = jqTabsDevices.SelectNodes("div[2]/div/table/tbody/tr"); if (sessionInformation == null) { return(null); } result.Session = new SessionInformation(); // производитель модема td = sessionInformation[2].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.ModemManufacturer = text; // Модель устройства td = sessionInformation[3].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.Model = text; // описание td = sessionInformation[4].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.Description = text; // статус td = sessionInformation[6].SelectNodes("td[2]").Single(); text = td.InnerText; result.Session.CurrentStatus = text; // сеанс td = sessionInformation[7].SelectNodes("td[2]").Single(); text = td.InnerText; DateTime date = new DateTime(); result.Session.LastSessionDate = DateTime.TryParse(text, out date) ? date : date; #endregion #region азбор секции с показаниями HtmlAgilityPack.HtmlNode jqTabsBalances = doc.DocumentNode.SelectNodes("//div[@id='jqTabsBalances']").Single(); if (jqTabsBalances == null) { return(null); } HtmlNodeCollection counters = jqTabsBalances.SelectNodes("table/tbody/tr"); if (counters == null) { return(null); } result.CountersIndications = new List <IndicationViewItem>(); byte startIndex = 0; for (int i = 0; i < counters.Count; i++) { HtmlNodeCollection hnc = counters[i].SelectNodes("td"); startIndex = 0; IndicationViewItem ivi = new IndicationViewItem(); ivi.PreviousIndications = new Indications(); ivi.NextIndications = new Indications(); #region Парсинг // точка td = hnc[startIndex++]; text = td.InnerText; ivi.AccountingPoint = text; // тип td = hnc[startIndex++]; text = td.InnerText; ivi.CounterType = text; // предыдущие показания T0 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff0 = GetIndication(td.InnerText); // предыдущие показания T1 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff1 = GetIndication(td.InnerText); // предыдущие показания T2 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff2 = GetIndication(td.InnerText); // предыдущие показания T3 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff3 = GetIndication(td.InnerText); // предыдущие показания T4 td = hnc[startIndex++]; ivi.PreviousIndications.Tarriff4 = GetIndication(td.InnerText); // предыдущие показания достоверность td = hnc[startIndex++]; text = td.InnerText; ivi.PreviousIndications.DataReliability = text; // текущие показания T0 td = hnc[startIndex++]; ivi.NextIndications.Tarriff0 = GetIndication(td.InnerText); // текущие показания T1 td = hnc[startIndex++]; ivi.NextIndications.Tarriff1 = GetIndication(td.InnerText); // текущие показания T2 td = hnc[startIndex++]; ivi.NextIndications.Tarriff2 = GetIndication(td.InnerText); // текущие показания T3 td = hnc[startIndex++]; ivi.NextIndications.Tarriff3 = GetIndication(td.InnerText); // текущие показания T4 td = hnc[startIndex++]; ivi.NextIndications.Tarriff4 = GetIndication(td.InnerText); // предыдущие показания достоверность td = hnc[startIndex++]; text = td.InnerText; ivi.NextIndications.DataReliability = text; // разница td = hnc[startIndex++]; ivi.Difference = GetIndication(td.InnerText); #endregion result.CountersIndications.Add(ivi); } #endregion #region Качество показаний if (result.QualityIndications == null) { result.QualityIndications = new List <QualityIndications>(); } HtmlNodeCollection indicationsQualityMonths = doc.DocumentNode.SelectNodes("//table[contains(@class,'tableQualityIndications')]"); if (indicationsQualityMonths != null) { int monthsCount = indicationsQualityMonths.Count; for (int monthIndex = 0; monthIndex < monthsCount; monthIndex++) { QualityIndications qi = new QualityIndications(); HtmlNode m = indicationsQualityMonths[monthIndex].SelectNodes("thead/tr[1]/th[2]").Single(); qi.Period = m == null ? "???" : m.InnerText; qi.PointsData = ParseMonthQualityIndications(indicationsQualityMonths[monthIndex].SelectNodes("tbody/tr")); result.QualityIndications.Add(qi); } } #endregion } } catch (Exception ex) { //TODO: Добавить логирование _logger?.Error(ex); return(null); } return(result); }