public void Init()
        {
            _log                 = Substitute.For <ILog>();
            _dateCalculator      = Substitute.For <IDateCalculator>();
            _powerService        = Substitute.For <IPowerService>();
            _positionAggregator  = Substitute.For <IPositionAggregator>();
            _fileNameGenerator   = Substitute.For <IFileNameGenerator>();
            _reportContentWriter = Substitute.For <IReportContentWriter>();
            _file                = Substitute.For <IFile>();
            _reportGenerator     = new ReportGenerator(_log, _dateCalculator, _powerService, _positionAggregator, _fileNameGenerator, _reportContentWriter, _file);

            _reportFolder = @"C:\Temp\";
            _dates        = new DateResult {
                ExtractDateTime = new DateTime(2015, 10, 5, 23, 34, 0), RequestDate = new DateTime(2015, 10, 6)
            };

            _powerTradeOne = new PowerTrade();
            _powerTradeTwo = new PowerTrade();
            _powerTrades   = new[] { _powerTradeOne, _powerTradeTwo };
            _powerPosition = new PowerPosition(_dates.RequestDate);
            _fileName      = "PowerPositions.csv";
            _content       = "Local time, Volume etc";

            _dateCalculator.Calculate().Returns(_dates);
            _powerService.GetTrades(_dates.RequestDate).Returns(_powerTrades);
            _positionAggregator.Aggregate(_dates.RequestDate, Arg.Is <List <PowerTrade> >(x => x[0] == _powerTradeOne && x[1] == _powerTradeTwo)).Returns(_powerPosition);
            _fileNameGenerator.Generate(_dates.ExtractDateTime).Returns(_fileName);
            _reportContentWriter.Write(_powerPosition).Returns(_content);
        }
        public void Init()
        {
            _log = Substitute.For<ILog>();
            _dateCalculator = Substitute.For<IDateCalculator>();
            _powerService = Substitute.For<IPowerService>();
            _positionAggregator = Substitute.For<IPositionAggregator>();
            _fileNameGenerator = Substitute.For<IFileNameGenerator>();
            _reportContentWriter = Substitute.For<IReportContentWriter>();
            _file = Substitute.For<IFile>();
            _reportGenerator = new ReportGenerator(_log, _dateCalculator, _powerService, _positionAggregator, _fileNameGenerator, _reportContentWriter, _file);

            _reportFolder = @"C:\Temp\";
            _dates = new DateResult { ExtractDateTime = new DateTime(2015, 10, 5, 23, 34, 0), RequestDate = new DateTime(2015, 10, 6) };

            _powerTradeOne = new PowerTrade();
            _powerTradeTwo = new PowerTrade();
            _powerTrades = new[] { _powerTradeOne, _powerTradeTwo };
            _powerPosition = new PowerPosition();
            _fileName = "PowerPositions.csv";
            _content = "Local time, Volume etc";

            _dateCalculator.Calculate().Returns(_dates);
            _powerService.GetTrades(_dates.RequestDate).Returns(_powerTrades);
            _positionAggregator.Aggregate(_dates.RequestDate, Arg.Is<List<PowerTrade>>(x => x[0] == _powerTradeOne && x[1] == _powerTradeTwo)).Returns(_powerPosition);
            _fileNameGenerator.Generate(_dates.ExtractDateTime).Returns(_fileName);
            _reportContentWriter.Write(_powerPosition).Returns(_content);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MachineOffCheckViewModel"/> class.
        /// </summary>
        /// <param name="powerService">The power service to use.</param>
        /// <param name="policyProvider">The policy provider to use.</param>
        public MachineOffCheckViewModel(IPowerService powerService, ICommandPolicyProvider policyProvider)
        {
            if (powerService is null)
            {
                throw new System.ArgumentNullException(nameof(powerService));
            }

            if (policyProvider is null)
            {
                throw new System.ArgumentNullException(nameof(policyProvider));
            }

            this.WhenActivated(disposable =>
            {
                this.poweredOn = powerService.PoweredOn.ToProperty(this, x => x.PoweredOn).DisposeWith(disposable);
                var policy     = policyProvider.GetPolicy();

                this.TurnOn = ReactiveCommand.CreateFromTask(
                    async(ct) =>
                    await policy.ExecuteAsync(
                        async(token) => await powerService.PowerOn(token),
                        ct),
                    powerService.PoweredOn.Select(x => !x)).DisposeWith(disposable);

                this.canExecuteTurnOn = this.TurnOn.CanExecute.ToProperty(this, x => x.CanExecuteTurnOn).DisposeWith(disposable);
            });
        }
        public void WriteCsvMinuteInterval_over_timeout_raises_WriteCsvException()
        {
            var csvWriter      = new CsvWriter();
            var minuteInterval = 30;
            //confirm file was written
            var      maxTrys      = 5;
            DateTime?lastWroteCsv = null;

            IPowerService powerService = Mock.Create <IPowerService>();

            Mock.Arrange(() => powerService.GetTradesAsync(_testDateTime)).Returns(() => new Task <IEnumerable <PowerTrade> >(() =>
            {
                var waitTimepan = new TimeSpan(0, 0, _timeOut.Seconds + 2);
                var stopwatch   = new Stopwatch();
                stopwatch.Start();
                while (stopwatch.ElapsedMilliseconds < waitTimepan.TotalMilliseconds)
                {
                    Thread.Sleep(0);
                }
                return(_powerTrades);
            }));

            //first try five times no error should be thrown it will be logged and a retry allowed
            for (int i = 1; i <= maxTrys; i++)
            {
                Assert.DoesNotThrow(() => lastWroteCsv = csvWriter.WriteCsvMinuteInterval(_fileFolder, _fileName, _fileDateFormat, _fileSuffix, _delimiter, _columnOneName, _columnTwoName,
                                                                                          _dataDateFormat, minuteInterval, _testDateTime, powerService, _timeOut, lastWroteCsv));
            }
            //final time is over maximum number of retries so should throw an exception
            Assert.Throws <WriteCsvException>(() => lastWroteCsv = csvWriter.WriteCsvMinuteInterval(_fileFolder, _fileName, _fileDateFormat, _fileSuffix, _delimiter, _columnOneName, _columnTwoName,
                                                                                                    _dataDateFormat, minuteInterval, _testDateTime, powerService, _timeOut, lastWroteCsv));
        }
        //Confirm the WriteCvException is being logged in the correct format
        public void WriteCsvMinuteInterval_PowerServiceException_is_caught_and_logged()
        {
            var csvWriter      = new CsvWriter();
            var minuteInterval = 30;
            //confirm file was written
            var      logFileName  = "PositionAggregatorLogFile.txt";
            var      maxTrys      = 5;
            DateTime?lastWroteCsv = null;

            File.Delete(logFileName);
            IPowerService powerService = Mock.Create <IPowerService>();

            Mock.Arrange(() => powerService.GetTradesAsync(_testDateTime)).Throws <PowerServiceException>("Power Service Exception");
            //first try five times and confirm log file is written correctly
            for (int i = 1; i <= maxTrys; i++)
            {
                lastWroteCsv = csvWriter.WriteCsvMinuteInterval(_fileFolder, _fileName, _fileDateFormat, _fileSuffix, _delimiter, _columnOneName, _columnTwoName,
                                                                _dataDateFormat, minuteInterval, _testDateTime, powerService, _timeOut, lastWroteCsv);
            }
            //confirm the log file has been written
            Assert.IsTrue(File.Exists(logFileName));
            var assembly           = Assembly.GetExecutingAssembly();
            var resourceName       = "TDomain.PositionAggregatorLogFile.txt";
            var logFileExampleText = "";

            using (StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resourceName)))
            {
                logFileExampleText = reader.ReadToEnd();
            }
            var logFileText = File.ReadAllText(logFileName);

            //confirm the log file has been written correctly.  contents will differ due to timing of runs so realistically good enough to just check the lengths
            Assert.AreEqual(logFileExampleText.Length, logFileText.Length);
        }
