private void MarkFlags(TVALUES_DB watts, ExtendedXlsFile xls, int col) { //есть ОВ if ((watts.F_FLAG & (VALUES_FLAG_DB.None | VALUES_FLAG_DB.IsOVReplaced)) == (VALUES_FLAG_DB.None | VALUES_FLAG_DB.IsOVReplaced)) { xls.SetCellFontColor(UsedRows, col, IsOVReplacedColor); xls.SetCellFontColor(UsedRows, col, IsOVReplacedColor); InternalData.FlagOVremark = true; } // нет данных if ((watts.F_FLAG & VALUES_FLAG_DB.DataNotFull) == VALUES_FLAG_DB.DataNotFull) { xls.SetCellBkColor(UsedRows, col, NoDataColor); InternalData.FlNoData = true; } // статус менялся вручную if (((watts.F_FLAG & VALUES_FLAG_DB.NotCorrect) == VALUES_FLAG_DB.NotCorrect) && ((watts.F_FLAG & VALUES_FLAG_DB.isManualStatusChanged) == VALUES_FLAG_DB.isManualStatusChanged)) { xls.SetCellBkColor(UsedRows, col, IsManualStatusChangeColor); InternalData.FlagManualStatusChange = true; } }
public void Calculate(TVALUES_DB v1, TVALUES_DB v2) { _val1.Add(v1); _val2.Add(v2); if (v1 != null) { _sumVal1 += v1.F_VALUE; //todo возможно нужно будет проверять достоверность } if (v2 != null) { _sumVal2 += v2.F_VALUE; } }
internal void Accamulate(double currValue, VALUES_FLAG_DB currFlag, enumClientFormulaTPType fFlag = enumClientFormulaTPType.None) { if (_isSumm) { _flagValues |= currFlag; //Накапливаем состояние _dValue += currValue; //Накапливаем сумму _fFlag |= fFlag; } else { _dValue = (_dValue * _stepOfReadHalfHours + currValue) / (_stepOfReadHalfHours + 1); } if (_stepOfReadHalfHours == _numbersHalfHoursInOurPeriod) //Если закрыли период дискретизации { if (_unitDigit.HasValue) { _dValue *= (double)_unitDigit.Value; } var fVal = new TVALUES_DB(_flagValues, _dValue, _fFlag); _result.Add(fVal); if (_intervalTimeList != null) { if (++_numbersOurDiscreteInOurPeriod >= _intervalTimeList.Count) { return; //Вышли за наш предел } _numbersHalfHoursInOurPeriod = _intervalTimeList[_numbersOurDiscreteInOurPeriod]; } #region -------------Обнуляем значения----------------------- _stepOfReadHalfHours = 0; _flagValues = VALUES_FLAG_DB.None; _fFlag = enumClientFormulaTPType.None; _dValue = 0; #endregion } else { _stepOfReadHalfHours++; //Наращиваем до нужного периода дискретизации } }
protected override bool Execute(CodeActivityContext context) { object obj_id = ObjectID.Get(context); if (obj_id == null) { Error.Set(context, "Не опреден идентификатор объекта"); return(false); } SummValues.Set(context, 0); Status.Set(context, (int)VALUES_FLAG_DB.DataNotFull); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(VALUES_FLAG_DB.DataNotFull, ";")); var found = false; List <TVALUES_DB> vallist = null; try { var tidList = new List <ID_Hierarchy_Channel>(); var IH_Chanel = new ID_Hierarchy_Channel(); IH_Chanel.ID = obj_id.ToString(); IH_Chanel.TypeHierarchy = (enumTypeHierarchy)ObjectType; IH_Chanel.Channel = (byte)Channel; tidList.Add(IH_Chanel); //TODO часовой пояс var res = ARM_Service.DS_GetArchivesHierObjectLastHalfHours( tidList, IsCoeffEnabled, StartDateTime.Get(context), EndDateTime.Get(context), DataSourceType, DiscreteType, UnitDigit, false, null); if (res != null && res.Result_Values != null && res.Result_Values.Count > 0) { var resultValues = new Dictionary <ID_Hierarchy_Channel, List <TVALUES_DB> >(res.Result_Values, new ID_Hierarchy_Channel_EqualityComparer()); if (resultValues.TryGetValue(IH_Chanel, out vallist) && vallist != null) { found = true; var R = vallist.Accomulate(); SummValues.Set(context, R.F_VALUE); Status.Set(context, (int)R.F_FLAG); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(R.F_FLAG, ";")); } } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } if (vallist == null) { vallist = new List <TVALUES_DB>(); } ValueList.Set(context, vallist); return(string.IsNullOrEmpty(Error.Get(context))); }
public TVALUES_DB EvaluateStringValue(int halfHourIndex) { if (!Compiled) { Compile(); } var count = 0; bool isPrecalcOpen = false; Variable precalcVariable = null; WorkedPeriodVariable wpPrecalcVariable = null; foreach (var evalStringValue in OutString) { switch (evalStringValue.PolskayaType) { case EnumPolskayaType.FunctionDescription: CurrentOperation = (Operations)evalStringValue.Variable; OutEvalString[count++].FunctionDevider = true; if (CurrentOperation == Operations.func_precalc) { isPrecalcOpen = true; } break; case EnumPolskayaType.Function: MakeFunction(ref count, evalStringValue.Variable as Function, _polskaParams.StartDateTime, _polskaParams.EndDateTime, halfHourIndex, _polskaParams.DiscreteType); break; case EnumPolskayaType.PrecalcFunctionBoolean: MakePrecalculateBooleanFunction(ref count, evalStringValue.Variable as Function, wpPrecalcVariable, halfHourIndex); break; case EnumPolskayaType.PrecalcFunctionVariable: MakePrecalculateFunctionVariable(ref count, evalStringValue.Variable as PrecalculatedFunctionVariable, precalcVariable, halfHourIndex); break; case EnumPolskayaType.Operation: CurrentOperation = (Operations)evalStringValue.Variable; MakeOperation(ref count); break; case EnumPolskayaType.Double: OutEvalString[count++].Value = (double)evalStringValue.Variable; break; case EnumPolskayaType.String: var stringval = evalStringValue.Variable as string; if (stringval != null) { OutEvalString[count++].StringValue = (string)evalStringValue.Variable; } break; case EnumPolskayaType.Variable: //Переменная или архив var val = evalStringValue.Variable as Variable; if (val != null) { TVALUES_DB dbValue = null; if (isPrecalcOpen) { isPrecalcOpen = false; precalcVariable = val; } else { dbValue = val.GetHalfHourValueByIndex(halfHourIndex); } if (dbValue != null) { if (_polskaParams.UnitDigit.HasValue) { //Сначала делим OutEvalString[count].SetValue(dbValue.F_FLAG, dbValue.F_VALUE / (double)_polskaParams.UnitDigit.Value); } else { OutEvalString[count].SetValue(dbValue.F_FLAG, dbValue.F_VALUE); } } else { var flag = _polskaParams.IsArchTech ? VALUES_FLAG_DB.DataNotFull : VALUES_FLAG_DB.IsFormulaNotCorrectEvaluated; OutEvalString[count].SetValue(flag, 0); } } count++; break; case EnumPolskayaType.WorkedPeriodVariable: var wpVal = evalStringValue.Variable as WorkedPeriodVariable; if (wpVal != null) { if (isPrecalcOpen) { isPrecalcOpen = false; wpPrecalcVariable = wpVal; } else { wpVal.FillVariable(halfHourIndex); } } count++; break; } } if (count != 1 || OutEvalString[0].FunctionDevider) { throw new Exception("Выражение некорректно!"); } return(OutEvalString[0].DBValue); }
public static DataTableEx ExecuteFormulasValueExpand(FormulasResult formulasResult, ArchivesValues_List2 archivesList, IVisualDataRequestObjectsNames getNameInterface, int doublePrecision, DateTime dtStart, DateTime dtEnd, enumTimeDiscreteType discreteType, string timeZoneId, ArchivesTPValueAllChannels archivesTpList = null, SectionIntegralActsTotalResults?archivesSection = null, bool isSumTiForChart = false, FormulaConstantArchives constantArchives = null, ArchTariffIntegralsTIs cumulativeIntegrals = null, ForecastConsumptionResult fResult = null, List <TRowObjectForGrid> listTiViewModel = null, bool isDetailOv = true, BalanceFreeHierarchyResults balanceFreeHierarchy = null) { if (archivesList == null && formulasResult == null && archivesTpList == null && archivesSection == null && constantArchives == null && cumulativeIntegrals == null && fResult == null && balanceFreeHierarchy == null) { return(null); } #if DEBUG var sw = new System.Diagnostics.Stopwatch(); sw.Start(); #endif var dts = getNameInterface.GetDateTimeListForPeriod(dtStart, dtEnd, discreteType, timeZoneId.GeTimeZoneInfoById()); var numbersValues = dts.Count; //Расчетный ли это профиль var deltaDiscrete = (int)discreteType + 1; //-------------Таблица для представления данных---------------------------- var userTable = new DataTableEx(); userTable.BeginLoadData(); try { userTable.Columns.Add("EventDateTime", typeof(DateTime)); #region Создаем колонки в пользовательском представлениее var vType = typeof(IFValue); var k = 0; #region ------------Перебираем точки--------------------------------------------- var tiColumnValues = userTable.AddColumnsTi(ref k, archivesList, isSumTiForChart, isDetailOv); #endregion #region ------------ТП--------------------------------------------- var tpColumnValues = userTable.AddColumnsTp(ref k, archivesTpList, listTiViewModel); // var tpArchives = new List<Tuple<TPoint, Dictionary<byte, List<TPointValue>>>>(); //if (archivesTpList != null) //{ //} #endregion #region ------------Перебираем формулы--------------------------------------------- var formulaArchives = new List <Tuple <IFormulaInfo, TFormulasResult, List <TFormulaConsist> > >(); if (formulasResult != null && formulasResult.Result_Values != null) { foreach (var formulas in formulasResult.Result_Values .Select(f => new Tuple <IFormulaInfo, TFormulasResult, List <TFormulaConsist> >(f.GetFormulaInfo(getNameInterface), f.Result_Values.FirstOrDefault(), f.FormulaConsist)) .Where(f => f.Item1 != null) .OrderBy(f => f.Item1.FormulaName)) { var fVal = formulas.Item2; if (fVal != null && fVal.Val_List != null && fVal.Val_List.Count > 0) { var col = new DataColumn("F_VALUE" + k, vType) { ReadOnly = true, }; userTable.Columns.Add(col); k++; } //------------ТИ которые входят в формулу------------------------------------------------------- if (formulasResult.IsValuesAllTIEnabled && formulas.Item3 != null) { foreach (var archivesValue in formulas.Item3) { if (archivesValue.Val_List == null) { continue; } //var hierObj = // getNameInterface.GetHierarchyDbTreeObject(archivesValue.TI_Ch_ID.TI_ID.ToString(), // archivesValue.TypeTIinFormula); var col = new DataColumn("F_VALUE" + k, vType) { ReadOnly = true, }; userTable.Columns.Add(col); k++; } } formulaArchives.Add(formulas); } } #endregion #region ------------Перебираем константы--------------------------------------------- if (constantArchives != null && constantArchives.FormulaConstantDict != null) { foreach (var formulaConstant in constantArchives.FormulaConstantDict.Values) { if (formulaConstant.ArchiveValues != null && formulaConstant.ArchiveValues.Count > 0) { var col = new DataColumn("F_VALUE" + k, vType) { //Caption = "Конст. -" + formulaConstant.ConstantaParams.FormulaConstantName, ReadOnly = true, }; userTable.Columns.Add(col); //namesFormulas.Add(new GridTitle //{ // //TitleString = "Конст. -" + formulaConstant.ConstantaParams.FormulaConstantName, // TitleString = "Конст. -" + formulaConstant.ConstantaParams.FormulaConstantName //}); k++; } } } #endregion #region ------------Перебираем сечения--------------------------------------------- if (archivesSection != null && archivesSection.Value.Total_Result != null && archivesSection.Value.Total_Result.Count > 0) { foreach (var sectionPair in archivesSection.Value.Total_Result) { var section = sectionPair.Value; if (section.TotalVals != null && section.TotalVals.Count > 0) { var sectionName = getNameInterface.GetSectionName(sectionPair.Key); var col = new DataColumn("F_VALUE" + k, vType) { //Caption = "Сеч. -" + sectionName, ReadOnly = true, }; userTable.Columns.Add(col); //namesFormulas.Add(new GridTitle //{ // //TitleString = "Сеч. -" + sectionName, // TitleString = "Сеч. -" + sectionName //}); k++; } } } #endregion #region ------------Перебираем накопительные интегралы------------------------------ if (cumulativeIntegrals != null && cumulativeIntegrals.IntegralsValue30orHour != null) { var nType = typeof(IConvertible); foreach (var integral in cumulativeIntegrals.IntegralsValue30orHour) { if (integral.Cumulate_Val_List == null || integral.Cumulate_Val_List.Count == 0) { continue; } //var tiName = getNameInterface.GetTIName(integral.TI_Ch_ID.TI_ID, integral.TI_Ch_ID.IsCA); //var psName = getNameInterface.GetPSName(integral.PS_ID, integral.TI_Ch_ID.IsCA); var col = new DataColumn("F_VALUE" + k, nType) { //Caption = tiName + // getNameInterface.GetChanelTypeNameByID(integral.TI_Ch_ID.TI_ID, // integral.TI_Ch_ID.ChannelType, false, // cumulativeIntegrals.DTStart, cumulativeIntegrals.DTEnd) + " \n" + // psName, ReadOnly = true, }; userTable.Columns.Add(col); k++; } } #endregion #region ------------Прогнозирование------------------------------ if (fResult != null && fResult.Result_Values != null) { var hierarchyObject = getNameInterface.GetHierarchyDbTreeObject(fResult.ID.ID, fResult.ID.TypeHierarchy); if (hierarchyObject != null) { foreach (var archive in fResult.Result_Values) { if (archive.Value == null) { continue; } var col = new DataColumn("F_VALUE" + k, vType) { Caption = hierarchyObject.Name + " " + getNameInterface.GetChanelTypeNameByID(archive.Key.Channel, false), ReadOnly = true, }; userTable.Columns.Add(col); k++; } } } #endregion #region ------------Перебираем балансы--------------------------------------------- var balanceColumnValues = userTable.AddColumnsBalances(ref k, balanceFreeHierarchy); #endregion #endregion #if DEBUG sw.Stop(); Console.WriteLine("Создаем колонки в пользовательском представлениее - > {0} млс", sw.ElapsedMilliseconds); sw.Restart(); #endif #region Наполняем поставщик if (archivesList != null) { userTable.Description = new DataTableDescription { DtStart = archivesList.DTStart, DiscreteType = archivesList.DiscreteType, TimeZoneId = archivesList.TimeZoneId, }; } else { userTable.Description = null; } for (var i = 0; i < numbersValues; i++) { k = 0; //--------колонки в промежуточную таблицу----------- var row = userTable.NewRow() as DataRowEx; var dt = dts[i]; row["EventDateTime"] = dt; //row["Time"] = dt.TimeOfDay; //-------пишем в промежуточную таблицу значения-------- //TVALUES_DB mainChannelVal = null; #region ТИ userTable.PopulateRowsTi(ref k, tiColumnValues, numbersValues, isSumTiForChart, row, i); #endregion #region ТП userTable.PopulateRowsTp(ref k, tpColumnValues, row, i); #endregion #region Формулы if (formulasResult != null && formulasResult.Result_Values != null) { foreach (var formulas in formulaArchives) { enumTypeHierarchy typeHierarchy; switch (formulas.Item1.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 = formulas.Item1.Formula_UN, TypeHierarchy = typeHierarchy }; var fVal = formulas.Item2; if (fVal != null && fVal.Val_List != null && fVal.Val_List.Count > 0) { var v = fVal.Val_List.ElementAtOrDefault(i); if (v != null) { var useMeasureModule = string.IsNullOrEmpty(fVal.MeasureUnit_UN) && (string.Equals(fVal.MeasureQuantityType_UN, "EnergyUnit") || string.Equals(fVal.MeasureQuantityType_UN, "PowerUnit")); //row["F_VALUE" + k] = v; row.SetValue("F_VALUE" + k, i, 0, id, null, fVal.MeasureUnit_UN, v, useMeasureModule); } k++; } if (formulasResult.IsValuesAllTIEnabled && formulas.Item3 != null) { foreach (var archivesValue in formulas.Item3) { if (archivesValue.Val_List == null) { continue; } var v = archivesValue.Val_List.ElementAtOrDefault(i); if (v != null) { if (archivesValue.Id == null) { row["F_VALUE" + k] = new TVALUES_DB { F_VALUE = v.F_VALUE, F_FLAG = v.F_FLAG, }; } else { row.SetValue("F_VALUE" + k, i, archivesValue.ChannelType, archivesValue.Id, null, null, v); } } k++; } } } } #endregion #region Константы if (constantArchives != null && constantArchives.FormulaConstantDict != null) { foreach (var formulaConstant in constantArchives.FormulaConstantDict.Values) { if (formulaConstant.ArchiveValues != null) { var v = formulaConstant.ArchiveValues.ElementAtOrDefault(i); if (v != null) { row.SetValue("F_VALUE" + k, i, 0, new ID_Hierarchy { ID = formulaConstant.ConstantaParams.FormulaConstant_UN, TypeHierarchy = enumTypeHierarchy.FormulaConstant }, null, null, v); } k++; } } } #endregion #region Сечения if (archivesSection != null && archivesSection.Value.Total_Result != null && archivesSection.Value.Total_Result.Count > 0) { foreach (var sectionPair in archivesSection.Value.Total_Result) { var section = sectionPair.Value; List <TVALUES_DB> values; if (section.TotalVals != null && section.TotalVals.Count > 0 && section.TotalVals.TryGetValue(enumInputType.Saldo, out values)) { var v = values.ElementAtOrDefault(i); if (v != null) { //row["F_VALUE" + k] = v; row.SetValue("F_VALUE" + k, i, 0, new ID_Hierarchy { ID = sectionPair.Key.ToString(), TypeHierarchy = enumTypeHierarchy.Section }, null, null, v); } k++; } } } #endregion #region ------------Перебираем накопительные интегралы------------------------------ if (cumulativeIntegrals != null && cumulativeIntegrals.IntegralsValue30orHour != null) { var unitDigitCoeff = (double)cumulativeIntegrals.UnitDigit; foreach (var integral in cumulativeIntegrals.IntegralsValue30orHour) { if (integral.Cumulate_Val_List == null || integral.Cumulate_Val_List.Count == 0) { continue; } var val = integral.Cumulate_Val_List.ElementAtOrDefault(i); if (val != null) { var v = new TVal { F_FLAG = val.F_FLAG, F_VALUE = val.Value / unitDigitCoeff, }; //var v = val.Value / unitDigitCoeff; //------------ТИ ФСК----------------------------- row.SetValue("F_VALUE" + k, i, integral.TI_Ch_ID.ChannelType, new ID_Hierarchy { ID = integral.TI_Ch_ID.TI_ID.ToString(), TypeHierarchy = enumTypeHierarchy.Info_TI }, integral.TI_Ch_ID.DataSourceType, null, v); //row["F_VALUE" + k] = v; //if (integral.TI_Ch_ID.ChannelType < 3 && v > 0) //{ // mainChannelVal = v; //} } k++; } } #endregion #region ------------Прогнозирование------------------------------ if (fResult != null && fResult.Result_Values != null) { var hierarchyObject = getNameInterface.GetHierarchyDbTreeObject(fResult.ID.ID, fResult.ID.TypeHierarchy); if (hierarchyObject != null) { var unitDigitCoeff = (double)fResult.UnitDigit; foreach (var archive in fResult.Result_Values) { if (archive.Value == null) { continue; } var val = archive.Value.ElementAtOrDefault(i); if (val != null) { var v = new TVALUES_DB { F_FLAG = val.F_FLAG, F_VALUE = val.F_VALUE / unitDigitCoeff, }; //------------ТИ ФСК----------------------------- //row["F_VALUE" + k] = v; row.SetValue("F_VALUE" + k, i, archive.Key.Channel, new ID_Hierarchy { ID = archive.Key.ID, TypeHierarchy = archive.Key.TypeHierarchy, }, null, null, v); } k++; } } } #endregion #region Балансы userTable.PopulateRowsBalances(ref k, balanceColumnValues, row, i); #endregion // if (consumptionSchedule != null && mainChannelVal != null && mainChannelVal.F_VALUE != null && // mainChannelVal.F_FLAG.HasFlag(VALUES_FLAG_DB.ConsumptionScheduleOverflow)) //{ // //Ищем значение типового графика для данной получасовки // var cs_val = // consumptionSchedule.ConsumptionScheduleValues.FirstOrDefault( // cs => cs.TotalDay == (dt.Date - dtStart.Date).TotalDays && cs.TotalNumberPerDay == // dt.TimeOfDay.TotalMinutes / (30 * deltaDiscrete)); // if (cs_val != null && cs_val.F_VALUE.HasValue) // { // double delta = 0; // if (mainChannelVal.F_VALUE > cs_val.MAX_VALUE) // { // delta = mainChannelVal.F_VALUE - cs_val.F_VALUE.Value; // } // else // { // delta = mainChannelVal.F_VALUE - cs_val.F_VALUE.Value; // } // row["ConsumptionSchedule"] = delta; // row["ConsumptionSchedulePercent"] = delta / mainChannelVal.F_VALUE * 100; // } //} userTable.Rows.Add(row); } #endregion } finally { userTable.EndLoadData(); userTable.AcceptChanges(); } #if DEBUG sw.Stop(); Console.WriteLine("ExecuteFormulasValueExpand - > {0} млс", sw.ElapsedMilliseconds); #endif return(userTable); }
private object BuildValue(DetailFieldInfo fieldInfo, int i, ref int k) { switch (fieldInfo.ColumnType) { case EnumColumnType.OvInfo: // Это информация об ОВ { var replacedIds = new List <ID_Hierarchy>(); //Перебираем все ТИ, которые могут быть замещены в этом дискретном периоде if (fieldInfo.TiReplaced != null) { foreach (var tiReplaced in fieldInfo.TiReplaced) { if (tiReplaced.Value.ValuesByIndexes == null) { continue; } if (!tiReplaced.Value.ValuesByIndexes.ContainsKey(i)) { continue; } replacedIds.Add(new ID_Hierarchy { ID = tiReplaced.Key.ToString(), TypeHierarchy = enumTypeHierarchy.Info_TI, }); } } return(new ObjectIdCollection(replacedIds)); } case EnumColumnType.OvValue: //Это значение замещаемой ТИ { TDateTimeOV vals; TVALUES_DB val = null; int replacedTiId; if (fieldInfo.ReplacedId != null && int.TryParse(fieldInfo.ReplacedId.ID, out replacedTiId) && fieldInfo.TiReplaced.TryGetValue(replacedTiId, out vals) && vals != null && vals.ValuesByIndexes != null) { vals.ValuesByIndexes.TryGetValue(i, out val); } return(val); } case EnumColumnType.FactUnbalancePercent: case EnumColumnType.FactUnbalanceValue: { return(fieldInfo.TryGetBalaanceValue(i, fieldInfo.ColumnType)); } default: { //Обычное значение k++; if (fieldInfo.Values != null) { if (fieldInfo.IsOv) { //Считаем неразнесенное значение return(fieldInfo.TryCalculateUnreplacedValue(i)); } } return(fieldInfo.TryGetValue(i)); } } return(null); }
protected override bool Execute(CodeActivityContext context) { int ti_id = TiId.Get(context); Value.Set(context, 0); Status.Set(context, (int)VALUES_FLAG_DB.DataNotFull); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(VALUES_FLAG_DB.DataNotFull, ";")); ValueDateTime.Set(context, DateTime.MinValue); List <TINTEGRALVALUES_DB> _valueList = new List <TINTEGRALVALUES_DB>(); ValueList.Set(context, _valueList); if (RequestType == enumEnrgyQualityRequestType.Archive) { if (StartDateTime.Get(context) == null || EndDateTime.Get(context) == null) { Error.Set(context, "Для архивных значений начальная и конечная дата должна быть определена"); return(false); } } try { List <TI_ChanelType> tiList = new List <TI_ChanelType>() { new TI_ChanelType() { TI_ID = ti_id, ChannelType = Channel.Get(context), DataSourceType = DataSourceType, } }; if (RequestType == enumEnrgyQualityRequestType.Archive) { //TODO часовой пояс var values = ARM_Service.DS_GetIntegralsValues_List(tiList, StartDateTime.Get(context), EndDateTime.Get(context), IsCoeffEnabled, false, false, true, false, false, enumTimeDiscreteType.DBHalfHours, EnumUnitDigit.None, null, false, false); if (values != null && values.IntegralsValue30orHour != null && values.IntegralsValue30orHour.Count > 0) { var integralTiValue = values.IntegralsValue30orHour[0]; double diff = 0; var flag = VALUES_FLAG_DB.None; if (integralTiValue.Val_List != null) { foreach (var iVal in integralTiValue.Val_List) { diff += iVal.F_VALUE_DIFF; flag = flag.CompareAndReturnMostBadStatus(iVal.F_FLAG); _valueList.Add(iVal); } } Value.Set(context, diff); var stat = flag; Status.Set(context, (int)stat); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(stat, ";")); if (integralTiValue.Val_List != null && integralTiValue.Val_List.Count > 0) { ValueDateTime.Set(context, integralTiValue.Val_List.Last().EventDateTime); } } } else { var Val = ARM_Service.DS_ReadLastIntegralArchives(tiList); if (Val != null && Val.Count > 0) { var ValDict = Val.ToDictionary(k => k.Key, v => v.Value, new TI_ChanelComparer()); foreach (var r in tiList) { TINTEGRALVALUES_DB i_val; if (ValDict.TryGetValue(r, out i_val) && i_val != null) { Value.Set(context, i_val.F_VALUE); Status.Set(context, (int)i_val.F_FLAG); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(i_val.F_FLAG, ";")); ValueDateTime.Set(context, i_val.EventDateTime); _valueList.Add(i_val); break; } } } } } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } ValueList.Set(context, _valueList); return(string.IsNullOrEmpty(Error.Get(context))); }
protected override bool Execute(CodeActivityContext context) { var formulaUn = Formula_UN.Get(context); if (string.IsNullOrEmpty(formulaUn)) { Error.Set(context, "Не определен идентификатор формулы"); return(false); } var fId = new TFormulaParam { FormulaID = formulaUn, FormulasTable = enumFormulasTable.Info_Formula_Description, IsFormulaHasCorrectDescription = true, }; TFormulasResult result = null; try { var res = ARM_Service.FR_GetFormulasResults(new List <TFormulaParam> { fId }, StartDateTime.Get(context), EndDateTime.Get(context), DiscreteType, DataSourceType, 1, IsCoeffEnabled, false, isPower, false, UnitDigit, null, false, false); if (res != null && res.Result_Values != null && res.Result_Values.Count > 0) { var rv = res.Result_Values[0]; if (rv != null && rv.Result_Values != null && rv.Result_Values.Count > 0) { result = rv.Result_Values[0]; if (result.Val_List != null) { var r = result.Val_List.Accomulate(); SummValues.Set(context, r.F_VALUE); Status.Set(context, (int)r.F_FLAG); StatusStr.Set(context, TVALUES_DB.FLAG_to_String(r.F_FLAG, ";")); } } } if (res.Errors != null) { Error.Set(context, res.Errors.ToString()); } FormulaResult.Set(context, result); } catch (Exception ex) { Error.Set(context, ex.Message); if (!HideException.Get(context)) { throw ex; } } return(string.IsNullOrEmpty(Error.Get(context))); }
private MemoryStream ФормируемПриложение51(XlsFileExBase xls, BalanceFreeHierarchyCalculatedResult balanceCalculatedResult, bool isHeaderFormed) { xls.ActiveSheet = 1; var sheetName = xls.SheetName = "Приложение"; xls.SetPrintMargins(new TXlsMargins(0.75, 1, 0.75, 1, 0.5, 0.5)); xls.SheetZoom = 100; #region Добавление форматов var f = xls.GetCellVisibleFormatDef(1, 4); f.Font.Name = "Tahoma"; f.Font.Family = 2; f.HAlignment = THFlxAlignment.center; f.WrapText = true; if (_doublePrecisionProfile == 0) { f.Format = "#,##0"; } else { f.Format = "#,##0." + new string(_need0 ? '0' : '#', _doublePrecisionProfile); } var centerFormat = xls.AddFormat(f); f = xls.GetCellVisibleFormatDef(4, 1); if (_doublePrecisionProfile == 0) { f.Format = "#,##0"; } else { f.Format = "#,##0." + new string(_need0 ? '0' : '#', _doublePrecisionProfile); } f.Font.Name = "Tahoma"; f.Font.Family = 2; f.Borders.Left.Style = TFlxBorderStyle.Thin; f.Borders.Left.Color = Color.FromArgb(0x00, 0x00, 0x00); f.Borders.Right.Style = TFlxBorderStyle.Thin; f.Borders.Right.Color = Color.FromArgb(0x00, 0x00, 0x00); f.Borders.Top.Style = TFlxBorderStyle.Thin; f.Borders.Top.Color = Color.FromArgb(0x00, 0x00, 0x00); f.Borders.Bottom.Style = TFlxBorderStyle.Thin; f.Borders.Bottom.Color = Color.FromArgb(0x00, 0x00, 0x00); f.HAlignment = THFlxAlignment.center; f.VAlignment = TVFlxAlignment.center; f.WrapText = true; var borderedCenterFormat = xls.AddFormat(f); f.Font.Style = TFlxFontStyles.Bold; var boldBorderedCenterFormat = xls.AddFormat(f); var startRow = 18; var startCol = 1; #endregion xls.ProfileFormat = xls.NoDecimalFormat = borderedCenterFormat; List <Dict_Balance_FreeHierarchy_Section> sections = null; if (_balanceCalculated.SectionsByType != null) { _balanceCalculated.SectionsByType.TryGetValue(balanceCalculatedResult.BalanceFreeHierarchyType, out sections); } if (!isHeaderFormed) { #region Шапка xls.SetColWidth(1, 9142); //(34.96 + 0.75) * 256 xls.SetColWidth(2, 4554); //(11.96 + 0.75) * 256 xls.SetColWidth(3, 6582); //(24.96 + 0.75) * 256 xls.SetColWidth(4, 6582); //(24.96 + 0.75) * 256 xls.MergeCells(10, 1, 10, 3); xls.MergeCells(12, 1, 12, 3); xls.MergeCells(1, 2, 3, 3); xls.MergeCells(4, 1, 4, 3); xls.MergeCells(6, 1, 6, 3); xls.MergeCells(8, 1, 8, 3); xls.SetCellFormat(1, 1, 3, 3, centerFormat); xls.SetCellValue(1, 2, "Приложение № 63\nк приказу Минэнерго России\nот 23 июля 2012г. №340"); xls.SetCellFormat(4, 1, 4, 3, boldBorderedCenterFormat); //_xls.Add //_xls.SetCellFromHtml(4, 1, "<b>121212</b> weqeeqewq <i>wwewewewe</i>"); xls.SetCellValue(4, 1, "Показатели баланса производства и потребления электроэнергии\n" + "и отпуска тепловой энергии по субьектам электроэнергетики\n" + "в границах субьектов Российской Федерации\n" + "за " + DateTime.Now.Date.Year.ToString() + " год."); xls.SetRowHeight(4, 1000); xls.SetCellFormat(6, 1, 6, 3, borderedCenterFormat); xls.SetCellValue(6, 1, "КОНФИДЕНЦИАЛЬНОСТЬ ГАРАНТИРУЕТСЯ ПОЛУЧАТЕЛЕМ ИНФОРМАЦИИ"); xls.SetCellFormat(8, 1, 8, 3, borderedCenterFormat); xls.SetCellValue(8, 1, "ВОЗМОЖНО ПРЕДСТАВЛЕНИЕ В ЭЛЕКТРОННОМ ВИДЕ"); xls.SetCellFormat(9, 1, 10, 3, borderedCenterFormat); xls.SetCellValue(10, 1, "1. Предоставляется электростанциями генерирующих компаний и других собственников, ФГУП `Концерн " + "Росэнергоатом`, котельными"); xls.SetRowHeight(10, 500); xls.SetCellFormat(12, 1, 12, 3, borderedCenterFormat); xls.SetCellValue(12, 1, balanceCalculatedResult.DocumentName.Replace("№51", "№63") + " филиал " + _branchName); xls.SetCellFormat(13, 1, 14, 3, centerFormat); xls.SetCellValue(14, 2, string.Format("{0:dd.MM.yyyy}", _dtEnd)); xls.SetCellValue(14, 3, _unitDigitName + ", " + _unitDigitHeatName); #endregion } else { //Обрабатываем наши ф-ии SpreadsheetFunctionHelper.Evaluate(xls, this, out startRow, _errors); } #region Заголовок таблицы xls.SetCellFormat(startRow, 1, startRow + 2, 3, borderedCenterFormat); xls.SetCellValue(startRow, 1, "Наименование показателя"); xls.MergeCells(startRow, 1, startRow + 1, 1); xls.SetCellValue(startRow, 2, "Фактические значения показателя"); xls.MergeCells(startRow, 2, startRow, 3); xls.SetRowHeight(startRow, 400); xls.SetCellValue(startRow + 1, 2, "за сутки"); xls.SetCellValue(startRow + 1, 3, "нарастающим итогом с начала месяца"); startRow++; startRow++; xls.SetCellValue(startRow, 1, "А"); xls.SetCellValue(startRow, 2, "1"); xls.SetCellValue(startRow, 3, "2"); startRow++; #endregion #region Таблица if (_doublePrecisionProfile == 0) { f.Format = "#,##0"; } else { f.Format = "#,##0." + new string(_need0 ? '0' : '#', _doublePrecisionProfile); } var boldBorderedDoubleFormat = xls.AddFormat(f); xls.ProfileBoldFormat = boldBorderedDoubleFormat; var sectionNumber = 1; var row = startRow; double potreb = 0.0, potrebDaily = 0.0; foreach (var section in sections.OrderBy(s => s.SortNumber)) { xls.SetCellValue(row, startCol, section.SectionName, boldBorderedCenterFormat); xls.SetCellValue(row, startCol + 1, row - startRow + 1, boldBorderedCenterFormat); var sectionRow = row; List <BalanceFreeHierarchyItemParams> itemParams; //Все объекты для данного раздела balanceCalculatedResult.ItemsParamsBySection.TryGetValue(section.Section_UN, out itemParams); var formulaIdSumm = "summ" + section.SortNumber; var formulaIdDailySumm = "dailySumm" + section.SortNumber; double sectionSum = 0.0, sectionDailySum = 0.0; var itemNumber = 1; if (itemParams != null && itemParams.Count > 0) { //Перебираем объекты в разделе foreach (var itemParam in itemParams.OrderBy(itm => itm.SortNumber)) { TVALUES_DB latestDay = null; var daysSumm = 0.0; var coeff = itemParam.Coef ?? 1; if (itemParam.HalfHours != null) { var archives = MyListConverters.ConvertHalfHoursToOtherList(_discreteType, itemParam.HalfHours, 0, _intervalTimeList); latestDay = archives.LastOrDefault(); //Нарастающее с начала месяца daysSumm = archives.Sum(itm => itm.F_VALUE); } //Объекты в разделе отображаем только для поступления if (Equals(section.MetaString1, "postupilo")) { row++; xls.SetCellValue(row, startCol, sectionNumber + "." + itemNumber + " " + itemParam.Name, borderedCenterFormat); //_xls.SetCellValue(row, startCol + 1, row - startRow + 1, borderedCenterFormat); if (latestDay != null) { //Факт за последние сутки xls.SetCellFloatValue(row, startCol + 1, latestDay.F_VALUE * coeff, false); } else { xls.SetCellFormat(row, startCol + 1, borderedCenterFormat); } xls.SetCellFloatValue(row, startCol + 2, daysSumm * coeff, false); AddRowRangeToFormulaSum(xls, formulaIdSumm, new FormulaRowsRange { Row1 = row, Row2 = row, Col = startCol + 1, }); AddRowRangeToFormulaSum(xls, formulaIdDailySumm, new FormulaRowsRange { Row1 = row, Row2 = row, Col = startCol + 2, }); itemNumber++; } if (latestDay != null) { sectionSum += latestDay.F_VALUE * coeff; } sectionDailySum += daysSumm * coeff; } } if (Equals(section.MetaString1, "postupilo")) { potreb += sectionSum; potrebDaily += sectionDailySum; } else if (Equals(section.MetaString1, "saldo")) { potreb -= sectionSum; potrebDaily -= sectionDailySum; } if (Equals(section.MetaString1, "potreb")) { sectionSum = potreb; sectionDailySum = potrebDaily; } if (!string.IsNullOrEmpty(section.MetaString1)) { if (!Equals(section.MetaString1, "potreb")) { WriteFormulaToCell(xls, formulaIdSumm, sectionRow, startCol + 1, boldBorderedDoubleFormat, sectionSum); WriteFormulaToCell(xls, formulaIdDailySumm, sectionRow, startCol + 2, boldBorderedDoubleFormat, sectionDailySum); } else { xls.SetCellFloatValue(sectionRow, startCol + 1, sectionSum, false); xls.SetCellFloatValue(sectionRow, startCol + 2, sectionDailySum, false); } } else { xls.SetCellFormat(sectionRow, startCol + 1, sectionRow, startCol + 2, boldBorderedDoubleFormat); } sectionNumber++; row++; } #endregion return(Export(xls)); }