コード例 #1
0
        private static string GetHeaderfromColumn(ColumnBase cc, IMeasure measure)
        {
            string header;

            if (cc.Label != null)
            {
                header = cc.Label.ToString();

                var haveMeasure = cc.Label as IHaveMeasureUnit;
                if (haveMeasure != null)
                {
                    if (string.IsNullOrEmpty(haveMeasure.MeasureUnitUn))
                    {
                        if (measure != null && measure.MeasureUnitSelectedInfo != null)
                        {
                            var measureUnitUn = (haveMeasure.ChannelType % 10) > 2
                                ? measure.MeasureUnitSelectedInfo.ReactiveMeasureUnitUn
                                : measure.MeasureUnitSelectedInfo.ActiveMeasureUnitUn;

                            header += ", " + EnumClientServiceDictionary.GetMeasureUnitAbbreviation(measureUnitUn);
                        }
                    }
                }
            }
            else if (!string.IsNullOrEmpty(cc.HeaderText))
            {
                header = cc.HeaderText;
            }
            else
            {
                header = cc.Key;
            }

            return(header);
        }
コード例 #2
0
ファイル: XceedGridFinder.cs プロジェクト: Kobuntu/ProryvARM
        private static void ExpandParentAndSelectObjectXceedGrid(enumTypeHierarchy parentType, int parentId,
                                                                 IFreeHierarchyObject hierarchyObject, DataGridControl xamTree)
        {
            IFreeHierarchyObject parent = null;

            switch (parentType)
            {
            case enumTypeHierarchy.Dict_PS:
            case enumTypeHierarchy.USPD:
            case enumTypeHierarchy.E422:
                parent = EnumClientServiceDictionary.DetailPSList[parentId];
                break;

            case enumTypeHierarchy.Info_TP:
                var tps = EnumClientServiceDictionary.GetTps();
                if (tps != null)
                {
                    parent = tps[parentId];
                }
                break;
            }

            if (parent == null)
            {
                return;
            }

            var chain = new Stack();

#if DEBUG
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
#endif
            var source = xamTree.ItemsSource as ICollection;
            if (source == null)
            {
                return;
            }

            FinderHelper.FindFirstElement(source, parent, chain);
#if DEBUG
            sw.Stop();
            Console.WriteLine("Поиск {0} млс", sw.ElapsedMilliseconds);
#endif
            if (chain.Count <= 0)
            {
                return;
            }

            var arr = new object[chain.Count];
            chain.CopyTo(arr, 0);
            //Array.Reverse(arr);

            chain = new Stack(arr);

            xamTree.ExpandandSelectXceedGrid(chain, hierarchyObject);
        }
