Example #1
0
        /// <summary>
        /// Deletes all logs of specific type that are older than date range
        ///
        /// Log format: [Date].[Optional:Something].[LogType].txt
        /// </summary>
        /// <param name="retention"></param>
        /// <param name="folder"></param>
        /// <param name="logType"></param>
        /// <returns></returns>
        private List <SystemTaskResult> DeleteLogsByType(TimeSpan retention, string folder, string logType)
        {
            List <SystemTaskResult> results = new List <SystemTaskResult>();

            try
            {
                DateTime     minEventDate       = DateTime.UtcNow.Subtract(retention);
                const string eventLogDateFormat = "dd-MM-yyyy";
                Dictionary <string, string> fileNamePatternByLogType = FileNamePatternByLogType;
                if (Directory.Exists(folder))
                {
                    foreach (string logFile in GetLogsByType(folder, logType, fileNamePatternByLogType[logType]))
                    {
                        DateTime eventsDate = DateHelper.GetDate(Path.GetFileNameWithoutExtension(logFile), eventLogDateFormat);
                        if (eventsDate < minEventDate)
                        {
                            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, string.Format("Deleting {0} log {1}", logType, Path.GetFileName(logFile))));
                            File.Delete(logFile);
                            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, string.Format("Deleted {0} log {1}", logType, Path.GetFileName(logFile))));
                        }
                    }
                }
            }
            catch (System.Exception exception)
            {
                results.Add(new SystemTaskResult(SystemTaskResult.ResultTypes.Error, this.Id, string.Format("Error deleting logs for type {0}: {1}", logType, exception.Message)));
            }
            return(results);
        }
 /// <summary>
 /// It is called dynamically.
 /// </summary>
 public async Task Execute(CancellationToken cancellationToken, AutoBook autoBook)
 {
     try
     {
         try
         {
             _autoBooks.Create(autoBook);
             _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                  $"Creating AutoBook instance (AutoBookID={autoBook.Id}): Waiting for Idle notification"));
         }
         catch (Exception ex)
         {
             _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0,
                                                                                         $"Error creating AutoBook (AutoBookID={autoBook.Id})", ex));
             autoBook.Status = AutoBookStatuses.Fatal_Error;
             _autoBookRepository.Update(autoBook);
         }
     }
     finally
     {
         foreach (var dbContext in _tenantDbContexts)
         {
             try
             {
                 await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
             }
             catch //ignore exception
             {
             }
         }
     }
 }
        public CampaignsReqmOutput ProcessFile(Guid scenarioId, string folder)
        {
            string pathToFile = FileHelpers.GetPathToFileIfExists(folder, FileName);
            var    result     = new CampaignsReqmOutput();

            if (String.IsNullOrEmpty(pathToFile))
            {
                _audit.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, $"File {pathToFile} was not found."));

                return(result);
            }

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processing output file {pathToFile}"));

            var importSettings = CSVImportSettings.GetImportSettings(pathToFile, typeof(CampaignsReqmHeaderMap), typeof(CampaignsReqmIndexMap));

            ICampaignsReqmImportRepository _fileReader = new CSVCampaignsReqmImportRepository(importSettings);

            var data = _fileReader.GetAll().ToList();

            result.Data = _mapper.Map <IEnumerable <CampaignsReqm> >(data);

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processed output file {pathToFile}"));

            return(result);
        }
        private void PreGenerateReport(List <ScenarioCampaignLevelResultItem> data, Run run, Scenario scenario)
        {
            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                 0, $"Start scenario campaign level results report generation. ScenarioId: {scenario.Id} Count: {data.Count}"));
            try
            {
                _campaignResultReportCreator.EnablePerformanceKPIColumns(_includeScenarioPerformanceMeasurementKpIs);
                _campaignResultReportCreator.EnableCampaignLevel(!_saveData);
                string fileName = ReportFileNameHelper.ScenarioCampaignResult(scenario, run.ExecuteStartedDateTime.Value);

                using (var reportStream = _campaignResultReportCreator.GenerateReport(() =>
                                                                                      ScenarioCampaignResultReportHelper.MapToExtendedResults(data, scenario.CampaignPassPriorities, _mapper)))
                {
                    _ = _cloudStorage.Upload(new S3UploadComment
                    {
                        BucketName          = _awsSettings.S3Bucket,
                        DestinationFilePath = fileName,
                        FileStream          = reportStream
                    });
                }
            }
            catch (Exception e)
            {
                _auditEventRepository.Insert(
                    AuditEventFactory.CreateAuditEventForException(
                        0,
                        0,
                        $"Error while generating report for scenario campaign level results. ScenarioId: {scenario.Id}", e
                        )
                    );
                throw;
            }
            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                 0, $"End scenario campaign level results report generation. ScenarioId: {scenario.Id}"));
        }
        public IEnumerable <ConversionEfficiency> Process(string pathToFile)
        {
            if (!File.Exists(pathToFile))
            {
                _audit?.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, "File was not found."));

                return(Enumerable.Empty <ConversionEfficiency>());
            }

            _audit?.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                   0, $"Processing output file {pathToFile}"));

            try
            {
                var importSettings = CSVImportSettings.GetImportSettings(pathToFile, typeof(ConversionEfficiencyHeaderMap), typeof(ConversionEfficiencyIndexMap));

                var conversionEfficiency = new CSVConversionEfficiencyImportRepository(importSettings);

                var data = conversionEfficiency.GetAll();

                var output = _mapper.Map <IEnumerable <ConversionEfficiency> >(data);

                _audit?.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                       0, $"Processed output file {pathToFile}"));

                return(output);
            }
            catch (Exception exception)
            {
                _audit?.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, $"Error processing file {pathToFile}", exception));

                return(Enumerable.Empty <ConversionEfficiency>());
            }
        }