Beispiel #6
0
 public VillainService(HeroesDbContext context, IPowerService powerService, IOptions <AppSettings> appSettings, IUserService userService)
 {
     _context      = context;
     _powerService = powerService;
     _appSettings  = appSettings.Value;
     _userService  = userService;
 }
Beispiel #7
0
        public static void DownloadTrades(IPowerService powerService, ILogService logService)
        {
            DateTime localDateTime        = DateTime.Now;
            Dictionary <int, double> data = GetHourlyVolume(powerService, logService, localDateTime);

            SaveTradeData(GetHourlyVolumeReport(data), logService, localDateTime);
        }
        /// <summary>
        /// Instantiate to be able to get the trades required.
        /// </summary>
        /// <param name="service">The type of API service.</param>
        /// <param name="trade">The type of trade.</param>
        public TradesFetcher(IPowerService service, TradeType trade, IServiceLogger logger)
        {
            this.service = service;
            this.trade   = trade;
            this.logger  = logger;

            Environment.SetEnvironmentVariable("Trade", trade.ToString());
        }
 public CharacterController(ICharacterService characterService, ILogger logger, IPowerService powerService, IPowerLevelService powerLevelService, ITemplateService templateService)
 {
     _characterService = characterService;
     _powerService = powerService;
     _powerLevelService = powerLevelService;
     _templateService = templateService;
     _logger = logger;
 }
