Esempio n. 1
0
        public Task AddConsumption(DateTime dateTime, Counter counter, decimal position)
        {
            ServiceRun serviceRun = new ServiceRun {
                iServiceKey           = 3,
                dtServiceRunStartDate = DateTime.Now
            };
            // Get all Consumption
            Consumption lastConsumption = db.Consumption.Where(w => w.iCounterKey == counter.iCounterKey).OrderByDescending(o => o.dtEndDateTime).FirstOrDefault();

            // Check of datetime is higher than last consumption
            bool isHigherDateTime = dateTime > lastConsumption.dtEndDateTime;

            if (isHigherDateTime)
            {
                if (position >= lastConsumption.dEndPosition)
                {
                    var newConsumption = new Consumption
                    {
                        Counter           = counter,
                        dtStartDateTime   = lastConsumption.dtEndDateTime,
                        dtEndDateTime     = dateTime,
                        dEndPosition      = position,
                        dConsumption      = position - lastConsumption.dEndPosition,
                        iAddressKey       = lastConsumption.iAddressKey,
                        bExcludeForReport = counter.ConsumptionMeter.MeterType.sPurchaseOrSale.Contains("Distribution"),
                        bValidated        = true,
                        ServiceRun        = serviceRun
                    };

                    db.Consumption.Add(newConsumption);

                    serviceRun.dtServiceRunEndDate    = DateTime.Now;
                    serviceRun.iServiceRunStatus      = 200;
                    serviceRun.iServiceRunRowsUpdated = 1;
                    serviceRun.sServiceRunMessage     = "1 row added.";

                    db.SaveChanges();

                    return(Task.FromResult(1));
                }
            }

            return(Task.FromResult(0));
        }
Esempio n. 2
0
        public void Delete(PmsEteckContext context, bool save)
        {
            if (Counters.Count > 0)
            {
                //foreach (Consumption consumption in Counters.SelectMany(s => s.Consumption))
                //{
                //    context.Consumption.Attach(consumption);
                //    context.Consumption.Remove(consumption);
                //}
                context.Consumption.RemoveRange(Counters.SelectMany(s => s.Consumption));
                context.BlindConsumptions.RemoveRange(Counters.SelectMany(s => s.BlindConsumption));
                context.MaximumPowers.RemoveRange(Counters.SelectMany(s => s.MaximumPowers));
                context.CounterChangeLogs.RemoveRange(Counters.SelectMany(s => s.ChangeLogs));
                context.Counters.RemoveRange(Counters);
            }
            context.MeterChangeLogs.RemoveRange(MeterChangeLogs);
            context.ConsumptionMeters.Remove(this);

            if (save)
            {
                context.SaveChanges(_httpContextAccessor.HttpContext.User.Identity.GetUserID());
            }
        }
Esempio n. 3
0
        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);
                }
            }
        }