Example #6
0
        public void ProcessScenarioCampaignMetrics(Guid runId, Guid scenarioId, IEnumerable <Recommendation> scenarioRecommendations)
        {
            try
            {
                var scenarioCampaignMetrics = new ScenarioCampaignMetric
                {
                    Id      = scenarioId,
                    Metrics = GenerateCampaignKPIs(runId, scenarioId, scenarioRecommendations)
                };

                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"Start insert of scenario campaign metrics. ScenarioId: {scenarioId} Count: {scenarioCampaignMetrics.Metrics.Count}"));

                using (var innerScope = _repositoryFactory.BeginRepositoryScope())
                {
                    var scenarioCampaignMetricRepository = innerScope.CreateRepository <IScenarioCampaignMetricRepository>();
                    scenarioCampaignMetricRepository.AddOrUpdate(scenarioCampaignMetrics);
                    scenarioCampaignMetricRepository.SaveChanges();
                }

                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"End insert of scenario campaign metrics. ScenarioId: {scenarioId} Count: {scenarioCampaignMetrics.Metrics.Count}"));
            }
            catch (Exception e)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, $"Error while processing scenario campaign metrics. ScenarioId: {scenarioId}", e));
            }
        }
Example #7
0
        /// <summary>
        /// Deletes SpotPlacement docs for dead spots, not modified for more than N days
        /// </summary>
        /// <returns></returns>
        private List <SystemTaskResult> DeleteSpotPlacements(TimeSpan spotPlacementRetention)
        {
            List <SystemTaskResult> results = new List <SystemTaskResult>();

            if (spotPlacementRetention.Ticks != 0)
            {
                try
                {
                    using (var scope = _repositoryFactory.BeginRepositoryScope())
                    {
                        _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, string.Format("Deleting spot placements (Days Old={0})", spotPlacementRetention.TotalDays)));
                        var spotPlacementRepository = scope.CreateRepository <ISpotPlacementRepository>();

                        DateTime modifiedBefore = DateTime.UtcNow.Subtract(spotPlacementRetention);
                        spotPlacementRepository.DeleteBefore(modifiedBefore);
                        _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, "Deleted spot placements"));
                    }
                }
                catch (System.Exception exception)
                {
                    results.Add(new SystemTaskResult(SystemTaskResult.ResultTypes.Error, this.Id, string.Format("Error deleting spot placements: {0}", exception.Message)));
                }
            }
            return(results);
        }
