public void Delete(PmsEteckContext context, bool save) { if (ConsumptionMeters != null) { ConsumptionMeters.ToList().ForEach(f => f.Delete(context, false)); } if (Tickets != null) { foreach (Ticket ticket in Tickets) { ticket.iAddressID = null; context.Entry(ticket).State = EntityState.Modified; } } context.Addresses.Remove(this); //if (save) // context.SaveChanges(_httpContextAccessor.HttpContext.User.Identity.GetUserID()); }
public async Task <ServiceRun> UpdateSDSConsuptionMeter(ConsumptionMeter consumptionMeter, ServiceRun serviceRun) { DateTime today = DateTime.Today; // Check if consumptionMeter exists in api if (await smartDataSolution.ConsumptionMeterExists(consumptionMeter.sEANCode)) { if (consumptionMeter.Counters.Count > 0) { // Get first day from api where data is stored DateTime firstDayInApi = smartDataSolution.ConsumptionMeterAvailableFrom(consumptionMeter.sEANCode); if (firstDayInApi != new DateTime()) { foreach (Counter counter in consumptionMeter.Counters) { counter.Consumption = new List <Consumption>(); // Get lastConsumptionRow from database by this Counter Consumption lastConsumption = db.Consumption.Where(w => w.iCounterKey == counter.iCounterKey).OrderByDescending(o => o.dEndPosition).ThenByDescending(t => t.dtEndDateTime).FirstOrDefault(); if (lastConsumption != null) { // SET the first day for getting consumption DateTime firstPickUpDateTime = lastConsumption.dtEndDateTime; if (firstPickUpDateTime >= firstDayInApi) { // Get last date from api where consumption is stored DateTime lastDayInApi = smartDataSolution.LastAvailableDateTime(consumptionMeter.sEANCode); if ((new int[] { 1, 3, 4 }.Contains(counter.iCounterTypeKey) && smartDataSolution.AssetType == "P4Electricity") || (counter.iCounterTypeKey == 2 && smartDataSolution.AssetType == "P4Gas")) { DateTime lastPickUpDateTime = lastDayInApi < today ? lastDayInApi : today; string webResult = smartDataSolution.GetConsumption(consumptionMeter.sEANCode, firstPickUpDateTime, lastPickUpDateTime); if (!string.IsNullOrEmpty(webResult)) { try { JObject resultObject = JObject.Parse(webResult); JArray resultArray = JArray.Parse(resultObject["Payload"].ToString()); foreach (JToken resultToken in resultArray) { Consumption previousConsumption = counter.Consumption.Count > 0 ? counter.Consumption.OrderByDescending(o => o.dEndPosition).ThenByDescending(o => o.dtEndDateTime).FirstOrDefault() : lastConsumption; decimal endPosition = 0; switch (counter.iCounterTypeKey) { case 2: decimal.TryParse(resultToken["R180"].ToString(), out endPosition); break; case 3: decimal.TryParse(resultToken["R181"].ToString(), out endPosition); break; case 4: decimal.TryParse(resultToken["R182"].ToString(), out endPosition); break; } DateTime endPositionDateTime = DateTime.Parse(resultToken["DateTime"].ToString()); // Deal with correctionFactor if (resultToken == resultArray.First) { counter.dCorrectionMutation = counter.dCorrectionMutation != 0 ? counter.dCorrectionMutation : previousConsumption.dEndPosition - endPosition; } else if (endPositionDateTime > previousConsumption.dtEndDateTime) { counter.Consumption.Add(new Consumption { iAddressKey = counter.ConsumptionMeter.iAddressKey.Value, Counter = counter, ServiceRun = serviceRun, dtStartDateTime = previousConsumption.dtEndDateTime, dtEndDateTime = endPositionDateTime, dConsumption = endPosition - previousConsumption.dEndPosition, dEndPosition = endPosition, bExcludeForReport = counter.ConsumptionMeter.MeterType.sPurchaseOrSale.Contains("Distribution"), bValidated = true }); serviceRun.iServiceRunRowsUpdated++; db.Entry(counter).State = EntityState.Modified; } } } catch (Exception e) { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.InternalServerError, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = e.Message, ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } } else { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.NotFound, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = string.Format("De API heeft een foutmelding gegeven met startdatum {0} en einddatum {1}", firstPickUpDateTime, lastPickUpDateTime), ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } } else { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.NotFound, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = string.Format("Telwerk {0} is geregistreerd met type {1}, maar vanuit de API telt dit telwerk {2}", counter.sCounterCode, counter.CounterType.sCounterTypeDescription, smartDataSolution.AssetType), ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } } else { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.NotFound, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = string.Format("Bij telwerk {0} met type {1} kan geen data opgehaald worden voor {2}. Geprobeerd wordt om verbruik op te halen vanaf {3}.", counter.sCounterCode, counter.CounterType.sCounterTypeDescription, firstDayInApi, firstPickUpDateTime), ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } } else { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.NotFound, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = string.Format("Bij telwerk {0} met type {1} kan geen laatste verbruiksregel opgehaald worden.", counter.sCounterCode, counter.CounterType.sCounterTypeDescription), ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } } } else { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.NotFound, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = "Van deze meter kan geen data opgehaald worden uit de API", ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } } else { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.BadRequest, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = "Bij deze meter zijn op dit moment geen telwerken gevonden", ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } } else { serviceRun.ServiceRunErrors.Add(new ServiceRunError { dtEffectiveDateTime = DateTime.UtcNow, iStatusCode = (int)HttpStatusCode.NotFound, sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = "Meter is niet gevonden in de API", ServiceRun = serviceRun, sProjectNumber = consumptionMeter.Address.Project.ProjectBase.sProjectCode }); serviceRun.iServiceRunStatus = 500; } return(await Task.FromResult(serviceRun)); }
public async Task GetBlindConsumption() { while (true) { Service service = db.Services.Find(7); // Maak een nieuwe servicerun aan ServiceRun serviceRun = new ServiceRun { iServiceKey = 7, dtServiceRunStartDate = DateTime.UtcNow, ServiceRunErrors = new List <ServiceRunError>() }; try { DateTime today = DateTime.Now; // Haal nieuwe accessToken op als de oude verlopen is if (today.AddMinutes(-10) >= FuduraExpiredDate) { GetFuduraAccessToken(); } // Haal alle meters van fudura op die gekoppeld zijn aan een adres en metertype inkoop/distributie/verkoop elektra of gas hebben hebben List <ConsumptionMeter> consumptionMeters = db.ConsumptionMeters .Include(i => i.Counters) .Include(i => i.Counters.Select(s => s.BlindConsumption)) .Where(w => w.iConsumptionMeterSupplierKey == 2 && w.iAddressKey != null && w.Counters.Any(u => u.iCounterTypeKey == 15)) .ToList(); foreach (ConsumptionMeter consumptionMeter in consumptionMeters) { try { DateTime authorizedFromDate = GetFuduraConsumptionMeterAuthorizedFrom(consumptionMeter.sEANCode); DateTime firstPickUpMonth = authorizedFromDate < new DateTime(2016, 1, 1) ? new DateTime(2016, 1, 1) : authorizedFromDate; DateTime lastAvailableDate = GetFuduraLastAvailableData(consumptionMeter.sEANCode); // Haal de blindverbruiksmeter op bij de meter Counter blindConsumptionCounter = consumptionMeter.Counters.FirstOrDefault(f => f.iCounterTypeKey == 15); if (blindConsumptionCounter == null) { throw new Exception(string.Format("Er is geen telwerk gevonden voor het meten van blindverbruik bij meter met EANCode {0}", consumptionMeter.sEANCode)); } // Haal het laatst geregistreerd blindverbruik van het telwerk op BlindConsumption lastRegisteredBlindConsumption = blindConsumptionCounter.BlindConsumption.OrderByDescending(o => o.dtEndDateTime).FirstOrDefault(); if (lastRegisteredBlindConsumption != null) { firstPickUpMonth = lastRegisteredBlindConsumption.dtEndDateTime; } if (firstPickUpMonth <= today.AddMonths(-1)) { decimal dBlindConsumption = 0; WebClient client = new WebClient { Encoding = Encoding.UTF8 }; client.Headers.Add(HttpRequestHeader.Authorization, "bearer " + FuduraAccessToken); client.Headers.Add("Content-type", "application/json"); DateTime firstPickUpDayOfMonth = new DateTime(firstPickUpMonth.Year, firstPickUpMonth.Month, 1); string urlChannels = string.Format("{0}/aansluitingen/{1}/channels/E65_EMVLRx/datapoints/{2}/{3}/{4}", apiFuduraEndPoint, consumptionMeter.sEANCode, firstPickUpMonth.Year, firstPickUpMonth.Month, firstPickUpMonth.Day); string result = client.DownloadString(urlChannels); JArray jsonArray = JArray.Parse(result); foreach (JToken item in jsonArray) { DateTime itemStartDateTime = DateTime.Parse(item["From"].ToString()); DateTime itemEndDateTime = DateTime.Parse(item["To"].ToString()); dBlindConsumption = decimal.Parse(item["ReadingN"].ToString()); if (blindConsumptionCounter.BlindConsumption.Count() != 0) { if (itemStartDateTime > blindConsumptionCounter.BlindConsumption.OrderByDescending(o => o.dtEndDateTime).FirstOrDefault().dtStartDateTime) { BlindConsumption blindConsumption = new BlindConsumption { iAddressKey = consumptionMeter.iAddressKey.Value, Counter = blindConsumptionCounter, dtStartDateTime = itemStartDateTime, dtEndDateTime = itemEndDateTime, dBlindConsumption = dBlindConsumption, ServiceRun = serviceRun }; blindConsumptionCounter.BlindConsumption.Add(blindConsumption); } } else { BlindConsumption blindConsumption = new BlindConsumption { iAddressKey = consumptionMeter.iAddressKey.Value, Counter = blindConsumptionCounter, dtStartDateTime = itemStartDateTime, dtEndDateTime = itemEndDateTime, dBlindConsumption = dBlindConsumption, ServiceRun = serviceRun }; blindConsumptionCounter.BlindConsumption.Add(blindConsumption); } } } } catch (Exception e) { ServiceRunError error = new ServiceRunError { sConsumptionMeterNumber = consumptionMeter.sConsumptionMeterNumber, sErrorMessage = e.Message, iStatusCode = 500, ServiceRun = serviceRun, dtEffectiveDateTime = DateTime.UtcNow }; serviceRun.ServiceRunErrors.Add(error); ServiceRun.iServiceRunStatus = 500; } } int rowsAdded = db.ChangeTracker.Entries().Count(c => c.State == EntityState.Added); serviceRun.dtServiceRunEndDate = DateTime.UtcNow; serviceRun.sServiceRunMessage = rowsAdded + " row(s) added at BlindConsumption."; serviceRun.iServiceRunRowsUpdated = rowsAdded; serviceRun.iServiceRunStatus = serviceRun.ServiceRunErrors.Count > 0 || serviceRun.iServiceRunStatus == 500 ? 500 : 200; if (rowsAdded > 0) { db.ServiceRuns.Add(serviceRun); } db.SaveChanges(); DateTime now = DateTime.Now; DateTime startDate = new DateTime(now.AddMonths(1).Year, now.AddMonths(1).Month, 1).Date.AddHours(5); service.dtNextServiceRun = TimeZoneInfo.ConvertTimeToUtc(startDate, TimeZoneInfo.Local); db.Entry(service).State = EntityState.Modified; db.SaveChanges(); TimeSpan interval = startDate - now; await Task.Delay(interval); } catch (Exception e) { serviceRun.dtServiceRunEndDate = DateTime.UtcNow; serviceRun.sServiceRunMessage = e.Message; serviceRun.iServiceRunStatus = 500; serviceRun.iServiceRunRowsUpdated = 0; db.ServiceRuns.Add(serviceRun); db.SaveChanges(); DateTime now = DateTime.Now; DateTime startDate = now.AddDays(1).Date.AddHours(5); service.dtNextServiceRun = TimeZoneInfo.ConvertTimeToUtc(startDate, TimeZoneInfo.Local); db.Entry(service).State = EntityState.Modified; db.SaveChanges(); TimeSpan interval = startDate - now; await Task.Delay(interval); } } }
// Get all Consumption From SDS Api en save it in the database public async Task GetSDSConsumption() { while (true) { Service service = db.Services.Find(1); // Maak een nieuwe serviceRun aan ServiceRun serviceRun = new ServiceRun { iServiceKey = service.iServiceKey, dtServiceRunStartDate = DateTime.UtcNow, ServiceRunErrors = new List <ServiceRunError>() }; // Maak een lege lijst aan waarin vervolgens het verbruik in gestopt kan worden List <Consumption> consumptionList = new List <Consumption>(); // Deze Hashset lijst wordt gebruikt om het al aanwezige verbruik toe te voege HashSet <Consumption> existedConsumptionList = new HashSet <Consumption>(); try { // Pak de huidige datum DateTime today = DateTime.Now; // Haal alle meters en telwerken op van de meters van SDS die aan een adres gekoppeld zijn. var currentConsumptionMeters = db.ConsumptionMeters .Include(i => i.Counters) .Where(w => w.iConsumptionMeterSupplierKey == 1 && w.iAddressKey != null).ToList(); //Draai een loop af voor elke meter foreach (ConsumptionMeter meter in currentConsumptionMeters) //foreach (ConsumptionMeter meter in currentConsumptionMeters) { // Check of consumptionMeter exist in API SmartDataSolution _sds = new SmartDataSolution(); if (await _sds.ConsumptionMeterExists(meter.sEANCode)) { // Check of de meter ook telwerken heeft if (meter.Counters.Count == 0) { throw new Exception(string.Format("Er zijn nog geen telwerken gevonden voor de meter met EANCode {0}", meter.sEANCode)); } // Haal de eerste beschikbare datum op van de meter DateTime dataAvailableFromDate = GetSDSConsumptionMeterAvailableFrom(meter.sEANCode); if (dataAvailableFromDate != new DateTime()) { // Loop elk telwerk af foreach (Counter counter in meter.Counters.Where(w => new int[] { 2, 3, 4 }.Contains(w.iCounterTypeKey))) { Consumption lastConsumption = db.Consumption.Where(w => w.iCounterKey == counter.iCounterKey).OrderByDescending(o => o.dtEndDateTime).ThenByDescending(t => t.dEndPosition).FirstOrDefault(); if (lastConsumption == null) { throw new Exception(string.Format("Voor telwerk {0} is geen verbruiksregel geregistreerd.", string.Join(", ", counter.sCounterCode))); } // Voeg de regel toe aan de HashSet existedConsumptionList.Add(lastConsumption); // Wat is de laatste datum van het verbruik DateTime firstPickUpDay = lastConsumption.dtEndDateTime; if (firstPickUpDay < dataAvailableFromDate) { throw new Exception(string.Format("Meter {0} is geauthorizeerd vanaf {1} en er wordt geprobeerd data op te halen vanaf {2}.", meter.sEANCode, dataAvailableFromDate.Date, firstPickUpDay.Date)); } // Haal laatst beschikbare datum op uit de webservice DateTime lastAvailableData = GetSDSLastAvailableData(meter.sEANCode); switch (counter.iCounterTypeKey) { case 1: //Check of ws ook elektra meet if (AssetType != "P4Electricity") { throw new Exception(string.Format("Vanuit Database verwachten we bij teller {1} voor elektra en we krijgen nu een meter die {0} meet.", AssetType, counter.iCounterKey)); } break; case 2: //Check of ws ook gas meet if (AssetType != "P4Gas") { throw new Exception(string.Format("Vanuit Database verwachten we bij teller {1} voor elektra en we krijgen nu een meter die {0} meet.", AssetType, counter.iCounterKey)); } break; case 3: //Check of ws ook elektra meet if (AssetType != "P4Electricity") { throw new Exception(string.Format("Vanuit Database verwachten we bij teller {1} voor elektra en we krijgen nu een meter die {0} meet.", AssetType, counter.iCounterKey)); } break; case 4: //Check of ws ook elektra meet if (AssetType != "P4Electricity") { throw new Exception(string.Format("Vanuit Database verwachten we bij teller {1} voor elektra en we krijgen nu een meter die {0} meet.", AssetType, counter.iCounterKey)); } break; } // Check tot welke datum opgehaald moet worden (vandaag of laatste registratiedatum) DateTime lastPickUpDateTime = lastAvailableData < today ? lastAvailableData : today.Date; TimeSpan timeSpan = lastPickUpDateTime - firstPickUpDay; string urlConsumption = string.Format("{0}readings/Identifier/{1}/Day/{2}?apikey={3}&dateto={4}&datetimeformat=nl&format=json&source=day", apiSDSEndPoint, meter.sEANCode, firstPickUpDay.ToString("yyyy-MM-dd"), SDSApiKey, lastPickUpDateTime.ToString("yyyy-MM-dd")); try { WebClient client = new WebClient { Encoding = Encoding.UTF8 }; string resultString = client.DownloadString(urlConsumption); JObject resultObject = JObject.Parse(resultString); JArray jsonArray = JArray.Parse(resultObject["Payload"].ToString()); foreach (JToken consumption in jsonArray) { Consumption previousConsumption = consumptionList.Where(w => w.Counter == counter).OrderByDescending(o => o.dtEndDateTime).FirstOrDefault() != null?consumptionList.Where(w => w.Counter == counter).OrderByDescending(o => o.dtEndDateTime).FirstOrDefault() : existedConsumptionList.Where(w => w.Counter == counter).OrderByDescending(o => o.dtEndDateTime).FirstOrDefault(); decimal ApiEndPosition = 0; switch (counter.iCounterTypeKey) { case 2: ApiEndPosition = decimal.Parse(consumption["R180"].ToString()); break; case 3: ApiEndPosition = decimal.Parse(consumption["R181"].ToString()); break; case 4: ApiEndPosition = decimal.Parse(consumption["R182"].ToString()); break; default: break; } DateTime consumptionDateTime = DateTime.Parse(consumption["DateTime"].ToString()); // Set the correctionfactor if (consumption == jsonArray.First) { counter.dCorrectionMutation = counter.dCorrectionMutation != 0 ? counter.dCorrectionMutation : previousConsumption.dEndPosition - ApiEndPosition; } else if (consumptionDateTime > previousConsumption.dtEndDateTime) { // Set correctionEndPosition ApiEndPosition = ApiEndPosition + counter.dCorrectionMutation; Consumption newConsumption = new Consumption { iAddressKey = counter.ConsumptionMeter.iAddressKey.Value, Counter = counter, ServiceRun = serviceRun, dtStartDateTime = previousConsumption.dtEndDateTime, dtEndDateTime = consumptionDateTime, dConsumption = ApiEndPosition - previousConsumption.dEndPosition, dEndPosition = ApiEndPosition, bExcludeForReport = counter.ConsumptionMeter.MeterType.sPurchaseOrSale.Contains("Distribution"), bValidated = true }; consumptionList.Add(newConsumption); } } } catch (Exception e) { ServiceRunError error = new ServiceRunError { dtEffectiveDateTime = DateTime.Now, iStatusCode = 500, sConsumptionMeterNumber = counter.ConsumptionMeter.sConsumptionMeterNumber, sErrorMessage = e.Message, ServiceRun = serviceRun }; serviceRun.ServiceRunErrors.Add(error); serviceRun.iServiceRunStatus = 500; } } // End of foreach counter } else { ServiceRunError error = new ServiceRunError { ServiceRun = serviceRun, dtEffectiveDateTime = DateTime.Now, iStatusCode = 500, sConsumptionMeterNumber = meter.sConsumptionMeterNumber, sErrorMessage = "Er kan geen data uit de API gelezen worden voor de meter" }; serviceRun.ServiceRunErrors.Add(error); serviceRun.iServiceRunStatus = 500; } } else { ServiceRunError serviceRunError = new ServiceRunError { iStatusCode = 500, sErrorMessage = string.Format("Meter met EAN-Code {0} kan niet gevonden worden in de API", meter.sEANCode), sConsumptionMeterNumber = meter.sConsumptionMeterNumber, ServiceRun = serviceRun, }; serviceRun.ServiceRunErrors.Add(serviceRunError); serviceRun.iServiceRunStatus = 500; } } // End of foreach meter //Voeg de hele lijst toe aan de database db.Consumption.AddRange(consumptionList); int rowsAdded = db.ChangeTracker.Entries().Count(c => c.State == EntityState.Added); serviceRun.dtServiceRunEndDate = DateTime.UtcNow; serviceRun.sServiceRunMessage = rowsAdded + " row(s) updated."; serviceRun.iServiceRunRowsUpdated = rowsAdded; serviceRun.iServiceRunStatus = serviceRun.iServiceRunStatus == 500 ? 500 : 200; if (rowsAdded > 0) { db.ServiceRuns.Add(serviceRun); } db.SaveChanges(); currentConsumptionMeters.Clear(); //Check invoeren over saldo van afgelopen dag/maand zelfde als ws if (today.Day == 1) { //Checks invoeren } DateTime now = DateTime.Now; DateTime startDate = now.AddDays(1).Date.AddHours(5); service.dtNextServiceRun = TimeZoneInfo.ConvertTimeToUtc(startDate, TimeZoneInfo.Local); db.Entry(service).State = EntityState.Modified; db.SaveChanges(); TimeSpan interval = startDate - now; await Task.Delay(interval); } catch (Exception e) { serviceRun.dtServiceRunEndDate = DateTime.UtcNow; serviceRun.sServiceRunMessage = e.Message; serviceRun.iServiceRunStatus = 500; serviceRun.iServiceRunRowsUpdated = 0; // Verwijder de lijst als aanpassingen hebben plaatsgevonden if (db.ChangeTracker.HasChanges()) { db.Consumption.RemoveRange(consumptionList); } db.ServiceRuns.Add(serviceRun); db.SaveChanges(); DateTime now = DateTime.Now; DateTime startDate = now.AddDays(1).Date.AddHours(5); service.dtNextServiceRun = TimeZoneInfo.ConvertTimeToUtc(startDate, TimeZoneInfo.Local); db.Entry(service).State = EntityState.Modified; db.SaveChanges(); TimeSpan interval = startDate - now; await Task.Delay(interval); } } }
static void Main(string[] args) { Console.WriteLine("Service is gestart."); PmsEteckContext context = new PmsEteckContext(); Console.WriteLine("Verbinding met de database is tot stand gebracht."); Console.WriteLine(string.Format("De volgende argumenten hebben we binnen gekregen: {0}.", string.Join(", ", args))); List <string> serviceNames = args.ToList(); Console.WriteLine("De omzetting van de argumenten is gelukt."); Console.WriteLine("Alle services worden opgehaald vanuit de databases."); List <Service> services = context.Services.Where(w => serviceNames.Contains(w.sServiceName)).ToList(); Console.WriteLine("Voor de volgende services ({0}) wordt er een nieuwe servicerun gestart", string.Join(", ", services.Select(s => s.sServiceName))); foreach (Service service in services) { Console.WriteLine("We zijn gestart met de servicerun voor service " + service.sServiceName); ServiceRun serviceRun = new ServiceRun(); switch (service.iServiceKey) { case 16: case 19: List <Counter> countersForUpdate = context.Counters .Where(w => w.iConsumptionMeterKey.HasValue && w.ConsumptionMeter.iConsumptionMeterSupplierKey == 6 && w.ConsumptionMeter.iAddressKey.HasValue && w.CounterType.bCanExchange).ToList(); Console.WriteLine("In totaal zullen er " + countersForUpdate.Count + " telwerken bijgewerkt moeten worden."); service.NewServiceRunAsync(countersForUpdate, context).Wait(); serviceRun = service.NewServiceRunAsync(countersForUpdate, context).Result; break; case 20: countersForUpdate = context.Counters .Where(w => w.iConsumptionMeterKey.HasValue && w.ConsumptionMeter.iConsumptionMeterSupplierKey == 4 && w.ConsumptionMeter.iAddressKey.HasValue && w.ConsumptionMeter.Address.ObjectID.HasValue) .ToList(); Console.WriteLine("In totaal zullen er " + countersForUpdate.Count + " bijgewerkt moeten worden."); service.NewServiceRunAsync(countersForUpdate, context).Wait(); serviceRun = service.NewServiceRunAsync(countersForUpdate, context).Result; break; default: break; } Console.WriteLine("Moment voor de volgende servicerun wordt ingesteld."); service.dtNextServiceRun = service.iServiceKey == 16 ? DateTime.Today.AddHours(38).ToUniversalTime() : DateTime.Today.AddHours(44).ToUniversalTime(); context.Entry(service).State = EntityState.Modified; Console.WriteLine("De servicerun voor " + service.sServiceName + " is afgerond."); Console.WriteLine("De volgende run voor " + service.sServiceName + " is" + service.dtNextServiceRun + " ."); } Console.WriteLine("Alle serviceruns zijn aangemaakt en verwerkt. De gegevens worden opgeslagen in de database."); try { context.SaveChanges(); Console.WriteLine("Gegevens zijn goed opgeslagen"); } catch (Exception ex) { Console.WriteLine("Het ging niet goed met het opslaan van de gegevens. De volgende melding hebben we ontvangen: " + ex.Message); } }