Beispiel #10
0
        public HomeController(ILogger <HomeController> logger, IConfiguration configuration)
        {
            _logger        = logger;
            _configuration = configuration;

            // Initialize the PowerServiceClientFactory using configuration data saved in application
            _api = PowerServiceClientFactory.CreateAsync(new Uri(_configuration["mp.ApiBaseUrl"]), _configuration["mp.client"], _configuration["mp.secret"]).Result;
        }
Beispiel #11
0
 public PositonService(ILogger logger,
                       IPowerService powerService,
                       IFileGenerator fileGenerator)
 {
     this._logger        = logger;
     this._fileGenerator = fileGenerator;
     this._powerService  = powerService;
 }
Beispiel #12
0
 public InterDayReportGenerator(IPowerService powerService,
                                IReportExporter exporter,
                                IReportDateProvider dateProvider)
 {
     _powerService = powerService;
     _exporter     = exporter;
     _dateProvider = dateProvider;
 }
Beispiel #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HeaderViewModel"/> class.
        /// </summary>
        /// <param name="powerService">The power service implementation.</param>
        /// <param name="titleService">The title service.</param>
        /// <param name="policyProvider">The policy provider to execute ordinary commands.</param>
        /// <param name="navigationManager">The navigation manager to navigate to a different page.</param>
        public HeaderViewModel(
            IPowerService powerService,
            ITitleService titleService,
            ICommandPolicyProvider policyProvider,
            NavigationManager navigationManager)
        {
            if (powerService is null)
            {
                throw new ArgumentNullException(nameof(powerService));
            }

            if (titleService is null)
            {
                throw new ArgumentNullException(nameof(titleService));
            }

            if (policyProvider is null)
            {
                throw new ArgumentNullException(nameof(policyProvider));
            }

            if (navigationManager is null)
            {
                throw new ArgumentNullException(nameof(navigationManager));
            }

            this.WhenActivated(disposable =>
            {
                this.poweredOn = powerService.PoweredOn.ToProperty(this, x => x.PoweredOn).DisposeWith(disposable);
                this.title     = titleService.Title.ToProperty(this, x => x.Title).DisposeWith(disposable);
                var policy     = policyProvider.GetPolicy();

                this.TogglePower = ReactiveCommand.CreateFromTask(async(ct) =>
                {
                    switch (this.PoweredOn)
                    {
                    case true:
                        await policy.ExecuteAsync(
                            async(token) => await powerService.PowerOff(token),
                            ct);
                        break;

                    case false:
                        await policy.ExecuteAsync(
                            async(token) => await powerService.PowerOn(token),
                            ct);
                        break;
                    }
                }).DisposeWith(disposable);

                this.Settings = ReactiveCommand.Create(() =>
                {
                    navigationManager.NavigateTo("/Settings");
                }).DisposeWith(disposable);

                this.canExecuteTogglePower = this.TogglePower.CanExecute.ToProperty(this, x => x.CanExecuteTogglePower).DisposeWith(disposable);
            });
        }
 public HeroService(HeroesDbContext context, IPowerService powerService, IHeroTypeService heroTypeService, IUserService userService, IOptions <AppSettings> appSettings, IRewardService rewardService)
 {
     _context         = context;
     _powerService    = powerService;
     _heroTypeService = heroTypeService;
     _userService     = userService;
     _appSettings     = appSettings.Value;
     _rewardService   = rewardService;
 }