Esempio n. 4
0
        public int GenerateBudgetDimensionMonthPreview(BudgetDimensionYearPreviewViewModel model)
        {
            int budgetDimensionKey = 0;

            bool projectHasFixedPart = false;


            try
            {
                BudgetBase budgetBase = db.BudgetBases
                                        .FirstOrDefault(f => f.iBudgetBaseKey == model.iBudgetBaseKey);

                BudgetSetting budgetSettings = db.BudgetSettings
                                               .Include(i => i.BudgetSectionIndex)
                                               .Include(i => i.BudgetSectionIndex.Select(s => s.ReportingStructure))
                                               .Include(i => i.MonthDegreeDayIndex)
                                               .OrderByDescending(o => o.iBudgetSettingKey)
                                               .FirstOrDefault();

                // Create the BudgetDimension
                BudgetDimension budgetDimension = new BudgetDimension
                {
                    iBudgetBaseKey              = model.iBudgetBaseKey,
                    bDraft                      = true,
                    BudgetSetting               = budgetSettings,
                    iBudgetDimensionTypeKey     = model.iBudgetDimensionTypeKey,
                    iProjectKey                 = model.iProjectKey,
                    iYearBudget                 = model.iYearBudget,
                    iYearPreview                = model.iYearPreview,
                    iEndPeriodPreview           = model.iEndPeriodPreview,
                    sBudgetDimensionDescription = model.sDescription,
                    dtLastModified              = DateTime.UtcNow,
                    BudgetDimensionRules        = new Collection <BudgetDimensionRule>()
                };

                if (model.iProjectKey.HasValue)
                {
                    ProjectInfo projectInfo = db.ProjectInfo.FirstOrDefault(f => f.iFinProjectKey == model.iProjectKey);

                    if (projectInfo != null)
                    {
                        int[] gasKeys = db.TechnicalPrincipals.Where(w => w.bIsGas).Select(s => s.iTechnicalPrincipalKey).ToArray();
                        projectHasFixedPart = projectInfo.bHotWater || (projectInfo.iTechnicalPrincipalMainKey.HasValue && gasKeys.Contains(projectInfo.iTechnicalPrincipalMainKey.GetValueOrDefault()));
                        projectHasFixedPart = !projectHasFixedPart?projectInfo.iTechnicalPrincipalSub1Key.HasValue?gasKeys.Contains(projectInfo.iTechnicalPrincipalSub1Key.Value) : false : projectHasFixedPart;

                        projectHasFixedPart = !projectHasFixedPart?projectInfo.iTechnicalPrincipalSub2Key.HasValue?gasKeys.Contains(projectInfo.iTechnicalPrincipalSub2Key.Value) : false : projectHasFixedPart;
                    }
                }

                //Check of er gekozen is voor een DCF
                if (budgetBase.iBudgetBaseTypeKey == 1)
                {
                    //Hierbij is gekozen voor een DCF Hierbij hoeft geen verdeling over maanden plaats te vinden
                    foreach (BudgetSectionYearPreviewViewModel item in model.BudgetSections)
                    {
                        BudgetDimensionRule budgetDimensionRule = new BudgetDimensionRule
                        {
                            bSpatie                = item.bSpatie,
                            bSubtotaal             = item.bSubtotaal,
                            dJanuary               = item.dSuggestion.HasValue ? item.dSuggestion.Value : 0,
                            dFebruary              = 0,
                            dMarch                 = 0,
                            dApril                 = 0,
                            dMay                   = 0,
                            dJune                  = 0,
                            dJuly                  = 0,
                            dAugust                = 0,
                            dSeptember             = 0,
                            dOctober               = 0,
                            dNovember              = 0,
                            dDecember              = 0,
                            dTotal                 = !item.bSpatie && !item.bSubtotaal ? item.dSuggestion.HasValue ? item.dSuggestion.Value : 0 : 0,
                            iRecNo                 = item.iRecNo,
                            iReportingStructureKey = item.iReportingStructureKey,
                            sComment               = item.sComment
                        };

                        budgetDimension.BudgetDimensionRules.Add(budgetDimensionRule);
                    }
                }
                else
                {
                    // Hier wordt het bedrag over de maanden uitgesmeerd! Niet nodig voor begroting van DCF.
                    foreach (BudgetSectionYearPreviewViewModel item in model.BudgetSections)
                    {
                        BudgetDimensionRule budgetDimensionRule = new BudgetDimensionRule
                        {
                            bSpatie                = item.bSpatie,
                            bSubtotaal             = item.bSubtotaal,
                            dJanuary               = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 1, budgetSettings.MonthDegreeDayIndex),
                            dFebruary              = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 2, budgetSettings.MonthDegreeDayIndex),
                            dMarch                 = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 3, budgetSettings.MonthDegreeDayIndex),
                            dApril                 = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 4, budgetSettings.MonthDegreeDayIndex),
                            dMay                   = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 5, budgetSettings.MonthDegreeDayIndex),
                            dJune                  = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 6, budgetSettings.MonthDegreeDayIndex),
                            dJuly                  = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 7, budgetSettings.MonthDegreeDayIndex),
                            dAugust                = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 8, budgetSettings.MonthDegreeDayIndex),
                            dSeptember             = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 9, budgetSettings.MonthDegreeDayIndex),
                            dOctober               = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 10, budgetSettings.MonthDegreeDayIndex),
                            dNovember              = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 11, budgetSettings.MonthDegreeDayIndex),
                            dDecember              = CalculateMonthSuggestion(item.dSuggestion.HasValue ? item.dSuggestion.Value : 0, budgetSettings.BudgetSectionIndex.FirstOrDefault(f => f.iBudgetSectionIndexKey == item.iBudgetSectionIndexKey), projectHasFixedPart, 12, budgetSettings.MonthDegreeDayIndex),
                            dTotal                 = !item.bSpatie && !item.bSubtotaal ? item.dSuggestion.HasValue ? item.dSuggestion.Value : 0 : 0,
                            iRecNo                 = item.iRecNo,
                            iReportingStructureKey = item.iReportingStructureKey,
                            sComment               = item.sComment
                        };

                        budgetDimensionRule.dDecember = item.dSuggestion.GetValueOrDefault() -
                                                        budgetDimensionRule.dJanuary -
                                                        budgetDimensionRule.dFebruary -
                                                        budgetDimensionRule.dMarch -
                                                        budgetDimensionRule.dApril -
                                                        budgetDimensionRule.dMay -
                                                        budgetDimensionRule.dJune -
                                                        budgetDimensionRule.dJuly -
                                                        budgetDimensionRule.dAugust -
                                                        budgetDimensionRule.dSeptember -
                                                        budgetDimensionRule.dOctober -
                                                        budgetDimensionRule.dNovember;

                        budgetDimension.BudgetDimensionRules.Add(budgetDimensionRule);
                    }
                }

                db.BudgetDimensions.Add(budgetDimension);
                db.SaveChanges();

                budgetDimensionKey = budgetDimension.iBudgetDimensionKey;
            }
            catch (Exception e)
            {
                throw e;
            }

            return(budgetDimensionKey);
        }
Esempio n. 5
0
        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);
            }
        }