Example #8
0
        /// <summary>
        /// Executes systems task
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public List<SystemTaskResult> ExecuteTask(string taskId)
        {
            var allSystemTaskResults = new List<SystemTaskResult>();
            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, String.Format("Executing system task {0}", taskId)));

            try
            {
                // Get task to run
                var systemTask = GetSystemTasks().Where(mt => mt.Id == taskId).First();
                var systemTaskResults = systemTask.Execute();
                allSystemTaskResults.AddRange(systemTaskResults);

                // Log results
                foreach (var systemTaskResult in systemTaskResults)
                {
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, String.Format("System task result for {0}: {1}: {2}", taskId, systemTaskResult.ResultType, systemTaskResult.Message)));
                }
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, String.Format("Executed system task {0}", taskId)));
            }
            catch (System.Exception exception)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, String.Format("Error executing system task {0}", taskId), exception));
                throw;
            }
            return allSystemTaskResults;
        }
        public ProcessBreakEfficiencyOutput ProcessFile(Guid scenarioId, string folder)
        {
            var output             = new ProcessBreakEfficiencyOutput();
            var run                = _dataSnapshot.Run.Value;
            var efficiencySettings = _efficiencySettingsRepository.GetDefault();

            if (!run.Manual || run.Manual && efficiencySettings.PersistEfficiency == PersistEfficiency.AllRun)
            {
                if (scenarioId == run.Scenarios.OrderBy(c => c.Id).First().Id)
                {
                    try
                    {
                        output = ProcessFileInternal(scenarioId, folder);
                    }
                    catch (Exception exception)
                    {
                        _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, $"Error processing Break Efficiency", exception));
                    }
                }
                else
                {
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, $"Ignoring break efficiency because it should only be processed once for the run"));
                }
            }

            return(output);
        }
        public async Task Execute(Guid runId)
        {
            var runCompleted = false;

            try
            {
                runCompleted = await WaitForRunCompletedAsync(runId).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0,
                                                                                            $"Completed run notification error (RunID={runId})", ex));
            }
            finally
            {
                if (runCompleted)
                {
                    _runManager.CreateNotificationForCompletedRun(_run);
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                         $"Completed run notification has sent (RunID={runId})"));
                }
                else
                {
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0,
                                                                                                     $"Completed run notification warning, Run not found (RunID={runId})"));
                }
            }
        }
        public ScenarioCampaignLevelResult ProcessFile(Guid scenarioId, string folder)
        {
            string pathToFile = FileHelpers.GetPathToFileIfExists(folder, FileName);

            var result = new ScenarioCampaignLevelResult {
                Id = scenarioId
            };

            if (string.IsNullOrEmpty(pathToFile))
            {
                _audit.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, $"File {pathToFile} was not found."));

                return(result);
            }

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processing output file {pathToFile}"));

            var importSettings = CSVImportSettings.GetImportSettings(pathToFile, typeof(ScenarioCampaignLevelResultHeaderMap), typeof(ScenarioCampaignLevelResultIndexMap));
            IScenarioCampaignLevelResultsImportRepository repository = new CSVScenarioCampaignLevelResultsImportRepository(importSettings);

            var data = repository.GetAll();

            result.Items = _mapper.Map <List <ScenarioCampaignLevelResultItem> >(data);

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processed output file {pathToFile}"));

            return(result);
        }
Example #12
0
        public Failures ProcessFile(Guid scenarioId, string folder)
        {
            string pathToFile = FileHelpers.GetPathToFileIfExists(folder, FileName);
            var    failures   = new Failures {
                Id = scenarioId
            };

            if (string.IsNullOrEmpty(pathToFile))
            {
                _audit.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, $"File {pathToFile} was not found."));

                return(failures);
            }

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processing output file {pathToFile}"));

            var importSettings = CSVImportSettings.GetImportSettings(pathToFile, typeof(FailureHeaderMap), typeof(FailureIndexMap));

            var campaignsIndex = _dataSnapshot.AllCampaigns.Value.ToDictionary(c => (long)c.CustomId);
            var salesAreaIndex = _dataSnapshot.AllSalesAreas.Value.ToDictionary(c => c.CustomId);

            IFailureImportRepository failureRepository = new CSVFailureImportRepository(importSettings);

            foreach (var summary in failureRepository.GetAll())
            {
                var failure = new Failure();

                if (!campaignsIndex.TryGetValue(summary.Campaign, out var campaign))
                {
                    failure.ExternalId = failure.CampaignName = "Unknown";
                }
                else
                {
                    failure.ExternalId   = campaign.ExternalId;
                    failure.CampaignName = campaign.Name;
                }

                failure.Type     = summary.Type;
                failure.Failures = summary.Failures;
                failure.Campaign = summary.Campaign;

                failure.SalesAreaName = !salesAreaIndex.TryGetValue(summary.SalesAreaNumberOfBooking, out var salesArea)
                    ? "Unknown"
                    : salesArea.Name;

                failures.Items.Add(failure);
            }

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processed output file {pathToFile}"));

            return(failures);
        }