Beispiel #15
0
        public DataSyncProcessor(IWebhookService webhookService, ILoggingService loggingService, IBladeAndSoulService bladeAndSoulService, IPowerService powerService)
        {
            _webhookService      = webhookService;
            _loggingService      = loggingService;
            _bladeAndSoulService = bladeAndSoulService;
            _powerService        = powerService;

            _lock = new SemaphoreSlim(1);
        }
 public ReportGenerator(ILog log, IDateCalculator dateCalculator, IPowerService powerService, IPositionAggregator positionAggregator, IFileNameGenerator fileNameGenerator, IReportContentWriter reportContentWriter, IFile file)
 {
     _log = log;
     _dateCalculator = dateCalculator;
     _powerService = powerService;
     _positionAggregator = positionAggregator;
     _fileNameGenerator = fileNameGenerator;
     _reportContentWriter = reportContentWriter;
     _file = file;
 }
Beispiel #17
0
 public ReportGenerator(ILog log, IDateCalculator dateCalculator, IPowerService powerService, IPositionAggregator positionAggregator, IFileNameGenerator fileNameGenerator, IReportContentWriter reportContentWriter, IFile file)
 {
     _log                 = log;
     _dateCalculator      = dateCalculator;
     _powerService        = powerService;
     _positionAggregator  = positionAggregator;
     _fileNameGenerator   = fileNameGenerator;
     _reportContentWriter = reportContentWriter;
     _file                = file;
 }
Beispiel #18
0
 public Workflow()
 {
     //Use a dependency injection container (for unit/integration test)
     //and a factory class to delegate initialisation
     _powerService          = new PowerService();
     _configManager         = new ConfigManager();
     _fileManager           = new FileManager(_configManager);
     _aggregate             = new Aggregate();
     _intervalInMiliseconds = GetIntervalFromConfig();
 }
Beispiel #19
0
        public PowerPageViewModel(IPowerService powerService,
                                  IWordclockDialogService dialogService)
        {
            _powerService  = powerService;
            _dialogService = dialogService;

            SaveTimeSlotCommand = new Command(() => Save());

            Refresh();
        }
        public PowerMonitorViewModel(IPowerService pService)
        {
            _pService         = pService;
            _pService.GotData = (t, p) =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => { Power = p; Temperature = t; });
            };

            _pService.ConnectAndListen();
            ConnectToHub();
        }
 public PowerMonitorViewModel(IPowerService pService)
 {
     _pService = pService;
     _pService.GotData = (t, p) =>
     {
         DispatcherHelper.CheckBeginInvokeOnUI(() => { Power = p; Temperature = t; });
     };
       
     _pService.ConnectAndListen();
     ConnectToHub();
 }
Beispiel #22
0
        public TradeExtractorService(IScheduler scheduler,
                                     IConfigurationProvider configurationProvider,
                                     ILogger log)
        {
            Argument.IsNotNull(() => scheduler);
            Argument.IsNotNull(() => configurationProvider);
            Argument.IsNotNull(() => log);

            _scheduler             = scheduler;
            _configurationProvider = configurationProvider;

            Log.Logger = log;
            SetupPeriodTextLookup();

            _powerService = new PowerService();
        }
