/// <summary>
        /// Читаем все итоги для баланса по подгруппам
        /// </summary>
        /// <param name="balanceFreeHierarchyUns">Идентификаторы балансов, для которых возвращаем итоги по своим подгруппам</param>
        /// <returns></returns>
        public static ConcurrentDictionary <string, Dictionary <string, List <Dict_Balance_FreeHierarchy_Footers> > > GetFreeHierarchyBalanceFootersByBalances(List <string> balanceFreeHierarchyUns)
        {
            if (balanceFreeHierarchyUns == null)
            {
                return(null);
            }

            var result = new ConcurrentDictionary <string, Dictionary <string, List <Dict_Balance_FreeHierarchy_Footers> > >();

            Parallel.ForEach(Partitioner.Create(0, balanceFreeHierarchyUns.Count, Settings.MaxStringRows)
                             , range =>
            {
                using (var db = new FSKDataContext(Settings.DbConnectionString)
                {
                    ObjectTrackingEnabled = false,
                    DeferredLoadingEnabled = false,
                    CommandTimeout = 60,
                })
                {
                    foreach (var footersByBalance in db.Dict_Balance_FreeHierarchy_Footers
                             .Where(f => balanceFreeHierarchyUns.Contains(f.BalanceFreeHierarchy_UN))
                             .ToList()
                             .GroupBy(f => f.BalanceFreeHierarchy_UN))                                                 //Группируем по балансам
                    {
                        result[footersByBalance.Key] = footersByBalance.GroupBy(f => f.BalanceFreeHierarchySection_UN) //Группируем по подгруппам
                                                       .ToDictionary(f => f.Key, vv => vv.OrderBy(f => f.SortNumber).ToList());
                    }
                }
            });

            return(result);
        }
Пример #2
0
        private static Dictionary <string, List <IFreeHierarchyBalanceSignature> > GetBalanceSignatures(List <string> balanceFreeHierarchyUNs, out string branchName)
        {
            var signatures = new Dictionary <string, List <IFreeHierarchyBalanceSignature> >();

            using (var db = new FSKDataContext(Settings.DbConnectionString)
            {
                ObjectTrackingEnabled = false,
                DeferredLoadingEnabled = false,
                CommandTimeout = 60,
            })
            {
                using (var txn = new TransactionScope(TransactionScopeOption.Required,
                                                      new TransactionOptions {
                    IsolationLevel = IsolationLevel.ReadUncommitted
                }))
                {
                    var ore = db.Dict_SubjOREs.FirstOrDefault();
                    branchName = ore != null ? ore.SubjOREName : string.Empty;

                    foreach (var range in Partitioner.Create(0, balanceFreeHierarchyUNs.Count, Settings.MaxStringRows).GetDynamicPartitions())
                    {
                        var uns = "(" + string.Join(",", balanceFreeHierarchyUNs.GetRange(range.Item1, range.Item2 - range.Item1).Select(un => "'" + un + "'")) + ")";

                        foreach (var signature in db.ExecuteQuery <FreeHierarchyBalanceSignatureInfo>
                                     ("select s.BalanceFreeHierarchySignature_UN as BalanceFreeHierarchySignatureUn,PostName, FIO,"
                                     + "s.BalanceFreeHierarchySignatureGroup_UN as BalanceFreeHierarchySignatureGroupUn,"
                                     + "g.SortNumber as GroupSortNumber, g.Name as GroupName, l.BalanceFreeHierarchy_UN as BalanceFreeHierarchyUn "
                                     + "from [dbo].[Info_Balance_FreeHierarchy_List] l "
                                     + "cross apply "
                                     + "("
                                     + "	select distinct BalanceFreeHierarchySignature_UN from "
                                     + "	[dbo].[Info_Balance_FreeHierarchy_SignaturesLinks] "
                                     + "	where (BalanceFreeHierarchy_UN is not null and BalanceFreeHierarchy_UN = l.BalanceFreeHierarchy_UN) "
                                     + "	or (BalanceFreeHierarchyObject_UN is not null and BalanceFreeHierarchyObject_UN = l.BalanceFreeHierarchyObject_UN) "
                                     + ") ss "
                                     + "join [dbo].[Info_Balance_FreeHierarchy_Signatures] s on s.BalanceFreeHierarchySignature_UN = ss.BalanceFreeHierarchySignature_UN "
                                     + "join [dbo].[Info_Balance_FreeHierarchy_SignaturesGroups] g on g.BalanceFreeHierarchySignatureGroup_UN = s.BalanceFreeHierarchySignatureGroup_UN "
                                     + "where l.BalanceFreeHierarchy_UN in " + uns
                                     + "order by g.SortNumber"))
                        {
                            List <IFreeHierarchyBalanceSignature> sl;
                            if (!signatures.TryGetValue(signature.BalanceFreeHierarchyUn, out sl))
                            {
                                sl = new List <IFreeHierarchyBalanceSignature>();
                                signatures[signature.BalanceFreeHierarchyUn] = sl;
                            }

                            sl.Add(signature);
                        }
                    }
                }
            }

            return(signatures);
        }