Example #13
0
        public List <SystemTaskResult> Execute()
        {
            IReadOnlyCollection <Run> GetRunsToDeleteForLastNDays(DateTime minCreatedDate)
            {
                using (var scope = _repositoryFactory.BeginRepositoryScope())
                {
                    var runRepository = scope.CreateRepository <IRunRepository>();

                    return(runRepository.GetAll()
                           .Where(r => r.CreatedDateTime.Year > 2000 && r.CreatedDateTime < minCreatedDate)
                           .OrderBy(r => r.CreatedDateTime)
                           .ToList());
                }
            }

            DateTime minCreated            = DateTime.UtcNow.Subtract(_runRetention);
            IReadOnlyCollection <Run> runs = GetRunsToDeleteForLastNDays(minCreated);

            var results = new List <SystemTaskResult>();

            foreach (var run in runs)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                     $"Deleting run {run.Id} ({run.Description})"
                                                                                                     ));

                try
                {
                    Run.ValidateForDelete(run);

                    _runManager.DeleteRun(run.Id);

                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForRunDeleted(0, 0, run.Id, null));
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                         $"Deleted run {run.Id} ({run.Description})"
                                                                                                         ));
                }
                catch (Exception exception)
                {
                    results.Add(
                        new SystemTaskResult(SystemTaskResult.ResultTypes.Error, Id,
                                             $"Error deleting run {run.Id} ({run.Description}): {exception.Message}"
                                             )
                        );
                }
            }

            return(results);
        }
Example #14
0
        public override void Log(ExceptionLoggerContext context)
        {
            if (context.Exception == null)
            {
                return;
            }

            _logger.LogError(context.Exception, "application exception");

            try
            {
                _auditEventRepository.Insert(
                    AuditEventFactory.CreateAuditEventForException(
                        tenantId: 0,
                        userId: 0,
                        message: GetAuditInfo(context),
                        exception: context.Exception));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "auditevent insert exception"); // hope unreachable code
            };

            base.Log(context);
        }
Example #15
0
        public IHttpActionResult Post([FromBody] CreateAuditEventModel command)
        {
            if (command == null || !ModelState.IsValid)
            {
                return(this.Error().InvalidParameters("Audit event body parameters missing"));
            }

            List <AuditEventValueType> valueTypes = new AuditEventValueTypeRepository().GetAll();

            var auditEvent = new AuditEvent()
            {
                ID          = Guid.NewGuid().ToString(),
                TimeCreated = (command.TimeCreated == null ? DateTime.UtcNow : (DateTime)command.TimeCreated),
                EventTypeID = command.EventTypeID,
                TenantID    = 0,
                UserID      = 0,
            };

            command.Values.ForEach(item => auditEvent.Values.Add(new AuditEventValue()
            {
                TypeID = item.TypeID, Value = AuditEventValue.ConvertValue(item.TypeID, item.Value, valueTypes.Find(vt => vt.ID == item.TypeID))
            }));

            _auditEventRepository.Insert(auditEvent);

            return(Ok());
        }
Example #16
0
        private List <SystemTestResult> ExecuteLoggingTest()
        {
            var results = new List <SystemTestResult>();

            // Write audit event
            AuditEvent auditEvent = AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, "Test message");

            _auditEventRepository.Insert(auditEvent);

            // Try reading audit event, may fail if there's an issue such as log file permissions
            AuditEventFilter auditEventFilter = new AuditEventFilter()
            {
                MinTimeCreated = auditEvent.TimeCreated.AddSeconds(-1),
                MaxTimeCreated = auditEvent.TimeCreated.AddSeconds(1)
            };
            var        auditEvents      = _auditEventRepository.Get(auditEventFilter);
            AuditEvent auditEventLogged = auditEvents.Where(ae => ae.ID == auditEvent.ID).FirstOrDefault();

            if (auditEventLogged == null)       // Not logged
            {
                results.Add(new SystemTestResult(SystemTestResult.ResultTypes.Error, _category, "Event logging logging mechanism is not working because it was not possible to log a test event. There may be a problem with log folder permissions or disk space on the Gameplan API server.", ""));
            }
            else
            {
                results.Add(new SystemTestResult(SystemTestResult.ResultTypes.Information, _category, "Event logging mechanism is OK", ""));
            }
            return(results);
        }