Beispiel #23
0
        public TelegramBotService(string botKey, IGardenService gardenService, ILogger <TelegramBotService> logger, IPowerService powerService)
        {
            _logger       = logger;
            _powerService = powerService;
            _currentBot   = new TelegramBotClient(botKey);

            _currentBot.OnMessage       += BotOnMessageReceived;
            _currentBot.OnMessageEdited += BotOnMessageReceived;
            _gardenService = gardenService;
            _gardenService.SubscribeOnStart(_gardenOnStartHandler);
            _gardenService.SubscribeOnStop(_gardenOnStopHandler);

            _powerService.SubscribeOnValueAcquired(_powerValueAcquiredHandler);

            User currentBotInfo = _currentBot.GetMeAsync().GetAwaiter().GetResult();

            _logger.LogDebug($"Connected as: {currentBotInfo.Username}");
        }
        //Confirm the WriteCvException is being logged in the correct format
        public void WriteCsvMinuteInterval_PowerServiceException_raised_sequentially_over_maximum_trys_throws_error()
        {
            var minuteInterval = 30;
            var asAt           = _testDateTime.AddMinutes(29);
            //confirm file was written
            var      maxTrys      = 5;
            var      csvWriter    = new CsvWriter();
            DateTime?lastWroteCsv = null;

            IPowerService powerService = Mock.Create <IPowerService>();

            Mock.Arrange(() => powerService.GetTradesAsync(_testDateTime)).Throws <AggregateException>("Power Service exception");
            //first try five times no error should be thrown it will be logged and a retry allowed
            for (int i = 1; i <= maxTrys; i++)
            {
                Assert.DoesNotThrow(() => lastWroteCsv = csvWriter.WriteCsvMinuteInterval(_fileFolder, _fileName, _fileDateFormat, _fileSuffix, _delimiter, _columnOneName, _columnTwoName,
                                                                                          _dataDateFormat, minuteInterval, _testDateTime, powerService, _timeOut, lastWroteCsv));
            }
            //final time is over maximum number of retries so should throw an exception
            Assert.Throws <AggregateException>(() => lastWroteCsv = csvWriter.WriteCsvMinuteInterval(_fileFolder, _fileName, _fileDateFormat, _fileSuffix, _delimiter, _columnOneName, _columnTwoName,
                                                                                                     _dataDateFormat, minuteInterval, _testDateTime, powerService, _timeOut, lastWroteCsv));
        }
Beispiel #25
0
 public MessageCreateProcessor(
     IMessageService messageService,
     IUserService userService,
     PlogDbContext plogDbContext,
     IBladeAndSoulService bladeAndSoulService,
     ILoggingService loggingService,
     IClanLogService clanLogService,
     IRaffleService raffleService,
     IAlertService alertService,
     ITimeZoneService timeZoneService,
     IPowerService powerService,
     IGuildService guildService
     )
 {
     _plogDbContext           = plogDbContext;
     _messageService          = messageService;
     _userService             = userService;
     _bladeAndSoulService     = bladeAndSoulService;
     _loggingService          = loggingService;
     _clanLogService          = clanLogService;
     _raffleService           = raffleService;
     _alertService            = alertService;
     _timeZoneService         = timeZoneService;
     _powerService            = powerService;
     _guildService            = guildService;
     _allowedTopLevelCommands = new List <string> {
         "test", "add", "me", "alt", "release", "characters", "whales", "clanlog", "raffle", "ticket", "alert", "mytime"
     };
     _adminCommands = new List <string> {
         "reset"
     };
     _bannedKashPhrases = new List <string> {
         "no", "nope", "nah", "nada", "n0", "n0pe"
     };
     _response = "There was an error processing this request.";
 }
