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 ViewCounterModel ViewCounter(string data, ProgressDialogController progressController) { HtmlNode td; string text; ViewCounterModel result = new ViewCounterModel(); //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 info = jqTabsDevices.SelectNodes("div[2]/table/tbody/tr"); if (info == null) { return(null); } // Наименование точки учета td = info[0].SelectNodes("td[2]").Single(); text = td.InnerText; result.AccountPoint = text; // Тип счетчика td = info[1].SelectNodes("td[2]").Single(); text = td.InnerText; result.CounterType = text; // Заводской номер td = info[2].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.CounterNumber = text; // Сетевой адрес td = info[3].SelectNodes("td[2]").Single(); text = td.InnerText; result.CounterNetworkAddress = text; // Коэффициент трансформации td = info[5].SelectNodes("td[2]").Single(); text = td.InnerText; result.Ktt = text; // Производитель td = info[6].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.CounterManufacturer = text; // Тип учёта td = info[7].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.AccountType = text; // Полное название абонента td = info[8].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.AbonentFullName = text; // Название абонента td = info[9].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.AbonentName = text; // Короткое название абонента td = info[10].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.AbonentShortName = text; // Подстанция td = info[11].SelectNodes("td[2]").Single(); text = td.InnerText; result.Substation = text; // Название объекта td = info[12].SelectNodes("td[2]").Single(); text = td.InnerText; result.ObjectName = text; // Название точки учета td = info[13].SelectNodes("td[2]").Single(); text = td.InnerText; result.AccountPointName = text; // Номер ТП td = info[14].SelectNodes("td[2]").Single(); text = td.InnerText; result.TP = text; // Адрес объекта td = info[15].SelectNodes("td[2]").Single(); text = td.InnerText; result.ObjectAddress = text; // Населенный пункт объекта td = info[16].SelectNodes("td[2]").Single(); text = td.InnerText; result.ObjectState = text; // Адрес абонента td = info[17].SelectNodes("td[2]").Single(); text = td.InnerText; result.AbonentAddress = text; // Фидер td = info[18].SelectNodes("td[2]").Single(); text = td.InnerText; result.Fider = text; // Номер договора td = info[19].SelectNodes("td[2]").Single(); text = td.InnerText; result.DogNumber = text; // Родительский лиц счет td = info[20].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.AmperParentPointId = text; // РЭС td = info[21].SelectNodes("td[2]").Single(); text = td.InnerText; result.Departament = text; // Зав. номер из расч системы td = info[22].SelectNodes("td[2]").Single(); text = td.InnerText; result.AmperCounterNumber = text; // Лицевой счет td = info[23].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); result.AmperPointId = text; // Текущий статус td = info[24].SelectNodes("td[2]").Single(); text = td.InnerText; result.Status = text; // Последний сеанс td = info[25].SelectNodes("td[2]").Single(); text = td.InnerText.Trim(); DateTime date = new DateTime(); result.LastSessionDate = DateTime.TryParse( text, System.Globalization.CultureInfo.CreateSpecificCulture("en-US"), System.Globalization.DateTimeStyles.None, out date) ? date : date; #endregion #region азбор секции с показаниями HtmlAgilityPack.HtmlNode jqTabsSingleMeterIndications = doc.DocumentNode.SelectNodes("//div[@id='jqTabsSingleMeterIndications']").Single(); info = jqTabsSingleMeterIndications.SelectNodes("table/tbody/tr/td"); if (info == null) { return(null); } IndicationViewItem ivi = new IndicationViewItem(); ivi.PreviousIndications = new Indications(); ivi.NextIndications = new Indications(); #region Парсинг int startIndex = 0; // точка td = info[startIndex++]; text = td.InnerText; ivi.AccountingPoint = text; // тип td = info[startIndex++]; text = td.InnerText; ivi.CounterType = text; // предыдущие показания T0 td = info[startIndex++]; ivi.PreviousIndications.Tarriff0 = GetIndication(td.InnerText); // предыдущие показания T1 td = info[startIndex++]; ivi.PreviousIndications.Tarriff1 = GetIndication(td.InnerText); // предыдущие показания T2 td = info[startIndex++]; ivi.PreviousIndications.Tarriff2 = GetIndication(td.InnerText); // предыдущие показания T3 td = info[startIndex++]; ivi.PreviousIndications.Tarriff3 = GetIndication(td.InnerText); // предыдущие показания T4 td = info[startIndex++]; ivi.PreviousIndications.Tarriff4 = GetIndication(td.InnerText); // предыдущие показания достоверность td = info[startIndex++]; text = td.InnerText; ivi.PreviousIndications.DataReliability = text; // текущие показания T0 td = info[startIndex++]; ivi.NextIndications.Tarriff0 = GetIndication(td.InnerText); // текущие показания T1 td = info[startIndex++]; ivi.NextIndications.Tarriff1 = GetIndication(td.InnerText); // текущие показания T2 td = info[startIndex++]; ivi.NextIndications.Tarriff2 = GetIndication(td.InnerText); // текущие показания T3 td = info[startIndex++]; ivi.NextIndications.Tarriff3 = GetIndication(td.InnerText); // текущие показания T4 td = info[startIndex++]; ivi.NextIndications.Tarriff4 = GetIndication(td.InnerText); // предыдущие показания достоверность td = info[startIndex++]; text = td.InnerText; ivi.NextIndications.DataReliability = text; // разница td = info[startIndex++]; ivi.Difference = GetIndication(td.InnerText); #endregion result.IndicationViewItem = ivi; #endregion } return(result); }