Пример #3
0
        /// <summary>
        /// Читаем заголовок баланса
        /// </summary>
        /// <param name="balanceFreeHierarchyUn">Идентификатор баланса</param>
        /// <returns></returns>
        public static Tuple <Guid, MemoryStream, bool> BL_GetBalanceHeader(string balanceFreeHierarchyUn)
        {
            if (string.IsNullOrEmpty(balanceFreeHierarchyUn))
            {
                throw new Exception("Неправильный идентификатор баланса");
            }

            var isUseAsTemplate = false;

            using (var db = new FSKDataContext(Settings.DbConnectionString)
            {
                CommandTimeout = 60,
            })
            {
                var bl = db.Info_Balance_FreeHierarchy_Lists.FirstOrDefault(b => Equals(balanceFreeHierarchyUn, b.BalanceFreeHierarchy_UN));
                if (bl == null)
                {
                    throw new Exception("Баланс не найден или удален");
                }

                var balanceFreeHierarchyHeaderUN = bl.BalanceFreeHierarchyHeader_UN;
                if (!balanceFreeHierarchyHeaderUN.HasValue)
                {
                    //Не наден индивидуальный заголовок для данного баланса, читаем обобщенный
                    var hbl = db.Info_Balance_FreeHierarchy_HeadersToBalanceTypes.FirstOrDefault(b => b.BalanceFreeHierarchyType_ID == bl.BalanceFreeHierarchyType_ID);
                    if (hbl == null)
                    {
                        return(null);            //throw new Exception("Не описан шаблона заголовка для данного типа баланса");
                    }
                    balanceFreeHierarchyHeaderUN = hbl.BalanceFreeHierarchyHeader_UN;
                    isUseAsTemplate = true;
                }

                var hl = db.Info_Balance_FreeHierarchy_Headers.FirstOrDefault(b => Equals(b.BalanceFreeHierarchyHeader_UN, balanceFreeHierarchyHeaderUN));
                if (hl == null)
                {
                    return(null);
                }

                return(new Tuple <Guid, MemoryStream, bool>(hl.BalanceFreeHierarchyHeader_UN, new MemoryStream(hl.FsData.ToArray()), isUseAsTemplate));
            }
        }
Пример #4
0
 public static List <Dict_Balance_FreeHierarchy_Section> GetFreeHierarchyBalanceSections(IEnumerable <byte> balanceFreeHierarchyTypes)
 {
     using (var db = new FSKDataContext(Settings.DbConnectionString)
     {
         ObjectTrackingEnabled = false,
         DeferredLoadingEnabled = false,
         CommandTimeout = 60,
     })
     {
         using (var txn = new TransactionScope(TransactionScopeOption.Required,
                                               new TransactionOptions {
             IsolationLevel = IsolationLevel.ReadUncommitted
         }))
         {
             return(db.Dict_Balance_FreeHierarchy_Sections
                    .Where(b => balanceFreeHierarchyTypes.Contains(b.BalanceFreeHierarchyType_ID))
                    .ToList());
         }
     }
 }