Example #17
0
        public List <SystemTaskResult> Execute()
        {
            List <SystemTaskResult> results = new List <SystemTaskResult>();

            try
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, "Deleting access tokens"));
                var accessTokens = _accessTokensRepository.RemoveAllExpired();
                _accessTokensRepository.SaveChanges();
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, $"Deleted {accessTokens.Count()} access tokens"));
            }
            catch (Exception exception)
            {
                results.Add(new SystemTaskResult(SystemTaskResult.ResultTypes.Error, Id, $"Error deleting access tokens: {exception.Message}"));
            }
            return(results);
        }
Example #18
0
        public IHttpActionResult Post([FromBody] List <CreateBreak> breaks)
        {
            if (breaks is null || !breaks.Any() || !ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Determine if they've just started uploading schedule data
            bool isScheduleDataUploadStarted = false;

            using (MachineLock.Create("xggameplan.checkisscheduledatauploadstarted", TimeSpan.FromSeconds(30)))
            {
                isScheduleDataUploadStarted = _breakRepository.CountAll == 0 && _spotRepository.CountAll == 0;
            }

            ValidateBreaks(breaks);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // zero out BroadcastDate's times
            foreach (var b in breaks)
            {
                if (b.BroadcastDate.HasValue)
                {
                    b.BroadcastDate = b.BroadcastDate.Value.Date;
                }
            }

            // group by date and channels
            breaks.GroupBy(s => new { s.ScheduledDate.Date, s.SalesArea }).ForEach(grp =>
            {
                using (MachineLock.Create(string.Format("xggameplan.scheduleday.{0}.{1}", grp.Key.SalesArea, grp.Key.Date), new TimeSpan(0, 10, 0)))
                {
                    var schedule  = _scheduleRepository.GetOrCreateSchedule(grp.Key.SalesArea, grp.Key.Date);
                    var breaklist = _mapper.Map <List <Break> >(grp.ToList());

                    LoadBreakProperties(ref breaklist);

                    _breakRepository.Add(breaklist);

                    schedule.Breaks = breaklist.ToList();
                    _scheduleRepository.Add(schedule);
                    _scheduleRepository.SaveChanges();
                }
            });

            // Generate notification for schedule data upload started
            if (isScheduleDataUploadStarted)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForScheduleDataUploadStarted(0, 0, null));
            }

            return(Ok());
        }
Example #19
0
        /// <inheritdoc />
        public List <KPI> CalculateKPIs(HashSet <string> kpiNamesToCalculate, Guid rawRunId, Guid rawScenarioId)
        {
            if (kpiNamesToCalculate is null)
            {
                throw new ArgumentNullException(nameof(kpiNamesToCalculate));
            }

            var runId      = rawRunId.ToString();
            var scenarioId = rawScenarioId.ToString();

            _audit?.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                   $"Executing KPI processing (RunID={runId}, ScenarioID={scenarioId}) "
                                                                                   + $"KPIs to calculate: [{string.Join(", ", kpiNamesToCalculate)}]"));

            var kpis = new List <KPI>();

            foreach (var kpiName in kpiNamesToCalculate)
            {
                _audit?.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                       $"Executing KPI calculation (KPI={kpiName}, RunID={runId}, ScenarioID={scenarioId})"));

                try
                {
                    var kpiResult = _kpiResolver.Resolve(kpiName);

                    if (kpiResult is null || !kpiResult.Any())
                    {
                        _audit?.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                               $"No result of {kpiName} KPI calculation (RunID={runId}, ScenarioID={scenarioId})"));

                        continue;
                    }

                    kpis.AddRange(kpiResult);
                }
                catch (DependencyResolutionException exception)
                {
                    _audit?.Insert(AuditEventFactory.CreateAuditEventForException(0, 0,
                                                                                  $"Error resolving calculator for {kpiName} KPI for Scenario {scenarioId} of Run {runId}",
                                                                                  exception));
                }
                catch (Exception exception)
                {
                    _audit?.Insert(AuditEventFactory.CreateAuditEventForException(0, 0,
                                                                                  $"Error calculating {kpiName} KPI for Scenario {scenarioId} of Run {runId}",
                                                                                  exception));
                }

                _audit?.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                       $"Executed KPI calculation (KPI={kpiName}, RunID={runId}, ScenarioID={scenarioId})"));
            }

            _audit?.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                   $"Executed KPI processing (RunID={runId}, ScenarioID={scenarioId})"));

            return(kpis);
        }