コード例 #3
0
ファイル: IgXamGrid.cs プロジェクト: Kobuntu/ProryvARM
        void OnLabelExporting(object sender, HeaderLabelExportingEventArgs e)
        {
            //Proryv check is null
            if (e.Label == null)
            {
                if (e.FieldGroup != null)
                {
                    return;
                }
                else
                {
                    e.Cancel = true;
                    return;
                }
            }

            var lts = e.Label.ToString();

            var haveMeasure = e.Label as IHaveMeasureUnit;

            if (haveMeasure != null)
            {
                if (string.IsNullOrEmpty(haveMeasure.MeasureUnitUn))
                {
                    var exporter = sender as ProryvDataPresenterExcelExporter;
                    var measured = exporter != null ? exporter.Measured : null;

                    if (measured != null && measured.MeasureUnitSelectedInfo != null)
                    {
                        var measureUnitUn = (haveMeasure.ChannelType % 10) > 2
                            ? measured.MeasureUnitSelectedInfo.ReactiveMeasureUnitUn
                            : measured.MeasureUnitSelectedInfo.ActiveMeasureUnitUn;

                        lts += ", " + EnumClientServiceDictionary.GetMeasureUnitAbbreviation(measureUnitUn);
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(lts))
            {
                e.Cancel = true;
                return;
            }

            e.Label = lts;
        }
コード例 #4
0
        public static DataTableEx ExecuteValidateValue(FormulasResult formulasResult, ArchivesValidate_List archivesList,
                                                       ArchivesTPValueAllChannels archivesTpList, IVisualDataRequestObjectsNames getNameInterface, List <DateTime> dts)
        {
            if ((archivesList == null || archivesList.Result_Values == null) &&
                (formulasResult == null || formulasResult.Result_Values == null) &&
                (archivesTpList == null || archivesTpList.Result_Values == null))
            {
                return(null);
            }

            int                  countColumn;
            DateTime             dtStart, dtEnd;
            enumTimeDiscreteType discreteType;

            if (archivesList != null && archivesList.Result_Values != null && archivesList.Result_Values.Count > 0)
            {
                dtStart      = archivesList.DTStart;
                dtEnd        = archivesList.DTEnd;
                countColumn  = archivesList.NumbersValues;
                discreteType = archivesList.DiscreteType;
            }
            else if (formulasResult != null && formulasResult.Result_Values != null && formulasResult.Result_Values.Count > 0 &&
                     formulasResult.Result_Values[0].Result_Values != null &&
                     formulasResult.Result_Values[0].Result_Values.Count > 0)
            {
                dtStart      = formulasResult.DTStart;
                dtEnd        = formulasResult.DTEnd;
                countColumn  = formulasResult.NumbersValues;
                discreteType = formulasResult.DiscreteType;
            }
            else if (archivesTpList != null && archivesTpList.Result_Values != null)
            {
                dtStart      = archivesTpList.DTStart;
                dtEnd        = archivesTpList.DTEnd;
                countColumn  = archivesTpList.NumbersValues;
                discreteType = archivesTpList.DiscreteType;
            }
            else
            {
                return(null);
            }

            string labelFormat;

            if (discreteType == enumTimeDiscreteType.DBHours || discreteType == enumTimeDiscreteType.DBHalfHours)
            {
                labelFormat = "dd.MM.yy\nHH:mm";
            }
            else
            {
                labelFormat = "dd.MM.yy";
            }

            var userTable = new DataTableEx()
            {
                FieldForSearch = "NameTI",
            };

            userTable.BeginLoadData();

            try
            {
                #region -------------Таблица для представления данных----------------------------

                userTable.Columns.Add("NameTI", typeof(IFreeHierarchyObject));
                userTable.Columns.Add("Channel", typeof(object));
                userTable.Columns.Add("Parent", typeof(IFreeHierarchyObject));
                userTable.Columns.Add("DataSource", typeof(string));

                var fType = typeof(VALUES_FLAG_DB);

                userTable.Columns.Add(new DataColumn("TotalFlag", fType)
                {
                    Caption = "Итого",
                });

                var i = 0;
                foreach (var dt in dts)
                {
                    userTable.Columns.Add(new DataColumn("Valid" + i, fType)
                    {
                        Caption = dt.ToString(labelFormat),
                    });
                    i++;
                }

                #endregion

                #region ------------Перебираем ТИ в архиве---------------------------------------

                if (archivesList != null && archivesList.Result_Values != null)
                {
                    userTable.Description = new DataTableDescription
                    {
                        DtStart      = archivesList.DTStart,
                        DiscreteType = archivesList.DiscreteType,
                        TimeZoneId   = archivesList.TimeZoneId,
                    };

                    //сортировка
                    foreach (var pair in archivesList.Result_Values
                             .Select(v => new Tuple <TPSHierarchy, TArchivesValidate, TInfo_TI>(
                                         EnumClientServiceDictionary.DetailPSList[v.TI_Validate.PS_ID], v,
                                         v.TI_Validate.TI_Ch_ID.IsCA
                                    ? EnumClientServiceDictionary.TICAList[v.TI_Validate.TI_Ch_ID.TI_ID]
                                    : EnumClientServiceDictionary.TIHierarchyList[v.TI_Validate.TI_Ch_ID.TI_ID]))
                             .Where(v => v.Item1 != null && v.Item3 != null && v.Item2.TI_Validate != null)
                             .OrderBy(v => v.Item2.TI_Validate.TI_Ch_ID.IsCA)
                             .ThenBy(v => v.Item1.Name)
                             .ThenBy(v => v.Item2.TI_Validate.PS_ID)
                             .ThenBy(v => v.Item3.Name)
                             .ThenBy(v => v.Item2.TI_Validate.TI_Ch_ID.TI_ID)
                             .ThenBy(v => v.Item2.TI_Validate.TI_Ch_ID.ChannelType % 10)
                             .ThenBy(v => v.Item2.TI_Validate.TI_Ch_ID.ChannelType))
                    {
                        var archiveValidateValue = pair.Item2;
                        var validate             = archiveValidateValue.TI_Validate;
                        //--------колонки в промежуточную таблицу-----------
                        var row = userTable.NewRow() as DataRowEx;
                        if (validate != null)
                        {
                            row["NameTI"]  = pair.Item3;
                            row["Channel"] = new TTariffPeriodID
                            {
                                ChannelType    = validate.TI_Ch_ID.ChannelType,
                                IsOV           = false,
                                TI_ID          = validate.TI_Ch_ID.TI_ID,
                                StartDateTime  = dtStart,
                                FinishDateTime = dtEnd,
                            };
                            row["Parent"]     = pair.Item1;
                            row["DataSource"] = EnumClientServiceDictionary
                                                .DataSourceTypeList
                                                .FirstOrDefault(v =>
                                                                EqualityComparer <EnumDataSourceType?> .Default.Equals(validate.TI_Ch_ID.DataSourceType,
                                                                                                                       v.Key))
                                                .Value;

                            var id = new ID_Hierarchy
                            {
                                ID            = validate.TI_Ch_ID.TI_ID.ToString(),
                                TypeHierarchy =
                                    validate.TI_Ch_ID.IsCA ? enumTypeHierarchy.Info_ContrTI : enumTypeHierarchy.Info_TI
                            };

                            row["TotalFlag"] = validate.Total_Flag;

                            if (validate.F_FLAG_List != null)
                            {
                                for (var j = 0; j < countColumn; j++)
                                {
                                    var flag = validate.F_FLAG_List.ElementAtOrDefault(j);
                                    row.SetValue("Valid" + j, j, validate.TI_Ch_ID.ChannelType, id, validate.TI_Ch_ID.DataSourceType, null, flag);
                                }
                            }
                        }

                        userTable.Rows.Add(row);
                        validate = archiveValidateValue.ContrTI_Validate;
                        if (validate != null)
                        {
                            row           = userTable.NewRow() as DataRowEx;
                            row["NameTI"] = "ТИ КА -" + getNameInterface.GetHierarchyDbTreeObject(
                                validate.TI_Ch_ID.TI_ID.ToString(),
                                validate.TI_Ch_ID.IsCA
                                                        ? enumTypeHierarchy.Info_ContrTI
                                                        : enumTypeHierarchy.Info_TI);
                            row["Parent"]  = EnumClientServiceDictionary.DetailContrPSList[validate.PS_ID];
                            row["Channel"] = validate.TI_Ch_ID.ChannelType;
                            if (validate.F_FLAG_List != null)
                            {
                                for (var j = 0; j < countColumn; j++)
                                {
                                    var flag = validate.F_FLAG_List.ElementAtOrDefault(j);
                                    row["Valid" + j] = flag;
                                }
                            }

                            row["TotalFlag"] = validate.Total_Flag;
                            userTable.Rows.Add(row);
                        }
                    }
                }

                #endregion

                #region ------------Перебираем формулы---------------------------------------------

                var tps = EnumClientServiceDictionary.GetTps();
                if (tps == null)
                {
                    return(userTable);
                }

                if (formulasResult != null && formulasResult.Result_Values != null)
                {
                    if (userTable.Description == null)
                    {
                        userTable.Description = new DataTableDescription
                        {
                            DtStart      = formulasResult.DTStart,
                            DiscreteType = formulasResult.DiscreteType,
                            TimeZoneId   = formulasResult.TimeZoneId,
                        };
                    }

                    foreach (var pair in formulasResult.Result_Values
                             .Where(fr => fr.Result_Values != null && fr.Result_Values.Count > 0)
                             .Select(fr =>

                                     new Tuple <IFreeHierarchyObject, IFormulaInfo, TFormulaResultsList>(fr.TP_CH_ID != null
                                        ? (IFreeHierarchyObject)tps[fr.TP_CH_ID.TP_ID]
                                        : EnumClientServiceDictionary.DetailPSList[fr.PS_ID],
                                                                                                         fr.GetFormulaInfo(getNameInterface),
                                                                                                         fr))
                             .OrderBy(p => p.Item1 == null ? "Формулы" : p.Item1.Name)
                             .ThenBy(p => p.Item2 == null ? string.Empty : p.Item2.FormulaName))
                    {
                        var formula = pair.Item3;

                        var formulaResult = formula.Result_Values[0];
                        var row           = userTable.NewRow() as DataRowEx;
                        row["NameTI"]  = pair.Item2;
                        row["Channel"] = null;
                        row["Parent"]  = pair.Item1;

                        var totalFlag = VALUES_FLAG_DB.None;

                        enumTypeHierarchy typeHierarchy;
                        switch (pair.Item2.FormulasTable)
                        {
                        case enumFormulasTable.Info_Formula_Description:
                            typeHierarchy = enumTypeHierarchy.Formula;
                            break;

                        case enumFormulasTable.Info_TP2_OurSide_Formula_Description:
                            typeHierarchy = enumTypeHierarchy.Formula_TP_OurSide;
                            break;

                        case enumFormulasTable.Info_TP2_Contr_Formula_Description:
                            typeHierarchy = enumTypeHierarchy.Formula_TP_CA;
                            break;

                        default:
                            typeHierarchy = enumTypeHierarchy.Unknown;
                            break;
                        }

                        var id = new ID_Hierarchy
                        {
                            ID            = formulaResult.FormulaId,
                            TypeHierarchy = typeHierarchy,
                        };

                        if (formulaResult.Val_List != null && formulaResult.Val_List.Count > 0)
                        {
                            for (int j = 0; j < countColumn; j++)
                            {
                                var v = formulaResult.Val_List.ElementAt(j);
                                if (v != null)
                                {
                                    var flag = v.F_FLAG;
                                    row.SetValue("Valid" + j, j, 0, id, null, null, flag);
                                    totalFlag = totalFlag.CompareAndReturnMostBadStatus(flag);
                                }

                                //row.SetIndex(description, j);
                            }
                        }
                        row["TotalFlag"] = totalFlag.AccomulateTotalStatistic();
                        userTable.Rows.Add(row);
                    }
                }

                #endregion

                #region ------------Перебираем ТП в архиве---------------------------------------

                if (archivesTpList == null || archivesTpList.Result_Values == null)
                {
                    return(userTable);
                }

                var sections = EnumClientServiceDictionary.GetSections();
                if (sections == null)
                {
                    return(userTable);
                }

                if (userTable.Description == null)
                {
                    userTable.Description = new DataTableDescription
                    {
                        DtStart      = archivesTpList.DTStart,
                        DiscreteType = archivesTpList.DiscreteType,
                        TimeZoneId   = archivesTpList.TimeZoneId,
                    };
                }

                foreach (var pair in archivesTpList.Result_Values
                         .Select(a =>
                {
                    TPoint tp;
                    tps.TryGetValue(a.Key, out tp);

                    TSection section;
                    sections.TryGetValue(tp.Section_ID, out section);

                    return(new Tuple <TSection, TPoint, List <TArchivesTPValueAllChannels> >(section, tp, a.Value));
                })
                         .Where(p => p.Item1 != null && p.Item2 != null && p.Item3 != null)
                         .OrderBy(p => p.Item1.SectionName)
                         .ThenBy(p => p.Item2.StringName))
                {
                    foreach (var tpArchive in pair.Item3)
                    {
                        if (tpArchive.Val_List == null)
                        {
                            continue;
                        }

                        Dictionary <byte, List <TPointValue> > tpVals;
                        if (!tpArchive.Val_List.TryGetValue(tpArchive.IsMoneyOurSide, out tpVals) || tpVals == null ||
                            tpVals.Count <= 0)
                        {
                            continue;
                        }

                        foreach (var valueByChannel in tpVals)
                        {
                            var row = userTable.NewRow() as DataRowEx;
                            row["NameTI"]  = pair.Item2;
                            row["Channel"] = valueByChannel.Key;
                            row["Parent"]  = pair.Item1;
                            var totalFlag = VALUES_FLAG_DB.None;

                            var id = new ID_Hierarchy
                            {
                                ID            = pair.Item2.TP_ID.ToString(),
                                TypeHierarchy = enumTypeHierarchy.Info_TP,
                            };

                            if (valueByChannel.Value != null && valueByChannel.Value.Count > 0)
                            {
                                for (var j = 0; j < countColumn; j++)
                                {
                                    var v = valueByChannel.Value.ElementAtOrDefault(j);
                                    if (v != null)
                                    {
                                        var flag = v.F_FLAG;
                                        row.SetValue("Valid" + j, j, valueByChannel.Key, id, null, null, flag);
                                        totalFlag = totalFlag.CompareAndReturnMostBadStatus(flag);

                                        //row.SetIndex(description, j);
                                    }
                                }
                            }

                            row["TotalFlag"] = totalFlag.AccomulateTotalStatistic();
                            userTable.Rows.Add(row);
                        }
                    }
                }

                #endregion
            }
            finally
            {
                userTable.EndLoadData();
                userTable.AcceptChanges();
            }

            return(userTable);
        }
コード例 #5
0
        public IFreeHierarchyObject UpdateSource(List <Info_Balance_FreeHierarchy_Description> descriptions, Dispatcher dispatcher,
                                                 Action onFieldChanged, out bool isAdded)
        {
            isAdded = false;

            //List<Info_Balance_FreeHierarchy_Description> descriptions = null;

            if (_balance != null && descriptions == null)
            {
                descriptions = ARM_Service.BL_GetFreeHierarchyBalanceDescritions(_balance.BalanceFreeHierarchy_UN);
            }

            var sections = ARM_Service.BL_GetFreeHierarchyBalanceSections(BalanceFreeHierarchyTypeID);

            if (sections == null || sections.Count == 0)
            {
                Manager.UI.ShowMessage("Не описаны разделы для данного типа баланса!");
                return(null);
            }

            var source = new List <BalanceFreeHierarchySectionRow>();
            var isExistsDescription = descriptions != null && descriptions.Count > 0;
            var tps        = EnumClientServiceDictionary.GetTps();
            var isFirst    = true;
            var isFirstRow = true;

            IFreeHierarchyObject result = null;

            foreach (var section in sections.Where(s => s.UseInTotalResult))
            {
                var row = new BalanceFreeHierarchySectionRow(section, dispatcher);
                if (isFirst)
                {
                    row.IsSelected = true;
                    isFirst        = false;
                }

                if (isExistsDescription)
                {
                    //Если есть описание данного баланса
                    foreach (var description in descriptions.Where(d => string.Equals(d.BalanceFreeHierarchySection_UN, section.BalanceFreeHierarchySection_UN)).OrderBy(d => d.SortNumber))
                    {
                        var isIntegral = false;
                        IFreeHierarchyObject hierarchyObject = null;
                        if (description.TI_ID.HasValue)
                        {
                            TInfo_TI ti;
                            if (!EnumClientServiceDictionary.TIHierarchyList.TryGetValue(description.TI_ID.Value, out ti) || ti == null)
                            {
                                continue;
                            }
                            hierarchyObject = ti;
                        }
                        if (description.IntegralTI_ID.HasValue)
                        {
                            isIntegral = true;
                            TInfo_TI ti;
                            if (!EnumClientServiceDictionary.TIHierarchyList.TryGetValue(description.IntegralTI_ID.Value, out ti) || ti == null)
                            {
                                continue;
                            }
                            hierarchyObject = ti;
                        }
                        else if (description.TP_ID.HasValue && tps != null)
                        {
                            TPoint tp;
                            if (!tps.TryGetValue(description.TP_ID.Value, out tp) || tp == null)
                            {
                                continue;
                            }
                            hierarchyObject = tp;
                        }
                        else if (!string.IsNullOrEmpty(description.Formula_UN) && EnumClientServiceDictionary.FormulasList != null)
                        {
                            var formula = EnumClientServiceDictionary.FormulasList[description.Formula_UN];
                            hierarchyObject = formula;
                        }
                        else if (!string.IsNullOrEmpty(description.OurFormula_UN))
                        {
                            TFormulaForSection formula;
                            if (!EnumClientServiceDictionary.FormulaFsk.TryGetValue(description.OurFormula_UN, out formula) || formula == null)
                            {
                                continue;
                            }
                            hierarchyObject = formula;
                        }
                        else if (!string.IsNullOrEmpty(description.ContrFormula_UN))
                        {
                            TFormulaForSection formula;
                            if (!EnumClientServiceDictionary.FormulaCA.TryGetValue(description.ContrFormula_UN, out formula) || formula == null)
                            {
                                continue;
                            }
                            hierarchyObject = formula;
                        }
                        else if (description.PTransformator_ID.HasValue)
                        {
                            var transformator = EnumClientServiceDictionary.GetOrAddTransformator(description.PTransformator_ID.Value, null);
                            hierarchyObject = transformator;
                        }
                        else if (description.PReactor_ID.HasValue)
                        {
                            var reactor = EnumClientServiceDictionary.GetOrAddReactor(description.PReactor_ID.Value, null);
                            hierarchyObject = reactor;
                        }
                        else if (description.Section_ID.HasValue)
                        {
                            var      hierarhicalSections = EnumClientServiceDictionary.GetSections();
                            TSection hierarhicalSection;
                            if (hierarhicalSections != null && hierarhicalSections.TryGetValue(description.Section_ID.Value, out hierarhicalSection))
                            {
                                hierarchyObject = hierarhicalSection;
                            }
                        }
                        else if (!string.IsNullOrEmpty(description.FormulaConstant_UN))
                        {
                            var formulaConstant = EnumClientServiceDictionary.FormulaConstantDictionary[description.FormulaConstant_UN];
                            hierarchyObject = formulaConstant;
                        }

                        if (hierarchyObject == null)
                        {
                            continue;
                        }

                        var itemRows = FindDescriptions(description, row, dispatcher);
                        if (itemRows != null)
                        {
                            itemRows.Add(new BalanceFreeHierarchyItemRow(hierarchyObject, description.ChannelType, description.Coef ?? 1, onFieldChanged,
                                                                         description.SortNumber, itemRows, isIntegral, (EnumDataSourceType?)description.DataSource_ID));
                        }

                        //Раскрываем дерево на первом объекте баланса
                        if (isFirstRow)
                        {
                            //fhTree.Dispatcher.BeginInvoke((Action)(() =>
                            //{
                            //    var freeHierTreeId = FormulaEditor_Frame.FindTreeByObjectType(hierarchyObject);
                            //    fhTree.ReloadTree(freeHierTreeId, hierarchyObject: hierarchyObject);
                            //}), DispatcherPriority.Background);

                            result = hierarchyObject;

                            isAdded    = true;
                            isFirstRow = false;
                        }
                    }
                }

                source.Add(row);
            }

            dispatcher.BeginInvoke((Action)(() => Source.AddRange(source)));

            //if (!isAdded)
            //{
            //    Task.Factory.StartNew(() =>
            //    {
            //        Thread.Sleep(100);
            //        //Раскрываем дерево на родителе баланса
            //        fhTree.Dispatcher.BeginInvoke((Action)(() =>
            //           fhTree.ExpandAndSelect(_hierarchyObject, true)), DispatcherPriority.ContextIdle);
            //    });
            //}

            return(result);
        }
コード例 #6
0
        /// <summary>
        /// Добавляем колонки по ТП
        /// </summary>
        /// <param name="k"></param>
        /// <param name="archivesTpList"></param>
        /// /// <param name="ListTiViewModel"></param>
        /// <returns></returns>
        public Dictionary <string, DetailFieldInfo> AddColumnsTp(ref int k, ArchivesTPValueAllChannels archivesTpList,
                                                                 List <TRowObjectForGrid> listTiViewModel = null)
        {
            var result = new Dictionary <string, DetailFieldInfo>();

            if (archivesTpList == null || archivesTpList.Result_Values == null)
            {
                return(result);
            }

            var vType = typeof(IFValue);
            var tps   = EnumClientServiceDictionary.GetTps();

            if (tps == null)
            {
                return(result);
            }

            foreach (var archivesTpValueAllChannelse in archivesTpList.Result_Values.Select(a =>
            {
                TPoint tp;
                tps.TryGetValue(a.Key, out tp);
                return(new Tuple <TPoint, List <TArchivesTPValueAllChannels> >(tp, a.Value));
            }).Where(a => a != null).OrderBy(a => a.Item1.StringName))
            {
                var id = new ID_Hierarchy
                {
                    ID            = archivesTpValueAllChannelse.Item1.TP_ID.ToString(),
                    TypeHierarchy = enumTypeHierarchy.Info_TP
                };

                foreach (var tpValue in archivesTpValueAllChannelse.Item2)
                {
                    if (tpValue.Val_List == null)
                    {
                        continue;
                    }

                    var tp = archivesTpValueAllChannelse.Item1;

                    Dictionary <byte, List <TPointValue> > pointsByChannel;
                    if (!tpValue.Val_List.TryGetValue(tpValue.IsMoneyOurSide, out pointsByChannel) || pointsByChannel == null || pointsByChannel.Count == 0)
                    {
                        continue;
                    }

                    foreach (var channel in archivesTpList.ChannelType_List.OrderBy(c => c))
                    {
                        List <TPointValue> tpVals;
                        if (!pointsByChannel.TryGetValue(channel, out tpVals) || tpVals == null)
                        {
                            continue;
                        }

                        var columnName = "F_VALUE" + k;

                        var col = new DataColumn(columnName, vType)
                        {
                            //Caption = "ТП - " + tp.StringName + " " +
                            //          getNameInterface.GetChanelTypeNameByID(channel, false),
                            ReadOnly = true,
                        };

                        Columns.Add(col);
                        k++;

                        result[columnName] = new DetailFieldInfo
                        {
                            ColumnName       = columnName,
                            Id               = id,
                            DataSource       = null,
                            MeasureUnitUn    = null,
                            Values           = tpVals.Select((s, i) => new { s, i }).ToDictionary(v => v.i, v => v.s as IFValue),
                            ChannelType      = channel,
                            UseMeasureModule = true,
                        };
                    }

                    //tpArchives.Add(new );
                }
            }

            return(result);
        }
コード例 #7
0
        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);
        }