Пример #5
0
        /// <summary>
        /// Чтение параметров трансформатора
        /// </summary>
        /// <param name="transIds">Идентификаторы трансформаторов</param>
        /// <param name="tiForTransformatorsAndReactors">Идентифкаторы ТИ для запросов в архив</param>
        /// <param name="itemsResultByBalance">Параметры балансов</param>
        private void ReadTransformatorsParams(ConcurrentDictionary <int, string> transIds,
                                              ConcurrentStack <TI_ChanelType> tiForTransformatorsAndReactors,
                                              ConcurrentDictionary <string, BalanceFreeHierarchyCalculatedResult> itemsResultByBalance)
        {
            if (transIds.Count == 0)
            {
                return;
            }

            var transList = transIds.ToList();

            Parallel.ForEach(Partitioner.Create(0, transIds.Count, Settings.MaxStringRows)
                             , range =>
            {
                var localIds = transList.GetRange(range.Item1, range.Item2 - range.Item1);
                using (var db = new FSKDataContext(Settings.DbConnectionString)
                {
                    ObjectTrackingEnabled = false,
                    DeferredLoadingEnabled = false,
                    CommandTimeout = 180,
                })
                {
                    var sprocTransformator = db.usp2_Info_GetTransfomatorsPropertyForBalancePS(null, _dtServerStart,
                                                                                               _dtServerEnd, string.Join(",", localIds.Select(v => v.Key)));

                    //Берем время работы трансформаторов
                    var transformatorWorkRangeDict = sprocTransformator
                                                     .GetResult <DBPTransformatorWorkPeriod>()
                                                     .ToList()
                                                     .GroupBy(r => r.PTransformator_ID)
                                                     .ToDictionary(k => k.Key, v => v.ToList());

                    //Считываем характеристики трансформаторов
                    var tps = sprocTransformator.GetResult <DBPTransformatorProperty>()
                              .Select(tProp =>
                    {
                        BalanceFreeHierarchyCalculatedResult balanceResult;
                        string balanceFreeHierarchyUn;
                        if (!transIds.TryGetValue(tProp.PTransformator_ID, out balanceFreeHierarchyUn) ||
                            !itemsResultByBalance.TryGetValue(balanceFreeHierarchyUn, out balanceResult))
                        {
                            return(null);
                        }

                        var transformator = new TPTransformatorsResult(tProp, transformatorWorkRangeDict,
                                                                       _dtServerStart, _dtServerEnd, _numbersHalfHours);
                        balanceResult.Transformators.Add(transformator);

                        return(transformator);
                    }).ToArray();

                    //заполняем ТИ в трансформаторах
                    foreach (var tiGroupByTransformator in sprocTransformator
                             .GetResult <DBPTransformators_To_TI_List>()
                             .ToList()
                             .GroupBy(t => t.PTransformator_ID))
                    {
                        var tr = tps.FirstOrDefault(t =>
                                                    t != null && t.PTransformatorProperty.PTransformator_ID == tiGroupByTransformator.Key);
                        if (tr == null)
                        {
                            continue;
                        }

                        tr.PTransformators_To_TI_List.AddRange(tiGroupByTransformator);
                        for (byte channelType = 1; channelType < 5; channelType++)
                        {
                            var tiArray = tiGroupByTransformator.Select(t => new TI_ChanelType
                            {
                                TI_ID = t.TI_ID, ChannelType = channelType, IsCA = t.IsCA
                            }).ToArray();
                            if (tiArray.Length > 0)
                            {
                                tiForTransformatorsAndReactors.PushRange(tiArray);
                            }
                        }
                    }
                }
            });
        }