Example #20
0
        /// <summary>
        /// Gets collection of valid autopilot rules for all needed rule categories
        /// </summary>
        /// <param name="flexibilityLevelId"></param>
        /// <returns>ReadOnly collection of autopilot rules</returns>
        private IReadOnlyDictionary <int, List <AutopilotRule> > GetAutopilotRules(int flexibilityLevelId)
        {
            var autopilotRules = _autopilotRuleRepository.GetByFlexibilityLevelId(flexibilityLevelId).ToList();

            string exceptionMessage = null;

            if (!autopilotRules.Any())
            {
                exceptionMessage = $"Autopilot rules missing for '{flexibilityLevelId}' flexibility level";
            }

            var rulesByType = autopilotRules
                              .Where(ar => ar.Enabled || ar.RuleTypeId == (int)RuleCategory.SlottingLimits)
                              .GroupBy(ar => ar.RuleTypeId)
                              .ToDictionary(g => g.Key, g => g.ToList());

            if (!rulesByType.ContainsKey((int)RuleCategory.SlottingLimits) ||
                rulesByType[(int)RuleCategory.SlottingLimits].Count != 1)
            {
                exceptionMessage = "Missing default SlottingLimits Autopilot rule";
            }

            if (exceptionMessage != null)
            {
                var exception = new Exception("Error while generating autopilot scenarios");
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, exceptionMessage, exception));
                throw exception;
            }

            // default values for all rule categories
            foreach (var ruleCategory in Enum.GetValues(typeof(RuleCategory)).Cast <RuleCategory>())
            {
                if (!rulesByType.ContainsKey((int)ruleCategory))
                {
                    rulesByType[(int)ruleCategory] = new List <AutopilotRule>();
                }
            }

            return(rulesByType);
        }
Example #21
0
        public void ProcessData(ScenarioCampaignFailureOutput data, Run run, Scenario scenario)
        {
            if (!_saveData)
            {
                PreGenerateReport(data.Data, run, scenario);
                return;
            }

            try
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"Start insert of campaign failures. ScenarioId: {data.ScenarioId} Count: {data.Data.Count}"));
                using (var internalScope = _repositoryFactory.BeginRepositoryScope())
                {
                    var scenarioCampaignFailureRepository = internalScope.CreateRepository <IScenarioCampaignFailureRepository>();
                    scenarioCampaignFailureRepository.AddRange(data.Data, false);
                    scenarioCampaignFailureRepository.SaveChanges();
                }
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"Complete insert of campaign failures. ScenarioId: {data.ScenarioId} Count: {data.Data.Count}"));
            }
            catch (Exception e)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, $"Error while processing scenario campaign failures. ScenarioId: {scenario.Id}", e));
                throw;
            }

            PreGenerateReport(data.Data, run, scenario);
        }
Example #22
0
        public void ProcessData(SpotsReqmOutput data, Run run, Scenario scenario)
        {
            try
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"Start insert of recommendations. ScenarioId: {data.ScenarioId} Count: {data.Recommendations.Count}"));

                using (var innerScope = _repositoryFactory.BeginRepositoryScope())
                {
                    var recommendationBatchRepository = innerScope.CreateRepository <IRecommendationRepository>();
                    recommendationBatchRepository.Insert(data.Recommendations, false);
                    recommendationBatchRepository.SaveChanges();
                }

                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"End insert of recommendations. ScenarioId: {data.ScenarioId}"));
            }
            catch (Exception e)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, $"Error while processing scenario recommendations. ScenarioId: {scenario.Id}", e));
                throw;
            }

            // do not generate report for scenario with smooth
            if (run.Smooth)
            {
                return;
            }

            var fileName = ReportFileNameHelper.RecommendationResult(run, scenario);

            PreGenerateReport(data.Recommendations, fileName, scenario.Id);
        }
Example #23
0
        /// <summary>
        /// It is called dynamically.
        /// </summary>
        public async Task Execute(CancellationToken cancellationToken, AutoBook autoBook)
        {
            try
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                     $"Deleting AutoBook (AutoBookID={autoBook.Id})"));
                var autobookDeleted = false;
                try
                {
                    _autoBooks.Delete(autoBook);
                    autobookDeleted = true;
                }
                catch (Exception ex)
                {
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0,
                                                                                                $"Error deleting AutoBook (AutoBookID={autoBook.Id})", ex));
                }

                if (autobookDeleted)
                {
                    _auditEventRepository.Insert(
                        AuditEventFactory.CreateAuditEventForInformationMessage(0, 0, "Deleted AutoBook"));
                }
            }
            finally
            {
                foreach (var dbContext in _tenantDbContexts)
                {
                    try
                    {
                        await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
                    }
                    catch //ignore exception
                    {
                    }
                }
            }
        }