Beispiel #26
0
        public static Dictionary <int, double> GetHourlyVolume(IPowerService powerService, ILogService logService, DateTime localDateTime)
        {
            Dictionary <int, double> periodVolume = new Dictionary <int, double>();

            try
            {
                foreach (PowerTrade p in powerService.GetTrades(localDateTime))
                {
                    foreach (PowerPeriod pp in p.Periods)
                    {
                        if (periodVolume.ContainsKey(pp.Period))
                        {
                            periodVolume[pp.Period] = periodVolume[pp.Period] + pp.Volume;
                        }
                        else
                        {
                            periodVolume.Add(pp.Period, pp.Volume);
                        }
                    }
                }
            }
            catch (Services.PowerServiceException seExp)
            {
                logService.Log(string.Format("Power service issue: {0} \n occured while getting data for {1}.csv file ", seExp.ToString(), GetFormattedFileName(localDateTime)));
            }
            catch (Exception exp)
            {
                logService.Log(string.Format("Unknow error: {0} \n  occured while getting data for {1}.csv file ", exp.ToString(), GetFormattedFileName(localDateTime)));
            }
            if (periodVolume.Count == 0)
            {
                logService.Log(string.Format("No trade data found for {0}.csv", GetFormattedFileName(localDateTime)));
            }

            return(periodVolume);
        }
        //Generate a csv for position at a set interval
        public void StartCsvMinuteInterval(string fileFolder, string fileName, string fileDateFormat, string fileSuffix, string delimiter, string columnOneName,
                                           string columnTwoName, string dataDateFormat, int minuteInterval, IPowerService powerService, TimeSpan timeout)
        {
            //var tokenSource = new CancellationTokenSource();
            var lastWroteCsv = new DateTime?();
            var task         = Task.Run(async() =>
            {
                while (true)
                {
                    lastWroteCsv = WriteCsvMinuteInterval(fileFolder, fileName, fileDateFormat, fileSuffix, delimiter, columnOneName,
                                                          columnTwoName,
                                                          dataDateFormat, minuteInterval, null, powerService, timeout, lastWroteCsv);
                    await Task.Delay(10000);
                }
            });

            /*
             * _timer = new System.Threading.Timer(t =>
             * WriteCsvMinuteInterval(fileFolder, fileName, fileDateFormat, fileSuffix, delimiter, columnOneName, columnTwoName,
             *    dataDateFormat, minuteInterval, null, powerService, timeout)
             *    , null, 0, 10000);
             */
        }
Beispiel #28
0
        private static async Task GenerateModels(IPowerService _api)
        {
            string currentFolder = AppDomain.CurrentDomain.BaseDirectory;
            var    tables        = await _api.GetTablesAsync();

            using (StreamWriter sw = File.CreateText(currentFolder + "\\MPModels.cs"))
            {
                sw.WriteLine("using System;");
                sw.WriteLine("using System.Collections.Generic;");
                sw.WriteLine("using System.ComponentModel.DataAnnotations;");
                sw.WriteLine("using System.ComponentModel.DataAnnotations.Schema;");
                sw.WriteLine("using System.Linq;");
                sw.WriteLine("using Newtonsoft.Json;");
                sw.WriteLine("using System.Web.DynamicData;");
                sw.WriteLine("");
                sw.WriteLine("namespace MinistryPlatform.Models");
                sw.WriteLine("{");

                // Produce Base Class (Optional)
                //sw.WriteLine("\tpublic class mpBaseClass");
                //sw.WriteLine("\t{");
                //sw.WriteLine("\t}");

                foreach (var item in tables)
                {
                    // Ignore all Tables starting with _ character
                    if (item.Name.StartsWith("_"))
                    {
                        continue;
                    }

                    // Ignore SQL Views
                    if (item.Name.StartsWith("mp_vw"))
                    {
                        continue;
                    }

                    string modelName = item.Name.Replace("_", "");

                    modelName = fixModelName(modelName);

                    modelName += "Model";
                    //sw.WriteLine("[Table(\"" + item.Name + "\")]");
                    sw.WriteLine($"\tpublic class {modelName}");
                    sw.WriteLine("\t{");
                    foreach (var c in item.Columns)
                    {
                        //Ignore any field called tablename // Reserved Constant for Model
                        if (c.Name.ToLower() == "tablename")
                        {
                            continue;
                        }

                        WriteColumn(c, sw);
                    }
                    sw.WriteLine("");
                    sw.WriteLine($"\t\tpublic const string TableName = \"{item.Name}\";");
                    sw.WriteLine("\t}");
                    sw.WriteLine("");
                    sw.WriteLine("");
                }
                sw.WriteLine("}");
            }

            return;
        }
        //Generate historical position csv files
        public void WriteCsvMinuteIntervalHistorical(string fileFolder, string fileName, string fileDateFormat, string fileSuffix, string delimiter, string columnOneName,
                                                     string columnTwoName, string dataDateFormat, int minuteInterval, IPowerService powerService, TimeSpan timeout, DateTime fromDate, DateTime toDate, bool overwriteExisting)
        {
            var lastWroteCsv = new DateTime?(fromDate.AddHours(-1));

            for (DateTime checkDateTime = fromDate; checkDateTime <= toDate; checkDateTime = checkDateTime.AddMinutes(1))
            {
                lastWroteCsv = WriteCsvMinuteInterval(fileFolder, fileName, fileDateFormat, fileSuffix, delimiter, columnOneName,
                                                      columnTwoName, dataDateFormat, minuteInterval, checkDateTime, powerService, timeout, lastWroteCsv, overwriteExisting);
            }
        }
 public PowersController(IPowerService powerService)
 {
     _powerService = powerService;
 }