コード例 #8
0
        private static ConcurrentDictionary <int, FreeHierarchyTreeItem> GenerateStandartTreeSections(FreeHierarchyTreeDescriptor descriptor)
        {
            var result = new ConcurrentDictionary <int, FreeHierarchyTreeItem>();
            var items  = new List <FreeHierarchyTreeItem>();

            HashSet <ID_TypeHierarchy> objectsHasRightDbSee = null;
            var hiers1 = EnumClientServiceDictionary.HierLev1List.Values;

            if (Manager.User != null && !Manager.User.IsAdmin)
            {
                try
                {
                    //Запрашиваем права на список объектов
                    objectsHasRightDbSee = Manager.User.UserHasRightDbSee(hiers1.Select(h1 => new ID_TypeHierarchy
                    {
                        ID            = h1.Id,
                        TypeHierarchy = enumTypeHierarchy.Dict_HierLev1,
                    }).ToList());
                }
                catch (Exception ex)
                {
                    Manager.UI.ShowMessage("Ошибка запроса прав: " + ex.Message);
                }
            }

            foreach (var item in hiers1.OrderBy(v => v.Item))
            {
                //Глобальный фильтр
                if (!IsGlobalFilterHaveItem(item))
                {
                    continue;
                }

                var minID = descriptor.GetMinIdAndDecrement();
                UserRightsForTreeObject hier1Right;
                var isExistsRight = Manager.User.AccumulateRightsAndVerify(item, EnumObjectRightType.SeeDbObjects, null, out hier1Right);
                if (!isExistsRight && Manager.User != null && !Manager.User.IsAdmin && objectsHasRightDbSee != null)
                {
                    //Проверяем через дочерних объектов
                    isExistsRight = objectsHasRightDbSee.Any(o => o.ID == item.Id && o.TypeHierarchy == item.GetTypeHierarchy());
                }

                var newItem = new FreeHierarchyTreeItem(descriptor, item, nodeName: item.Name)
                {
                    FreeHierItem_ID       = minID,
                    IncludeObjectChildren = true,
                    FreeHierItemType      = EnumFreeHierarchyItemType.HierLev1,
                    NodeRights            = hier1Right
                };

                newItem.Descriptor.Tree = result;
                bool isExistsChildSeeDbObjects = false;
                if (newItem.IncludeObjectChildren)
                {
                    isExistsChildSeeDbObjects = newItem.LoadStaticChildren(isExistsRight, isLoadStatic: true);
                }

                isExistsChildSeeDbObjects = newItem.IncludeChildrenSection(item.Id, item.Type, newItem.Children) || isExistsChildSeeDbObjects ||
                                            item.TIStatus.HasFlag(EnumTIStatus.Is_Section_Enabled);

                //У объекта нет прав на просмотр, или нет дочерних объектов на которые есть такие права
                if (isExistsChildSeeDbObjects) //Включаем только если есть сечения
                {
                    items.Add(newItem);
                }
                else
                {
                    newItem.Dispose();
                }
            }

            //Сечения которые не привязаны ни к чему
            foreach (var section in EnumClientServiceDictionary.GetSections().Values.Where(s => s.ParentId <= 0 && s.Section_ID > 0).OrderBy(s => s.Item))
            {
                UserRightsForTreeObject right;
                if (!Manager.User.AccumulateRightsAndVerify(section, EnumObjectRightType.SeeDbObjects, null, out right))
                {
                    continue;
                }

                var minID = descriptor.GetMinIdAndDecrement();
                FreeHierarchyTreeItem newItem = new FreeHierarchyTreeItem(descriptor, section)
                {
                    FreeHierItem_ID       = minID,
                    IncludeObjectChildren = true,
                    NodeRights            = right,
                    FreeHierItemType      = EnumFreeHierarchyItemType.Section,
                };

                newItem.Descriptor.Tree = result;
                newItem.LoadStaticChildren(true);

                items.Add(newItem);
            }

            if (FreeHierarchyTreeDescriptor.Sort != null)
            {
                FreeHierarchyTreeDescriptor.Sort(items);
            }
            foreach (var i in items)
            {
                result[i.FreeHierItem_ID] = i;
            }
            return(result);
        }