Example #24
0
        public void ProcessData(Failures data, Run run, Scenario scenario)
        {
            try
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"Failures has been generated. ScenarioId: {data.Id}, Count: {data.Items.Count}"));

                using (var innerScope = _repositoryFactory.BeginRepositoryScope())
                {
                    var failuresRepository = innerScope.CreateRepository <IFailuresRepository>();
                    failuresRepository.Add(data);
                    failuresRepository.SaveChanges();
                }

                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                                     0, $"Failures has been saved to the db. ScenarioId: {data.Id}"));
            }
            catch (Exception e)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, "Error while processing failures", e));
                throw;
            }
        }
        public BaseRatingsOutput ProcessFile(Guid scenarioId, string folder)
        {
            string pathToFile = FileHelpers.GetPathToFileIfExists(folder, FileName);
            var    result     = new BaseRatingsOutput();

            if (String.IsNullOrEmpty(pathToFile))
            {
                _audit.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, $"File {pathToFile} was not found."));

                return(result);
            }

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processing output file {pathToFile}"));

            try
            {
                var importSettings = CSVImportSettings.GetImportSettings(pathToFile, typeof(BaseRatingsHeaderMap), typeof(BaseRatingsIndexMap));

                var baseRatingsImportRepository = new CSVBaseRatingsImportRepository(importSettings);

                var data = baseRatingsImportRepository.GetAll();

                result.Data = _mapper.Map <IEnumerable <BaseRatings> >(data);

                _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                      0, $"Processed output file {pathToFile}"));

                return(result);
            }
            catch (Exception exception)
            {
                _audit.Insert(AuditEventFactory.CreateAuditEventForException(0, 0, "Error processing base ratings file", exception));

                return(result);
            }
        }
Example #26
0
        /// <summary>
        /// Requests an autobookRequest model
        /// </summary>
        /// <param name="autoBookRequest"></param>
        public string AutoBookRequestRun(AutoBookRequestModel autoBookRequest)
        {
            string url = $"{_apibaseUrl}/run";

            byte[] contentBody = SerializeContentBody(autoBookRequest);
            int    len         = 0;

            len = contentBody.Length;

            _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                 $"Creating WebRequest for {nameof(AutoBookRequestRun)}, content body len after serialization: {len.ToString()}, url: {url}, autoBookRequest.mock: {autoBookRequest.mock}"));

            try
            {
                var webRequest = CreateHttpWebRequest(url, "POST", GetAuthHeaders(AuthType, _accessToken), ContentTypeJSON, contentBody);

                using var webResponse = (HttpWebResponse)webRequest.GetResponse();
                ThrowExceptionIfNotSuccess(webResponse, new List <HttpStatusCode>()
                {
                    HttpStatusCode.OK
                });
                using var reader = new StreamReader(webResponse.GetResponseStream());
                {
                    var data = reader.ReadToEnd();
                    _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                         $"Created WebRequest for {nameof(AutoBookRequestRun)}, url: {url}, data: {data})"));
                    return(data);
                }
            }
            catch (WebException ex)
            {
                _auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                                     $"Error thrown Creating WebRequest for {nameof(AutoBookRequestRun)}, url: {url}, ex: {ex})"));
                throw ex;
            }
        }
        public ScenarioCampaignResult ProcessFile(Guid scenarioId, string folder)
        {
            string pathToFile = FileHelpers.GetPathToFileIfExists(folder, FileName);
            var    result     = new ScenarioCampaignResult {
                Id = scenarioId
            };

            if (string.IsNullOrEmpty(pathToFile))
            {
                _audit.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, $"File {pathToFile} was not found."));

                return(result);
            }

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processing output file {pathToFile}"));

            var importSettings = CSVImportSettings.GetImportSettings(pathToFile, typeof(ScenarioCampaignResultHeaderMap), typeof(ScenarioCampaignResultIndexMap));
            IScenarioCampaignResultsImportRepository repository = new CSVScenarioCampaignResultsImportRepository(importSettings);

            var data = repository.GetAll();

            var salesAreaIndex = _dataSnapshot.AllSalesAreas.Value.ToDictionary(c => c.CustomId);

            foreach (var importItem in data)
            {
                salesAreaIndex.TryGetValue(importItem.SalesAreaNo, out var salesArea);

                result.Items.Add(MapImportItem(importItem, salesArea));
            }

            _audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0,
                                                                                  0, $"Processed output file {pathToFile}"));

            return(result);
        }