Пример #6
0
        /// <summary>
        /// Читаем параметры балансов
        /// </summary>
        /// <param name="transIds"></param>
        /// <param name="reactorsIds"></param>
        /// <param name="tis"></param>
        /// <param name="intgralTis"></param>
        /// <param name="tps"></param>
        /// <param name="formulas"></param>
        /// <param name="sections"></param>
        /// <param name="formulaConstantIds"></param>
        /// <returns></returns>
        private ConcurrentDictionary <string, BalanceFreeHierarchyCalculatedResult> ReadBalanceParams(
            List <string> balanceFreeHierarchyUN,
            ConcurrentDictionary <int, string> transIds, ConcurrentStack <int> reactorsIds,
            ConcurrentStack <TI_ChanelType> tis, ConcurrentStack <TI_ChanelType> intgralTis,
            ConcurrentStack <TP_ChanelType> tps, ConcurrentStack <TFormulaParam> formulas,
            ConcurrentStack <TSectionChannel> sections, ConcurrentStack <string> formulaConstantIds)
        {
            var resultByBalance = new ConcurrentDictionary <string, BalanceFreeHierarchyCalculatedResult>();
            var subsections     = new ConcurrentStack <Dict_Balance_FreeHierarchy_Subsection>();

            using (var db = new FSKDataContext(Settings.DbConnectionString)
            {
                ObjectTrackingEnabled = false,
                DeferredLoadingEnabled = false,
                CommandTimeout = 180,
            })
            {
                foreach (var range in Partitioner.Create(0, balanceFreeHierarchyUN.Count, Settings.MaxStringRows)
                         .GetDynamicPartitions())
                {
                    var balanceFreeHierarchyUNs = balanceFreeHierarchyUN.GetRange(range.Item1, range.Item2 - range.Item1);

                    var sprocBalanceParams = db.usp2_Info_GetBalanceFreeHierarchyParams(
                        string.Join(",", balanceFreeHierarchyUNs), _dtServerStart, _dtServerEnd, _isGenerateDoc);

                    var r = new Dictionary <string, BalanceFreeHierarchyCalculatedResult>();
                    foreach (var balanceParam in sprocBalanceParams.GetResult <Info_Balance_FreeHierarchy_List>()
                             .Select(bl => new BalanceFreeHierarchyCalculatedResult(bl)))
                    {
                        r.Add(balanceParam.BalanceFreeHierarchyUn, balanceParam);
                        resultByBalance.TryAdd(balanceParam.BalanceFreeHierarchyUn, balanceParam);
                    }

                    foreach (var bto in sprocBalanceParams.GetResult <BalanceFreeHierarchyToObject>())
                    {
                        BalanceFreeHierarchyCalculatedResult hierarchyCalculatedResult;
                        if (r.TryGetValue(bto.BalanceFreeHierarchy_UN, out hierarchyCalculatedResult))
                        {
                            hierarchyCalculatedResult.ObjectId = bto.ToIdTypeHierarchy();
                        }
                    }

                    if (_isGenerateDoc)
                    {
                        //Заголовки подгрупп балансов
                        var s = sprocBalanceParams.GetResult <Dict_Balance_FreeHierarchy_Subsection>().ToArray();
                        if (s.Length > 0)
                        {
                            subsections.PushRange(s);
                        }
                    }

                    foreach (var bp in sprocBalanceParams.GetResult <usp2_Info_GetBalanceFreeHierarchyParamsResult>())
                    {
                        BalanceFreeHierarchyCalculatedResult balanceResult;
                        if (!r.TryGetValue(bp.BalanceFreeHierarchy_UN, out balanceResult))
                        {
                            continue;
                        }

                        var itemParam = new BalanceFreeHierarchyItemParams
                        {
                            ChannelType = bp.ChannelType,
                            BalanceFreeHierarchySectionUn     = bp.BalanceFreeHierarchySection_UN,
                            BalanceFreeHierarchySubsectionUn  = bp.BalanceFreeHierarchySubsection_UN,
                            BalanceFreeHierarchySubsectionUn2 = bp.BalanceFreeHierarchySubsection2_UN,
                            BalanceFreeHierarchySubsectionUn3 = bp.BalanceFreeHierarchySubsection3_UN,
                            IsOtpuskShin = !string.IsNullOrEmpty(bp.MetaString2) &&
                                           bp.MetaString2.IndexOf("otpusk_shin", 0, StringComparison.Ordinal) >= 0,

                            IsInput = !string.IsNullOrEmpty(bp.MetaString1) &&
                                      bp.MetaString1.IndexOf("postupilo", 0, StringComparison.Ordinal) >= 0,

                            IsOutput = !string.IsNullOrEmpty(bp.MetaString1) &&
                                       bp.MetaString1.IndexOf("rashod", 0, StringComparison.Ordinal) >= 0,
                            Coef                  = bp.Coef,
                            SortNumber            = bp.SortNumber,
                            Name                  = bp.Name,
                            MeasuringComplexError = bp.MeasuringComplexError,
                            CoeffTransformation   = bp.CoeffTransformation,
                            CoeffLosses           = bp.CoeffLosses,
                            MeterSerialNumber     = bp.MeterSerialNumber,
                            Voltage               = bp.Voltage
                        };

                        List <BalanceFreeHierarchyItemParams> items;
                        if (!balanceResult.ItemsParamsBySection.TryGetValue(itemParam.BalanceFreeHierarchySectionUn,
                                                                            out items))
                        {
                            items = new List <BalanceFreeHierarchyItemParams>();
                            balanceResult.ItemsParamsBySection[itemParam.BalanceFreeHierarchySectionUn] = items;
                        }

                        items.Add(itemParam);

                        if (bp.TI_ID.HasValue)
                        {
                            tis.Push(new TI_ChanelType
                            {
                                TI_ID          = bp.TI_ID.Value,
                                ChannelType    = bp.ChannelType ?? 1,
                                DataSourceType = (EnumDataSourceType?)bp.DataSource_ID,
                                //ClosedPeriod_ID =  Пока по закрытым периодам не формируем
                            });
                            itemParam.Id            = bp.TI_ID.Value;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Info_TI;
                        }
                        else if (bp.IntegralTI_ID.HasValue)
                        {
                            intgralTis.Push(new TI_ChanelType
                            {
                                TI_ID          = bp.IntegralTI_ID.Value,
                                ChannelType    = bp.ChannelType ?? 1,
                                DataSourceType = (EnumDataSourceType?)bp.DataSource_ID,
                                //ClosedPeriod_ID =  Пока по закрытым периодам не формируем
                            });
                            itemParam.Id            = bp.IntegralTI_ID.Value;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Info_Integral;
                        }
                        else if (bp.TP_ID.HasValue)
                        {
                            tps.Push(new TP_ChanelType
                            {
                                TP_ID       = bp.TP_ID.Value,
                                ChannelType = bp.ChannelType ?? 1,
                                //Пока не работает
                                //DataSourceType = (EnumDataSourceType?)bp.DataSource_ID,
                            });
                            itemParam.Id            = bp.TP_ID.Value;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Info_TP;
                        }
                        else if (!string.IsNullOrEmpty(bp.Formula_UN))
                        {
                            formulas.Push(new TFormulaParam(bp.Formula_UN, enumFormulasTable.Info_Formula_Description,
                                                            null, null, _dtServerStart, null));
                            itemParam.Un            = bp.Formula_UN;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Formula;
                        }
                        else if (!string.IsNullOrEmpty(bp.OurFormula_UN))
                        {
                            formulas.Push(new TFormulaParam(bp.OurFormula_UN,
                                                            enumFormulasTable.Info_TP2_OurSide_Formula_Description, null, null, _dtServerStart,
                                                            null));
                            itemParam.Un            = bp.OurFormula_UN;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Formula_TP_OurSide;
                        }
                        else if (!string.IsNullOrEmpty(bp.ContrFormula_UN))
                        {
                            formulas.Push(new TFormulaParam(bp.ContrFormula_UN,
                                                            enumFormulasTable.Info_TP2_Contr_Formula_Description, null, null, _dtServerStart,
                                                            null));
                            itemParam.Un            = bp.ContrFormula_UN;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Formula_TP_CA;
                        }
                        else if (bp.PTransformator_ID.HasValue)
                        {
                            transIds.TryAdd(bp.PTransformator_ID.Value, bp.BalanceFreeHierarchy_UN);
                            itemParam.Id            = bp.PTransformator_ID.Value;
                            itemParam.TypeHierarchy = enumTypeHierarchy.PTransformator;
                        }
                        else if (bp.PReactor_ID.HasValue)
                        {
                            reactorsIds.Push(bp.PReactor_ID.Value);
                            itemParam.Id            = bp.PReactor_ID.Value;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Reactor;
                        }
                        else if (bp.Section_ID.HasValue)
                        {
                            sections.Push(new TSectionChannel
                            {
                                Section_ID  = bp.Section_ID.Value,
                                ChannelType = bp.ChannelType.GetValueOrDefault(),
                            });

                            itemParam.Id            = bp.Section_ID.Value;
                            itemParam.TypeHierarchy = enumTypeHierarchy.Section;
                        }
                        else if (!string.IsNullOrEmpty(bp.FormulaConstant_UN))
                        {
                            formulaConstantIds.Push(bp.FormulaConstant_UN);
                            itemParam.Un            = bp.FormulaConstant_UN;
                            itemParam.TypeHierarchy = enumTypeHierarchy.FormulaConstant;
                        }
                    }
                }
            }

            if (subsections.Count > 0)
            {
                SubsectionNames = subsections
                                  .GroupBy(s => s.BalanceFreeHierarchySubsection_UN)
                                  .ToDictionary(k => k.Key, v => v.First().BalanceFreeHierarchySubsectionName);
            }

            return(resultByBalance);
        }