Beispiel #31
0
 public EmbedReportApiController(IPowerService powerService)
 {
     _powerService = powerService;
 }
Beispiel #32
0
 public PowerDataAccess(IPowerService powerService, IDtoConverter dtoConverter)
 {
     _powerService = powerService;
     _dtoConverter = dtoConverter;
 }
        //Write the csv file if the current time is at the minute Interval and no other file has been written by the process.  Otherwise write the file.
        public DateTime?WriteCsvMinuteInterval(string fileFolder, string fileName, string fileDateFormat, string fileSuffix, string delimiter, string columnOneName,
                                               string columnTwoName, string dataDateFormat, int minuteInterval, DateTime?asAt, IPowerService powerService, TimeSpan timeout, DateTime?lastWroteCsv, bool overwriteExisting = true)
        {
            //use at parameter to override what time the method believes it is.  This is useful for testing.
            //using Universal time means do not have to worry about clocks changing
            DateTime nowDateTime = asAt ?? DateTime.Now.ToUniversalTime();

            //if null then this is a first run so write the file if
            if (lastWroteCsv == null || (nowDateTime.Minute % minuteInterval == 0 &&
                                         (nowDateTime.Day != lastWroteCsv.Value.Day || nowDateTime.Hour != lastWroteCsv.Value.Hour || nowDateTime.Minute != lastWroteCsv.Value.Minute)))
            {
                try
                {
                    var writeFile  = GetFullFileName(fileFolder, fileName, fileDateFormat, fileSuffix, nowDateTime);
                    var fileExists = File.Exists(writeFile);
                    if (overwriteExisting == true || (!fileExists))
                    {
                        _tryWriteCsv++;
                        var tradesTask = powerService.GetTradesAsync(nowDateTime);
                        if (!tradesTask.Wait(timeout))
                        {
                            var exceptionMessage =
                                "The operation to retrieve power trades has timed out.  Timeout value used was " +
                                timeout.Seconds + " seconds.  The date parameter passed was " +
                                nowDateTime.ToString("R");
                            throw new WriteCsvException(exceptionMessage);
                        }
                        var trades   = tradesTask.Result;
                        var position = new Position(trades, nowDateTime);
                        WriteCsv(writeFile, delimiter, columnOneName, columnTwoName, dataDateFormat, position);
                        _tryWriteCsv = 0;
                        return(nowDateTime);
                    }
                }
                catch (Exception ex)
                    when(ex is PowerServiceException || ex is WriteCsvException || ex is AggregateException)
                    {
                        //Will retry the procedure a specified number of times when the above errors are called because they are potentially recoverable
                        if (_tryWriteCsv <= _maxTryWriteCsv)
                        {
                            //log and allow retry on next timer interval
                            var exceptionMessages = ex.GetExceptionMessages();
                            var errorMessage      =
                                "An error has occured trying to write the csv file.  This is attempt number " + _tryWriteCsv +
                                ".  A maximum of " + _maxTryWriteCsv + " attempts will be made to write the file " +
                                ".  Detailed information is below.\r\n\r\n"
                                + exceptionMessages;
                            _logger.Error(ex, errorMessage);
                        }
                        else
                        {
                            throw;
                        }
                    }
            }
            // by default assume csv not written
            return(lastWroteCsv);
        }
Beispiel #34
0
 public HydrateAssetPowerPorts(IPowerService powerService, IModelRepository modelRepo)
 {
     _powerService = powerService;
     _modelRepo    = modelRepo;
 }
 public PowerController(IPowerService powerService)
 {
     _powerService = powerService;
 }