Example #28
0
        //public static void TestSimpleEmail(IAuditEventRepository auditEventRepository)
        //{
        //    Email email = new Email()
        //    {
        //        Subject = "Test email",
        //        Body = "<html><head></head><body>Test email from xG Gameplan</body></html>",
        //        Sender = "*****@*****.**",
        //        SenderDisplay = "NextGen",
        //        RecipientList = { "*****@*****.**" }
        //    };
        //    AuditEvent auditEvent = AuditEventFactory.CreateAuditEventForSimpleEmail(0, 0, email);
        //    auditEventRepository.Insert(auditEvent);
        //}

        public static void TestException(IAuditEventRepository auditEventRepository)
        {
            try
            {
                // Generate exception
                int divisor = 0;
                int result  = 10 / divisor;
            }
            catch (System.Exception exception)
            {
                // Create new exception with other exception as inner exception
                System.Exception exception2 = new System.IO.FileNotFoundException("Test exception", exception);
                exception2.Data.Add("Data1", 10);
                exception2.Data.Add("Data2", DateTime.UtcNow);
                exception2.Data.Add("Data3", "ABC");
                AuditEvent auditEvent2 = AuditEventFactory.CreateAuditEventForException(0, 0, "Test", exception2);
                auditEventRepository.Insert(auditEvent2);
            }
        }
Example #29
0
        /// <summary>
        /// Processes the concrete AutoBook output data type.
        /// </summary>
        /// <typeparam name="TData">The type of the data.</typeparam>
        /// <param name="scope">Current KPI calculation scope.</param>
        /// <param name="featureManager">The feature manager.</param>
        /// <param name="audit">The audit.</param>
        /// <param name="folder">The folder.</param>
        /// <returns></returns>
        private static void ProcessData <TData>(IKPICalculationScope scope, IFeatureManager featureManager,
                                                IAuditEventRepository audit, string folder) where TData : class
        {
            var context       = scope.Resolve <IKPICalculationContext>();
            var fileProcessor = scope.Resolve <IOutputFileProcessor <TData> >();

            if (!featureManager.IsServiceEnabled(fileProcessor.GetType()))
            {
                audit.Insert(AuditEventFactory.CreateAuditEventForInformationMessage(0, 0,
                                                                                     $"Skipping disabled file processor. ScenarioId: {context.ScenarioId}, FileName: {fileProcessor.FileName}"));
                return;
            }

            var data = fileProcessor.ProcessFile(context.ScenarioId, folder);

            context.SetContextData(data);

            if (scope.TryResolve <IOutputDataHandler <TData> >(out var handler))
            {
                handler.ProcessData(data, context.Snapshot.Run.Value, context.Snapshot.Scenario.Value);
            }
        }
Example #30
0
        public SystemLogicalDateService(ITenantSettingsRepository tenantSettingsRepository, IFeatureManager featureManager, IClock clock, IAuditEventRepository auditEventRepository)
        {
            _clock = clock;

            var tenantSettings = tenantSettingsRepository.Get();

            var useSystemLogicalDate = featureManager.IsEnabled(nameof(ProductFeature.UseSystemLogicalDate));

            if (useSystemLogicalDate)
            {
                var isDateValid = DateTime.TryParseExact(tenantSettings.SystemLogicalDate, SystemLogicalDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var systemLogicalDate);

                if (isDateValid)
                {
                    _isSystemLogicalDateUsed = true;
                    _systemLogicalDate       = systemLogicalDate.Add(_clock.GetCurrentInstant().ToDateTimeUtc().TimeOfDay);
                }
                else
                {
                    auditEventRepository.Insert(AuditEventFactory.CreateAuditEventForWarningMessage(0, 0, $"System Logical Date is not it valid format. " +
                                                                                                    $"Date set: '{tenantSettings.SystemLogicalDate}', but valid format is: '{SystemLogicalDateFormat}'. Using current Date instead."));
                }
            }
        }