コード例 #9
0
        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));
        }
コード例 #10
0
ファイル: DetailFieldInfo.cs プロジェクト: Kobuntu/ProryvARM
        public override string ToString()
        {
            if (!string.IsNullOrEmpty(_stringName))
            {
                return(_stringName);
            }

            var name = new StringBuilder();

            if (ReplacedId != null)
            {
                //Это колонка с идентификаторами замещаемой ТИ
                //return string.Empty;
                var freeHierarchyObject =
                    HierarchyObjectHelper.ToHierarchyObject(ReplacedId.ID, ReplacedId.TypeHierarchy);
                if (freeHierarchyObject != null)
                {
                    name.Append(freeHierarchyObject.Name).Append(" замещаемая ТИ ");
                }
            }

            if (ChannelType > 0)
            {
                string channelName;
                if (ChannelFactory.ChanelTypeNameFSK.TryGetValue(ChannelType, out channelName) &&
                    !string.IsNullOrEmpty(channelName))
                {
                    name.Append(channelName).Append(" ");
                }

                if (ChannelType > 10 && Id != null && Id.TypeHierarchy == enumTypeHierarchy.Info_TI)
                {
                    int tiId;
                    int.TryParse(Id.ID, out tiId);
                    name.Append(ChannelDictionaryClass.MakeZoneNamePrefix(tiId, ChannelType, DateTime.Now, DateTime.Now))
                    .Append(" ");
                }
            }

            if (Id != null)
            {
                var freeHierarchyObject =
                    HierarchyObjectHelper.ToHierarchyObject(Id.ID, Id.TypeHierarchy);
                if (freeHierarchyObject != null)
                {
                    name.Append(freeHierarchyObject.Name);
                }
            }

            var k = EnumClientServiceDictionary.DataSourceTypeList.FirstOrDefault(d => d.Key == DataSource);

            if (!string.IsNullOrEmpty(k.Value))
            {
                name.Append("\n").Append(k.Value);
            }

            if (!string.IsNullOrEmpty(MeasureUnitUn))
            {
                var measureName = EnumClientServiceDictionary.GetMeasureUnitAbbreviation(MeasureUnitUn);
                name.Append(" ").Append(measureName);
            }

            _stringName = name.ToString();

            return(_stringName);
        }