//public IList<Meter> GetMeterListByPlant(Plant p) //{ // return new List<Meter>() { new Meter(){ Id = "ABAGI01000", LosingRate = 0, Power = 500 }, new Meter(){ Id = "SSANS01000", LosingRate = 0, Power = 500 } }; //} public IList<Meter> GetMeterListByPlant(Plant p) { // Plantas de prueba para pedir datos //IList<string> idPlantList = new List<string>() { "TRUFW01", "FESFW01", "OLMFW01", "ABECP01" }; RfcDestination rfcDestination = getRfcDestination(); IRfcFunction rfcFunction = getRfcFunction(rfcDestination); // Preparamos la tabla de carga con los datos que necesitamos IRfcTable rfcTable = rfcFunction.GetTable(RFC_FUNCTION_TABLE_NAME_LOADER); rfcTable.Append(); rfcTable.SetValue(RFC_FUNCTION_TABLE_NAME_LOADER_FIELD, p.Id); // Hacemos commit de la inserción en SAP commitDataInsertion(rfcFunction, rfcDestination); // Una vez metidos los datos de entrada, pedimos la tabla de resultados IRfcTable returnTable = getReturnTable(rfcDestination, rfcFunction); // Conversión a Meter IList<Meter> meterList = transformResultDataToMeterList(returnTable); //Console.WriteLine(String.Format("Se han encontrado {0} Meters", meterList.Count)); return meterList; }
private int ProcessSigmaMeasure(double totalPower, Meter meter, IOrderedEnumerable<SigmaMeasure> queryDay, DateTime initialUtcDate, DateTime localDate, string executionResume,Plant plant) { //It saves the minutes offset os a date converted to UTC //When a date with hour on the hour is converted to UTC in some time zones it could //be converted in half-past hour or something similar so we need to save this parameter int minutesOffset = initialUtcDate.Minute; DateTime utcDate = new DateTime(); int lastNumPeriod = -1; //this block generate a new SMeasure or increment value of a created SMeasure if was created with same date and time //ProductionValue parameter include all meters power sum per plant and datetime foreach (var sigmaMeasure in queryDay) { //Fix errors of same numperiod in two or more different sigmaMeasures if (sigmaMeasure.NumPeriod != lastNumPeriod) { while (sigmaMeasure.NumPeriod - lastNumPeriod != 1) { Logger.Warn(string.Format("Missing Period Number {0} in meter with ID '{1}' and local date {2}", lastNumPeriod, sigmaMeasure.Id_Meter, localDate.ToShortDateString())); executionResume = string.Format("{0}\n\tMissing Period Number {1} in meter with ID '{2}' and local date {3}", executionResume, lastNumPeriod, sigmaMeasure.Id_Meter, localDate.ToShortDateString()); lastNumPeriod++; } lastNumPeriod = sigmaMeasure.NumPeriod; utcDate = initialUtcDate.AddHours(sigmaMeasure.NumPeriod); SMeasure sm = SMeasureInListByDate(ListOfSMeasures, plant.Id, utcDate); if (sm == null) { sm = new SMeasure(plant.Id, utcDate.Date, utcDate.Hour, minutesOffset, sigmaMeasure.ProductionValue * meter.LosingRate * meter.PowerPercentage, ((meter.Power * 1000) / totalPower)); ListOfSMeasures.Add(sm); } else { sm.Value += sigmaMeasure.ProductionValue * meter.LosingRate * meter.PowerPercentage; //Preguntar si "meter.PowerPercentage" es necesario para el calculo de porcentaje de medida //Si porcentaje de medida indica la cantidad de medidas que hay NO sería necesario //Si indicara el porcentaje de potencia con respecto al total SI sm.MeasurePercentage += ((meter.Power * 1000) / totalPower); } } else { Logger.Warn(string.Format("Repeated Period Number {0} in meter with ID '{1}' and local date {2}", lastNumPeriod, sigmaMeasure.Id_Meter, localDate.ToShortDateString())); executionResume = string.Format("{0}\n\tRepeated Period Number {1} in meter with ID '{2}' and local date {3}", executionResume, lastNumPeriod, sigmaMeasure.Id_Meter, localDate.ToShortDateString()); } } return lastNumPeriod; }
private void ProcessMeters(double totalPower,Plant plant, IList<Meter> meterList, IList<SigmaMeasure> sigmaMeasureList, DateTime date, TimeZoneInfo timeZone, int periodsOfDate, string executionResume) { foreach (SigmaMeasure sigmameasure in sigmaMeasureList) { Logger.Info(string.Format("Sigma measures ProdutionDate '{0}' and numPeriod {1}", sigmameasure.ProductionDate, sigmameasure.NumPeriod)); } bool[] periodsWithData = new bool[24]; foreach (var meter in meterList) { Logger.Info(string.Format("Analyzing sigma measures of meter ID '{0}' and local date {1}", meter.IdMeter, date.ToShortDateString())); //Get list of sigma measures of a meter with id 'idMeter' where sigma measure production date (day, month and year) are equal to 'date' var var queryDay = from SigmaMeasure in sigmaMeasureList where SigmaMeasure.ProductionDate.Day == date.Day && SigmaMeasure.ProductionDate.Month == date.Month && SigmaMeasure.ProductionDate.Year == date.Year && SigmaMeasure.Id_Meter.Equals(meter.IdMeter) orderby SigmaMeasure.NumPeriod ascending select SigmaMeasure; if (queryDay.Count() == 0) { Logger.Warn(string.Format("{0} results", queryDay.Count())); executionResume = string.Format("{0}\n\t{1} results", executionResume, queryDay.Count()); } else { if (queryDay.Count()==25) periodsWithData = new bool[25]; Logger.Info(string.Format("{0} results", queryDay.Count())); Logger.Debug(string.Format("1.Entro")); foreach (SigmaMeasure sm in queryDay) { periodsWithData[sm.NumPeriod] = true; } Logger.Debug(string.Format("2.Entro")); DateTime localDate = date.Date; localDate = DateTime.SpecifyKind(localDate, DateTimeKind.Unspecified); Logger.Debug(string.Format("Entro en initial date '{0}' for converting to UTC with timezone '{1}'", localDate, timeZone)); DateTime initialUtcDate = new DateTime(); //If localDate is ambiguous date (in daylight saving time when it is converted to UTC could return 2 datetimes, //.Net method 'ConvertTimeToUtc' return second option. This code lines fix it) if (timeZone.IsAmbiguousTime(localDate)) { Logger.Warn(string.Format("Ambiguous local time found: {0}.", localDate)); executionResume = string.Format("{0}\n\tAmbiguous local time found: {1}.", executionResume, localDate); initialUtcDate = TimeZoneInfo.ConvertTimeToUtc(localDate, timeZone); initialUtcDate.AddHours(-1); Logger.Warn("Ambiguous local time fixed in UTC"); executionResume = string.Format("{0}\n\tAmbiguous local time fixed in UTC", executionResume); } else { Logger.Debug(string.Format("Entro en initial date '{0}' for converting to UTC with timezone '{1}'", localDate,timeZone)); initialUtcDate = TimeZoneInfo.ConvertTimeToUtc(localDate, timeZone); Logger.Debug(string.Format("Local date '{0}' has been converted to UTC: '{1}'",localDate,initialUtcDate)); } int lastNumPeriod = ProcessSigmaMeasure(totalPower, meter, queryDay, initialUtcDate, localDate, executionResume,plant); for (int i = lastNumPeriod + 1; i < periodsOfDate; i++) { Logger.Warn(string.Format("Missing Period Number {0} in meter with ID '{1}' and local date {2}", i, meter.IdMeter, localDate.ToShortDateString())); executionResume = string.Format("{0}\n\tMissing Period Number {1} in meter with ID '{2}' and local date {3}", executionResume, i, meter.IdMeter, localDate.ToShortDateString()); } } } String missingPeriods = ""; for (int i = 0; i < periodsWithData.Count(); i++) { if (periodsWithData[i] == false) { if (missingPeriods.Equals("")) { missingPeriods = string.Format("{0}", i); } else { missingPeriods = string.Format("{0},{1}", missingPeriods, i); } } } if (!missingPeriods.Equals("")) { if (!idPlantWritedInReport) { _wiseReport.AppendFormat("{0};", plant.Id); idPlantWritedInReport = true; } _wiseReport.AppendFormat("{0};", date.ToString(CultureInfo.GetCultureInfo("es-ES"))); _wiseReport.AppendFormat("{0};", missingPeriods); } }
private void ProcessAndSendListOfSMeasures(Plant plant, List<SMeasure> ListOfSMeasures, List<List<SMeasure>> ListOfListOfSMeasuresToReSend, double totalPower, string executionResume) { //This block round measure percentage and value parameters to 4 decimal foreach (var smeasure in ListOfSMeasures) { smeasure.MeasurePercentage = Math.Round(smeasure.MeasurePercentage, 4); smeasure.Value = Math.Round(smeasure.Value, 4); CultureInfo provider = CultureInfo.InvariantCulture; string format = "yyyyMMdd"; DateTime utcDateTime = DateTime.ParseExact(smeasure.UtcDate, format, provider); utcDateTime = utcDateTime.AddHours(smeasure.UtcHour); TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(plant.TimeZone); DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, timeZone); smeasure.ReliabilityType = MeasureValidation.GetMeasureReliabilityType(smeasure.Value, localDateTime.Hour, localDateTime.Date, plant, totalPower); } Logger.Info(string.Format("{0} measures generated of plant {1}", ListOfSMeasures.Count, plant.Id)); //These lines convert the list of SMeasure objects in a json string string jsonStringOfSMeasures = ConvertSMeasuresToJSON(ListOfSMeasures); try { Logger.Info(string.Format("Sending measures of plant {0}", plant.Id)); bool jsonSentSuccesfully = IWepAPIProv.PutJSONMeasureList(WebAPIURL, jsonStringOfSMeasures); if (jsonSentSuccesfully) { Logger.Info("Measures sent succesfully"); } else { Logger.Warn(string.Format("Failed measures send process of plant {0}. Saved to resend", plant.Id)); executionResume = string.Format("{0}\n\tFailed measures send process of plant {1}. Saved to resend", executionResume, plant.Id); List<SMeasure> copyOfList = ListOfSMeasures.Take(ListOfSMeasures.Count).ToList(); ListOfListOfSMeasuresToReSend.Add(copyOfList); } } catch (Exception e) { Logger.Error(string.Format("Exception sending measures of plant {0}. Saved to resend", plant.Id), e); executionResume = string.Format("{0}\n\t*Exception sending measures of plant {1}. Saved to resend", executionResume, plant.Id); List<SMeasure> copyOfList = ListOfSMeasures.Take(ListOfSMeasures.Count).ToList(); ListOfListOfSMeasuresToReSend.Add(copyOfList); } finally { ListOfSMeasures.Clear(); } }
public void Can_Get_Correct_Data_With_Missing_Periods() { var timezoneMock = new Mock<TimeZone>(); timezoneMock.Setup(s => s.StandardName).Returns("Iran Standard Time"); Plant p = new Plant() { Id = "PLT1", TimeZone = timezoneMock.Object.StandardName, }; var isappMock = new Mock<ISAPProvider>(); IList<Meter> meterList = new List<Meter>() { new Meter() { IdMeter = "ABAGI01000", LosingRate = 0, Power = 50, IdPlant = p.Id, PowerPercentage = 1 }, new Meter() { IdMeter = "ABAGI01001", LosingRate = 0, Power = 50, IdPlant = p.Id, PowerPercentage = 1 } }; isappMock.Setup(s => s.GetMeterListByPlant(p)).Returns(meterList); IList<SigmaMeasure> listSigmaMeasure = new List<SigmaMeasure>(); DateTime date1 = new DateTime(2012, 9, 21); for (int i = 0; i < 24; i++) { SigmaMeasure sm = new SigmaMeasure() { Id_Meter = "ABAGI01000", NumPeriod = i + 1, ProductionDate = date1, ProductionValue = 50 }; if (sm.NumPeriod != 3) { listSigmaMeasure.Add(sm); } sm = new SigmaMeasure() { Id_Meter = "ABAGI01001", NumPeriod = i + 1, ProductionDate = date1, ProductionValue = 40 }; if (sm.NumPeriod != 3) { listSigmaMeasure.Add(sm); } } Mock<SigmaMeasureService> sigmaMeasureServMock = new Mock<SigmaMeasureService>(null); sigmaMeasureServMock.Setup(s => s.GetByMeterListInDateRange(meterList, date1, date1)).Returns(listSigmaMeasure); SigmaMeasureFilterStart smfs = new SigmaMeasureFilterStart(); smfs.ISAPProv = isappMock.Object; smfs.SigmaMeasureService = sigmaMeasureServMock.Object; var webApiProvMock = new Mock<IWebAPIProvider>(); webApiProvMock.Setup(s => s.PutJSONMeasureList(It.IsAny<string>(), It.IsAny<string>())).Returns(true); smfs.IWepAPIProv = webApiProvMock.Object; smfs.Plants = new List<Plant>() { p }; smfs.SigmaMeasureFilterBeginningDate = date1; smfs.SigmaMeasureFilterEndingDate = date1; smfs.StartExecution(); List<SMeasure> correctList = new List<SMeasure>(); DateTime d2 = new DateTime(2012, 9, 21, 19, 30, 0, DateTimeKind.Utc); DateTime notIncludedDate = new DateTime(2012, 9, 20, 22, 30, 0, DateTimeKind.Utc); for (DateTime di = new DateTime(2012, 9, 20, 20, 30, 0, DateTimeKind.Utc); di <= d2; di = di.AddHours(1)) { if (di != notIncludedDate) correctList.Add(new SMeasure(p.Id, di, di.Hour, di.Minute, 90,1)); } bool dif = false; if (smfs.ListOfSMeasures.Count != correctList.Count) dif = true; for (int i = 0; i < smfs.ListOfSMeasures.Count && !dif; i++) { SMeasure sm = smfs.ListOfSMeasures[i]; if (!correctList.Contains(sm)) { dif = true; } } Assert.AreEqual(false, dif); }
public void Can_Get_Correct_Data_In_Summer_Daylight_Time_Change_In_Rare_TimeZone() { var timezoneMock = new Mock<TimeZone>(); timezoneMock.Setup(s => s.StandardName).Returns("Iran Standard Time"); Plant p = new Plant() { Id = "PLT1", TimeZone = timezoneMock.Object.StandardName, }; var isappMock = new Mock<ISAPProvider>(); IList<Meter> meterList = new List<Meter>() { new Meter() { IdMeter = "ABAGI01000", LosingRate = 0, Power = 50, IdPlant = p.Id, PowerPercentage = 1 }, new Meter() { IdMeter = "ABAGI01001", LosingRate = 0, Power = 50, IdPlant = p.Id, PowerPercentage = 1 } }; isappMock.Setup(s => s.GetMeterListByPlant(p)).Returns(meterList); IList<SigmaMeasure> listSigmaMeasure = new List<SigmaMeasure>(); DateTime date1 = new DateTime(2012, 9, 21); for (int i = 0; i < 24; i++) { SigmaMeasure sm = new SigmaMeasure() { Id_Meter = "ABAGI01000", NumPeriod = i + 1, ProductionDate = date1, ProductionValue = 50 }; listSigmaMeasure.Add(sm); sm = new SigmaMeasure() { Id_Meter = "ABAGI01001", NumPeriod = i + 1, ProductionDate = date1, ProductionValue = 40 }; listSigmaMeasure.Add(sm); } Mock<SigmaMeasureService> sigmaMeasureServMock = new Mock<SigmaMeasureService>(null); sigmaMeasureServMock.Setup(s => s.GetByMeterListInDateRange(meterList, date1, date1)).Returns(listSigmaMeasure); SigmaMeasureFilterStart smfs = new SigmaMeasureFilterStart(); smfs.ISAPProv = isappMock.Object; smfs.SigmaMeasureService = sigmaMeasureServMock.Object; var webApiProvMock = new Mock<IWebAPIProvider>(); webApiProvMock.Setup(s => s.PutJSONMeasureList(It.IsAny<string>(), It.IsAny<string>())).Returns(true); smfs.IWepAPIProv = webApiProvMock.Object; smfs.Plants = new List<Plant>() { p }; smfs.SigmaMeasureFilterBeginningDate = date1; smfs.SigmaMeasureFilterEndingDate = date1; smfs.StartExecution(); List<SMeasure> correctList = new List<SMeasure>(); for (int i = 20; i < 24; i++) { correctList.Add(new SMeasure(p.Id, date1.AddDays(-1), i, 30, 90,1)); } for (int i = 0; i < 20; i++) { correctList.Add(new SMeasure(p.Id, date1, i, 30, 90,1)); } bool dif = false; if (smfs.ListOfSMeasures.Count != correctList.Count) dif = true; for (int i = 0; i < smfs.ListOfSMeasures.Count && !dif; i++) { SMeasure sm = smfs.ListOfSMeasures[i]; if (!correctList.Contains(sm)) { dif = true; } } Assert.AreEqual(false, dif); }