private Task <ObservableCollection <ServiceReference.ARM_20_Service.Dict_Balance_FreeHierarchy_Subsection> > LoadSubsectionsTask()
        {
            return(Task <ObservableCollection <Proryv.AskueARM2.Client.ServiceReference.ARM_20_Service.Dict_Balance_FreeHierarchy_Subsection> > .Factory.StartNew(() =>
            {
                ObservableCollection <Proryv.AskueARM2.Client.ServiceReference.ARM_20_Service.Dict_Balance_FreeHierarchy_Subsection> subsections;
                try
                {
                    var request = ServiceFactory.ArmServiceInvokeSync <Tuple <string, List <Proryv.AskueARM2.Client.ServiceReference.ARM_20_Service.Dict_Balance_FreeHierarchy_Subsection> > >("BL_GetFreeHierarchyBalanceSubsections", _hierarchyObject.Type, _hierarchyObject.Id);
                    if (request != null)
                    {
                        subsections = new ObservableCollection <Proryv.AskueARM2.Client.ServiceReference.ARM_20_Service.Dict_Balance_FreeHierarchy_Subsection>(request.Item2);
                        _balance.BalanceFreeHierarchyObject_UN = request.Item1;
                    }
                    else
                    {
                        subsections = new ObservableCollection <Proryv.AskueARM2.Client.ServiceReference.ARM_20_Service.Dict_Balance_FreeHierarchy_Subsection>();
                    }
                }
                catch (Exception ex)
                {
                    Manager.UI.ShowMessage("Ошибка подгрузки подразделов :" + ex.Message);
                    return null;
                }

                //lvBalance.Dispatcher.BeginInvoke((Action)(() =>
                //{
                //    lvBalance.Resources["Subsections"] = subsections;
                //    lvBalance.Resources["BalanceFreeHierarchyObjectUn"] = _balance.BalanceFreeHierarchyObject_UN;

                //}));

                return subsections;
            }));
        }
        public static R BuildandWaitResult <R, P>(P groupTpWaiterParams, string methodName
                                                  , Action <string> onError, Action <double> incProgress = null
                                                  , CancellationToken?cancellationToken = null, Action <bool> setIndeterminat = null
                                                  )
            where R : class //Тип для результата
            where P : class //Тип для параметров
        {
            ProtoInitializer.InitProtobuf();

            int voidPacketLimit;

            var setting = EnumClientServiceDictionary.GetGlobalSettingsByName(RegistrySettings.FolderVisual, RegistrySettings.SettingVoidPacketLimit);

            if (setting == null || setting.Setting == null || !int.TryParse(setting.Setting, out voidPacketLimit) ||
                voidPacketLimit < 10) //Максимальное количество не ограничиваем
            {
                voidPacketLimit = 24001;
            }

            Guid loaderId;

            try
            {
                MemoryStream compressedParam;
                using (var ms = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(ms, groupTpWaiterParams);
                    ms.Position     = 0;
                    compressedParam = CompressUtility.CompressGZip(ms);
                }

                compressedParam.Position = 0;
                loaderId = ARM_Service.Builder_StartWait(compressedParam, methodName);
                Thread.Sleep(100);
            }
            catch (Exception ex)
            {
                if (onError != null)
                {
                    onError("Ошибка запуска построителя фак. мощности: " + ex.Message);
                }
                return(null);
            }

            var isLastPacket  = false;
            var voidCounter   = 0;
            var errCounter    = 0;
            var requestNumber = 0;
            var ca            = new List <byte>();

            var packetSize = 0.0; //Тут надо подумать как возвращать правильный размер, возможно никак

            do
            {
                if (cancellationToken.HasValue && cancellationToken.Value.IsCancellationRequested)
                {
                    ARM_Service.Builder_Cancel(loaderId);
                    break; //Отмена выполнения
                }

                try
                {
                    var packet = ServiceFactory.ArmServiceInvokeSync <BuilderPartResult>("Builder_GetNextPart", requestNumber, loaderId);
                    if (packet != null)
                    {
                        if (!string.IsNullOrEmpty(packet.Errors))
                        {
                            //Это критическая ошибка, продолжать нельзя
                            if (onError != null)
                            {
                                onError(packet.Errors);
                            }
                            break;
                        }

                        isLastPacket = packet.IsLastPacket;
                        if (isLastPacket)
                        {
                            break;
                        }

                        if (packet.Part != null && packet.Part.Length > 0)
                        {
                            //requestNumber++;
                            if (requestNumber == 0)
                            {
                                if (packet.PacketRemaining == 0)
                                {
                                    packetSize = 1;
                                }
                                else
                                {
                                    packetSize = 100 / (double)packet.PacketRemaining;
                                }

                                if (setIndeterminat != null)
                                {
                                    setIndeterminat(false);
                                }
                            }

                            ca.InsertRange(0, packet.Part.ToArray());
                            requestNumber++;

                            packet.Part.Close();
                            packet.Part.Dispose();

                            voidCounter = 0;

                            Thread.Sleep(10);
                        }
                        else
                        {
                            if (++voidCounter > voidPacketLimit)
                            {
                                isLastPacket = true;
                                if (onError != null)
                                {
                                    onError("ClientSideMultithreadBuilder: Превышен лимит ожидания пакетов");
                                }
                            }
                            else
                            {
                                Thread.Sleep(300);
                            }
                        }

                        errCounter = 0;
                    }
                    else
                    {
                        if (++errCounter > 50)
                        {
                            isLastPacket = true;
                            if (onError != null)
                            {
                                onError("ClientSideMultithreadBuilder: Превышен лимит пустых пакетов");
                            }
                        }

                        Thread.Sleep(5000);
                    }
                }
                catch (Exception ex)
                {
                    if (++errCounter > 6)
                    {
                        isLastPacket = true;
                        if (onError != null)
                        {
                            onError("ClientSideMultithreadBuilder: Сервер не отвечает");
                        }
                    }
                    else
                    {
                        if (onError != null)
                        {
                            onError(ex.Message);
                        }
                        Thread.Sleep(5000);
                    }
                }

                if (incProgress != null)
                {
                    incProgress(packetSize);
                }
            } while (!isLastPacket);

            var compressed = new MemoryStream(ca.ToArray());

            ca = null;

            R result = null;

            if (compressed.Length > 2)
            {
                try
                {
                    using (var ms = CompressUtility.DecompressGZip(compressed))
                    {
                        compressed.Close();
                        compressed.Dispose();

                        ms.Position = 0;
                        result      = ProtoBuf.Serializer.Deserialize <R>(ms);
                    }
                }
                catch (Exception ex)
                {
                    if (onError != null)
                    {
                        onError("ClientSideMultithreadBuilder: Ошибка обработки результата: " + ex.Message);
                    }
                }
            }

            GC.Collect();

            return(result);
        }
        private Tuple <List <IDHierarchy>, string, CancellationToken> InvokeSearch(string text, string parentText, enumTypeHierarchy?typeHierarchy, CancellationToken token)
        {
            var needFindTI     = _descriptor.NeedFindTI;
            var needFindUaNode = _descriptor.NeedFindUaNode;
            var needFindTransformatorsAndreactors = _descriptor.NeedFindTransformatorsAndreactors; //Необходим поиск трансформаторов и реакторов по базе (т.к. еще не подгрузились)
            var freeHierTreeId        = _descriptor.Tree_ID ?? -101;
            var findUspdAndE422InTree = _descriptor.ShowUspdAndE422InTree;
            var tiComparer            = new IFreeHierarchyObjectComparerTyped();
            var objectComparer        = new HierarchyObjectFoundedComparer();
            var foundedObjects        = new ConcurrentStack <IDHierarchy>();

#if DEBUG
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
#endif
            Parallel.Invoke(() =>
            {
                //if (_findTiType == EnumFindTiType.Pik) return;

                try
                {
                    //поиск прочих объектов
                    var hierObjects =
                        ARM_Service.TREE_FindHierObject(text, parentText, Manager.User.User_ID, freeHierTreeId, _findTiType.ToString(), findUspdAndE422InTree, typeHierarchy);
                    if (hierObjects != null && hierObjects.Count > 0)
                    {
                        foundedObjects.PushRange(hierObjects.OrderBy(h => h.TypeHierarchy).ThenByDescending(h => h, objectComparer).ToArray());
                    }
                }
                catch (Exception ex)
                {
                    Manager.UI.ShowMessage(ex.Message);
                }
            },
                            () =>
            {
                if (!needFindTransformatorsAndreactors)
                {
                    return;
                }

                try
                {
                    //Поиск трансформаторов и реакторов
                    var reactorsAndTransformators = ServiceFactory.ArmServiceInvokeSync <Tuple <List <Hard_PTransformator>, List <Hard_PReactors> > >("TREE_TransformatorOrReactor", text);
                    if (reactorsAndTransformators != null)
                    {
                        if (reactorsAndTransformators.Item1 != null)
                        {
                            reactorsAndTransformators.Item1.ForEach(transformator =>
                            {
                                foundedObjects.Push(
                                    EnumClientServiceDictionary.GetOrAddTransformator(transformator.PTransformator_ID,
                                                                                      transformator));
                            });
                        }

                        if (reactorsAndTransformators.Item2 != null)
                        {
                            reactorsAndTransformators.Item2.ForEach(reactor =>
                            {
                                foundedObjects.Push(
                                    EnumClientServiceDictionary.GetOrAddReactor(reactor.PReactor_ID, reactor));
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    Manager.UI.ShowMessage(ex.Message);
                }
            },
                            () =>
            {
                //Поиск узлов OPC на дереве

                if (!needFindUaNode)
                {
                    return;
                }

                try
                {
                    var opcNodes = UAService.Service.UA_FindNode(text, freeHierTreeId, _findTiType == EnumFindTiType.MeterSerialNumber ? "UANode_ID" : null); // "UANode_ID"
                    if (opcNodes != null && opcNodes.Count > 0)
                    {
                        //Предварительная прогрузка узлов с типами найденных узлов (чтобы визуалка не тормозила)
                        UAHierarchyDictionaries.UANodesDict.Prepare(new HashSet <long>(opcNodes
                                                                                       .Where(fn => fn.Node.UATypeNode_ID.HasValue)
                                                                                       .Select(fn => fn.Node.UATypeNode_ID.Value)));

                        foundedObjects.PushRange(opcNodes.ToArray());
                    }
                }
                catch (Exception ex)
                {
                    Manager.UI.ShowMessage(ex.Message);
                }
            });

#if DEBUG
            sw.Stop();
            Console.WriteLine("Поиск {0} млс", sw.ElapsedMilliseconds);
#endif

            //Отмена поиска
            if (token.IsCancellationRequested)
            {
                return(null);
            }

            //Подготавливаем словари
            Task.Factory.StartNew(() => FreeHierarchyTreePreparer.PrepareGlobalDictionaries(foundedObjects, token: token));

            return(new Tuple <List <IDHierarchy>, string, CancellationToken>(foundedObjects.OrderByDescending(d => d.TypeHierarchy).ToList(), text, token));
        }
        public override void ShowDialog(PropertyValue propertyValue, IInputElement commandSource)
        {
            ModelPropertyEntryToOwnerActivityConverter ownerActivityConverter = new ModelPropertyEntryToOwnerActivityConverter();
            ModelItem activityItem = ownerActivityConverter.Convert(propertyValue.ParentProperty, typeof(ModelItem), false, null) as ModelItem;
            var       av           = activityItem.GetCurrentValue() as SendBusinessObjectsReportToEmail;
            var       currReportUn = string.Empty;

            if (av != null && av.Report_id != null)
            {
                var literal = av.Report_id.Expression as Literal <string>;
                if (literal == null)
                {
                    return;
                }
                currReportUn = literal.Value;
            }

            var dialog = new ReportBusinessObjectsIdDialog(activityItem);

            var lv = dialog.lvReports;

            lv.ItemsSource = null;
            List <Info_Report_Stimul> reports = null;

            try
            {
                reports = ServiceFactory.ArmServiceInvokeSync <List <Info_Report_Stimul> >("REP_GetStimulReports");
            }
            catch (Exception ex)
            {
                Manager.UI.ShowMessage(ex.Message);
                return;
            }

            if (reports == null)
            {
                return;
            }

            lv.ItemsSource = reports;

            if (!string.IsNullOrEmpty(currReportUn))
            {
                var selectedReport = reports.FirstOrDefault(r => r.Report_UN == currReportUn);
                if (selectedReport != null)
                {
                    lv.SelectedItem = selectedReport;
                }
            }


            if (dialog.ShowOkCancel())
            {
                var selectedReport = lv.SelectedItem as Info_Report_Stimul;
                if (selectedReport == null)
                {
                    return;
                }

                if (Equals(selectedReport.Report_UN, currReportUn))
                {
                    return;
                }

                propertyValue.Value = new InArgument <string>(selectedReport.Report_UN);
                if (!string.IsNullOrEmpty(currReportUn) && av != null && !string.IsNullOrEmpty(av.Args))
                {
                    Manager.UI.ShowMessage("Изменилась бизнес модель. Объекты для построения отчета необходимо выбрать заново!");
                    av.Args = string.Empty;
                }
            }
        }
        public Task RunServerBuild(BackgroundWorker worker)
        {
            var parents = MonitoringAnalyseDict.Keys.ToList();

            try
            {
                //Запрос формирования данных
                ARM_Service_.Monit_GetArchive(_waiterId, parents, _selectedСhannels
                                              , DtStart, DtEnd, _maxValue, _selectedEvents, IsConcentratorsEnabled, _filterFlag);
                //Ждем формирования первых пакетов
                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                Manager.UI.ShowMessage(ex.Message);
                return(null);
            }


            //if (_showTotalStatistic != null)
            //{
            //    _showTotalStatistic(request.StatisticInformation);
            //}

            _isRequestCompleted = false;
            //double packetSize = request.ProgressPercent;

            //if (request.Result != null && request.Result.Count > 0)
            //{
            //    _stackForBuildResult.PushRange(request.Result.ToArray());
            //    _progressBar.IncValue(packetSize);
            //}

            //Отмена выполнения
            if (worker.CancellationPending || _cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            //Запускаем построитель результатов
            var builderTask = Task.Factory.StartNew(BuildPacketResult, _cancellationToken);

            //Получение следующих пакетов
            bool isLastPacket = false;
            int  voidCounter  = 0;
            int  errCounter   = 0;
            bool isFirst      = true;
            TStatisticInformation statisticInformation = null;

            int requestNumber = 0;

            do
            {
                try
                {
                    if (_cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }

                    var packet = ServiceFactory.ArmServiceInvokeSync <Tuple <bool, MemoryStream, string, TStatisticInformation, TMonitoringAnalyseResult> >("Monit_WaitArchives", requestNumber, _waiterId);
                    if (packet != null)
                    {
                        if (!string.IsNullOrEmpty(packet.Item3))
                        {
                            Manager.UI.ShowMessage(packet.Item3);
                        }

                        isLastPacket = packet.Item1;
                        if (isLastPacket)
                        {
                            statisticInformation = packet.Item4;
                            break;
                        }

                        if (packet.Item2 != null)
                        {
                            requestNumber++;
                            //var nextPart = packet.Item2.DecompressAndDeserialize<List<TMonitoringAnalyseResult>>();
                            var decomoressed = CompressUtility.DecompressGZip(packet.Item2);
                            decomoressed.Position = 0;
                            var nextPart = Serializer.Deserialize <List <TMonitoringAnalyseResult> >(decomoressed);
                            if (nextPart != null && nextPart.Count > 0)
                            {
                                _stackForBuildResult.PushRange(nextPart.ToArray());
                                voidCounter = 0;
                                _mres.Set();
                                if (isFirst)
                                {
                                    _progressBar.SetIndeterminat(false);
                                    isFirst = false;
                                }
                            }
                            else
                            {
                                Thread.Sleep(2000);
                            }
                        }
                        else
                        {
                            if (++voidCounter > 501)
                            {
                                isLastPacket = true;
                                Manager.UI.ShowMessage("MonitoringClientFactory: Превышен лимит ожидания пакетов");
                            }
                            else
                            {
                                Thread.Sleep(5000);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception();
                    }

                    errCounter = 0;
                }
                catch (Exception ex)
                {
                    if (++errCounter > 6)
                    {
                        isLastPacket = true;
                        Manager.UI.ShowMessage("MonitoringClientFactory: Превышен лимит пустых пакетов");
                        _progressBar.SetIndeterminat(false);
                    }
                    else
                    {
                        Manager.UI.ShowMessage(ex.Message);
                        Thread.Sleep(1000);
                    }
                }
                Thread.Sleep(200);
            } while (!isLastPacket);

            if (statisticInformation != null && _showTotalStatistic != null)
            {
                _showTotalStatistic(statisticInformation);
            }

            _isRequestCompleted = true;
            _mres.Set();
            return(builderTask);
        }