public async Task StartPath2()
        {
            //Arrange
            var logEntries = new List <LogEntry>();
            var log        = new StubIFeedback <LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return(Task.FromResult(0));
                }
            };
            var cts = new CancellationTokenSource();
            var tm  = new ScheduledTaskRunner(log, new StubICommandProcessor(), new UnitTestDbConnection(), new CurrentTimeProvider());

            //Act
            await tm.StartAsync(cts.Token);

            await tm.StartAsync(cts.Token);

            //Assert

            Assert.IsTrue(logEntries.Last().Level == LogEntryLevel.Warn);
        }
        public async Task StopPath1()
        {
            //Arrange
            var logEntries = new List <LogEntry>();
            var log        = new StubIFeedback <LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString()); logEntries.Add(e);
                    return(Task.FromResult(0));
                }
            };
            var cts = new CancellationTokenSource();
            var tm  = new ScheduledTaskRunner(log, new StubICommandProcessor(), new UnitTestDbConnection(), new CurrentTimeProvider());

            //Act
            await tm.StartAsync(cts.Token);

            await tm.StopAsync(cts.Token);

            //Assert
            Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Expected only info type log entries");
            Assert.IsTrue(logEntries.Any(o => o.Message.Contains("stopped")), "Manger not started or word started not in the log.");
            Assert.IsFalse(tm.IsRunning);
        }
        public void ConstructorPath5()
        {
            //arrange, act
            var tm = new ScheduledTaskRunner(new StubIFeedback<LogEntry>(), new StubICommandProcessor(), new ZvsEntityContextConnection(), new CurrentTimeProvider());

            //Assert
            Assert.IsNotNull(tm);
        }
        public void ConstructorPath5()
        {
            //arrange, act
            var tm = new ScheduledTaskRunner(new StubIFeedback <LogEntry>(), new StubICommandProcessor(), new UnitTestDbConnection(), new CurrentTimeProvider());

            //Assert
            Assert.IsNotNull(tm);
        }
Ejemplo n.º 5
0
        public static async Task Runs_tasks_that_are_due()
        {
            var currentInstant = 30.December(2020).At(12, 07, 26).Utc();

            var dueTime    = currentInstant;
            var notDueTime = currentInstant.Plus(1.Seconds());

            var dailyNotificationSchedule       = new Schedule(ScheduledTaskType.DailyNotification, dueTime);
            var requestReminderSchedule         = new Schedule(ScheduledTaskType.RequestReminder, notDueTime);
            var softInterruptionUpdaterSchedule = new Schedule(ScheduledTaskType.SoftInterruptionUpdater, notDueTime);
            var weeklyNotificationSchedule      = new Schedule(ScheduledTaskType.WeeklyNotification, dueTime);

            var schedules = new[]
            {
                dailyNotificationSchedule,
                requestReminderSchedule,
                softInterruptionUpdaterSchedule,
                weeklyNotificationSchedule
            };

            var mockScheduleRepository = new Mock <IScheduleRepository>(MockBehavior.Strict);

            mockScheduleRepository.Setup(r => r.GetSchedules()).ReturnsAsync(schedules);
            mockScheduleRepository.Setup(r => r.UpdateSchedule(It.IsAny <Schedule>())).Returns(Task.CompletedTask);

            var mockDateCalculator = new Mock <IDateCalculator>(MockBehavior.Strict);

            mockDateCalculator.Setup(d => d.ScheduleIsDue(dailyNotificationSchedule, null)).Returns(true);
            mockDateCalculator.Setup(d => d.ScheduleIsDue(requestReminderSchedule, null)).Returns(false);
            mockDateCalculator.Setup(d => d.ScheduleIsDue(softInterruptionUpdaterSchedule, null)).Returns(false);
            mockDateCalculator.Setup(d => d.ScheduleIsDue(weeklyNotificationSchedule, null)).Returns(true);

            var mockDailyNotification       = CreateMockScheduledTask(ScheduledTaskType.DailyNotification);
            var mockRequestReminder         = CreateMockScheduledTask(ScheduledTaskType.RequestReminder);
            var mockSoftInterruptionUpdater = CreateMockScheduledTask(ScheduledTaskType.SoftInterruptionUpdater);
            var mockWeeklyNotification      = CreateMockScheduledTask(ScheduledTaskType.WeeklyNotification);

            var scheduledTasks = new[]
            {
                mockDailyNotification.Object,
                mockRequestReminder.Object,
                mockSoftInterruptionUpdater.Object,
                mockWeeklyNotification.Object
            };

            var scheduledTaskRunner = new ScheduledTaskRunner(
                mockDateCalculator.Object,
                scheduledTasks,
                mockScheduleRepository.Object);

            await scheduledTaskRunner.RunScheduledTasks();

            mockDailyNotification.Verify(s => s.Run(), Times.Once);
            mockRequestReminder.Verify(s => s.Run(), Times.Never);
            mockSoftInterruptionUpdater.Verify(s => s.Run(), Times.Never);
            mockWeeklyNotification.Verify(s => s.Run(), Times.Once);
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     Adds a task onto the schedule so it will be checked and run as defined by the schedule
        /// </summary>
        /// <param name="task">The task to run</param>
        /// <param name="schedule">The schedule that determines when the task should run</param>
        public bool TryAddTask(ITask task, Schedule schedule)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            if (schedule == null)
            {
                throw new ArgumentNullException(nameof(schedule));
            }

            if (IsRunning)
            {
                return(false);
            }

            switch (schedule.Type)
            {
            case ScheduleType.Periodical:
                var p = new PeriodicalTaskRunner(task, schedule.Frequency);
                _taskRunners.Add(p);
                break;

            case ScheduleType.Scheduled:
                var s = new ScheduledTaskRunner(task, schedule.RunAt);
                _taskRunners.Add(s);
                break;

            case ScheduleType.Task:
                var neverRunner = new OnDemandTaskRunner(task);
                _taskRunners.Add(neverRunner);
                break;

            case ScheduleType.Defered:

                break;

            default:
                throw new Exception(schedule.Type + " is not a supported schedule type.");
            }

            return(true);
        }
Ejemplo n.º 7
0
        public async Task StartAsyncTest()
        {
            //arrange
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var logEntries = new List <LogEntry>();
            var log        = new StubIFeedback <LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return(Task.FromResult(0));
                }
            };
            var isAdapterManagerInitialized = false;
            var isPluginManagerInitialized  = false;


            var am = new StubIAdapterManager {
                StartAsyncCancellationToken = async ct => isAdapterManagerInitialized = true
            };
            var pm = new StubIPluginManager {
                StartAsyncCancellationToken = async ct => isPluginManagerInitialized = true
            };
            var tr = new TriggerRunner(log, new StubICommandProcessor(), dbConnection);
            var st = new ScheduledTaskRunner(log, new StubICommandProcessor(), dbConnection, new CurrentTimeProvider());

            var engine = new ZvsEngine(log, am, pm, dbConnection, tr, st);

            //Act
            await engine.StartAsync(CancellationToken.None);


            //assert
            Assert.IsNotNull(engine);
            Assert.IsTrue(isAdapterManagerInitialized, "Adapter manager was not started!");
            Assert.IsTrue(isPluginManagerInitialized, "Plugin manager was not started!");
            Assert.IsTrue(engine.ScheduledTaskRunner.IsRunning, "Scheduled Task Runner was not started!");
            Assert.IsTrue(engine.TriggerRunner.IsRunning, "Trigger Runner was not started!");
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> RunTask(string taskType, string instCode)
        {
            try
            {
                var processor = Utilities.QueryProcessor;
                processor.InstitutionCode = instCode;
                ScheduledTask scheduledTask = await processor.ProcessAsync(new GetTaskByTypeQuery { Type = taskType });

                if (scheduledTask != null)
                {
                    var task = new ScheduledTaskRunner(scheduledTask);
                    await task.Execute();
                }
            }
            catch (System.Exception ex)
            {
                Utilities.Logger.Log("ScheduledTaskApi/RunTask: " + ex.GetFullExceptionMessage());
            }
            return(new EmptyResult());
        }
        public async Task StartPath1()
        {
            //Arrange 
            var logEntries = new List<LogEntry>();
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString()); logEntries.Add(e);
                    return Task.FromResult(0);
                }
            };
            var cts = new CancellationTokenSource();
            var tm = new ScheduledTaskRunner(log, new StubICommandProcessor(), new ZvsEntityContextConnection(), new CurrentTimeProvider());

            //Act
            await tm.StartAsync(cts.Token);

            //Assert
            Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Expected only info type log entries");
            Assert.IsTrue(logEntries.Any(o => o.Message.Contains("started")), "Manger not started or word started not in the log.");
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Adds a task onto the schedule so it will be checked and run as defined by the schedule
        /// </summary>
        /// <param name="task">The task to run</param>
        /// <param name="schedule">The schedule that determines when the task should run</param>
        public void AddTask(ITask task, Schedule schedule)
        {
            switch (schedule.Type)
            {
            case ScheduleType.Periodical:
                var p = new PeriodicalTaskRunner(task, schedule.Frequency);
                _taskRunners.Add(p);
                break;

            case ScheduleType.Scheduled:
                var s = new ScheduledTaskRunner(task, schedule.RunAt);
                _taskRunners.Add(s);
                break;

            case ScheduleType.Task:
                _tasks.Add(task);
                break;

            default:
                throw new Exception(schedule.Type + " is not a supported schedule type.");
            }
        }
Ejemplo n.º 11
0
        protected async override void OnStartup(StartupEventArgs e)
        {
            var adapterLoader = new AdapterLoader();
            var result        = await adapterLoader.FindAdaptersAsync("Adapters", Cts.Token);

            if (result.HasError)
            {
                await Log.ReportErrorAsync(result.Message, Cts.Token);
            }

            var adapterManager = new Processor.AdapterManager(result.Adapters, EntityContextConnection, new DatabaseFeedback(EntityContextConnection));

            var pluginLoader     = new PluginLoader();
            var pluginFindResult = await pluginLoader.FindPluginsAsync("plugins", Cts.Token);

            if (pluginFindResult.HasError)
            {
                await Log.ReportErrorAsync(pluginFindResult.Message, Cts.Token);
            }

            var pluginManager = new Processor.PluginManager(pluginFindResult.Plugins, EntityContextConnection, new DatabaseFeedback(EntityContextConnection), adapterManager);


            var triggerRunner       = new TriggerRunner(new DatabaseFeedback(EntityContextConnection), new CommandProcessor(adapterManager, EntityContextConnection, new DatabaseFeedback(EntityContextConnection)), EntityContextConnection);
            var scheduledTaskRunner = new ScheduledTaskRunner(new DatabaseFeedback(EntityContextConnection), new CommandProcessor(adapterManager, EntityContextConnection, new DatabaseFeedback(EntityContextConnection)), EntityContextConnection, new CurrentTimeProvider());

            ZvsEngine = new ZvsEngine(new DatabaseFeedback(EntityContextConnection), adapterManager, pluginManager, EntityContextConnection, triggerRunner, scheduledTaskRunner);

            var splashscreen = new SplashScreen();

            splashscreen.SetLoadingTextFormat("Starting {0}", Utils.ApplicationNameAndVersion);
            splashscreen.Show();
            await Task.Delay(10);

#if DEBUG
            var sw = new Stopwatch();
            sw.Start();
#endif

#if (RELEASE)
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#endif
            using (var context = new ZvsContext(new ZvsEntityContextConnection()))
            {
                //Install Program Options
                var option =
                    await
                    context.ProgramOptions.FirstOrDefaultAsync(o => o.UniqueIdentifier == "LOGDIRECTION",
                                                               Cts.Token);

                if (option == null)
                {
                    var registerLogDirectionResult = await ProgramOption.TryAddOrEditAsync(context, new ProgramOption
                    {
                        UniqueIdentifier = "LOGDIRECTION",
                        Value            = "Descending"
                    }, Cts.Token);

                    if (registerLogDirectionResult.HasError)
                    {
                        await Log.ReportErrorAsync(registerLogDirectionResult.Message, Cts.Token);
                    }
                }
            }
            //using (var context = new ZvsContext(new ZvsEntityContextConnection()))
            //{
            //    var adapter = CreateFakeAdapter();
            //    context.Devices.Add(new Device
            //    {
            //        Name = "Light Switch",
            //        Location = "Living Room",
            //        Type = new DeviceType
            //        {
            //            Name = "Switch Device Type",
            //            UniqueIdentifier = "Switch",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Main Controller",
            //        Location = "Utility",
            //        Type = new DeviceType
            //        {
            //            Name = "Controller Type",
            //            UniqueIdentifier = "Controller",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Can Lights",
            //        Location = "Kitchen",
            //        Type = new DeviceType
            //        {
            //            Name = "Dimmer Type",
            //            UniqueIdentifier = "Dimmer",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Thermostat",
            //        Location = "Kitchen",
            //        Type = new DeviceType
            //        {
            //            Name = "Thermostat Type",
            //            UniqueIdentifier = "Thermostat",
            //            Adapter = adapter
            //        }
            //    });

            //    context.Devices.Add(new Device
            //    {
            //        Name = "Front Door",
            //        Location = "Entry",
            //        Type = new DeviceType
            //        {
            //            Name = "Doorlock Type",
            //            UniqueIdentifier = "Doorlock",
            //            Adapter = adapter
            //        }
            //    });
            //    var sensorDt = new DeviceType
            //    {
            //        Name = "Sensor Type",
            //        UniqueIdentifier = "Sensor",
            //        Adapter = adapter
            //    };
            //    var device = new Device
            //    {
            //        Name = "Motion Sensor",
            //        Location = "Entry",
            //        Type = sensorDt,
            //    };
            //    var value = new DeviceValue
            //    {
            //        Name = "Level",
            //        ValueType = DataType.BYTE,
            //        Value = "255"
            //    };
            //    device.Values.Add(value);
            //    context.Devices.Add(device);

            //     //context.SaveChanges();
            //}

            #region Create Logger

            await Log.ReportInfoFormatAsync(Cts.Token, "Init Complete ({0})", (Utils.DebugMode ? "Debug Mode" : "Release Mode"));

#if DEBUG
            await Log.ReportInfoAsync("--------------DUMPING ENVIRONMENT--------------", Cts.Token);

            await Log.ReportInfoFormatAsync(Cts.Token, "AppDataPath:{0}", Utils.AppDataPath);

            await Log.ReportInfoFormatAsync(Cts.Token, "AppPath:{0}", Utils.AppPath);

            await Log.ReportInfoFormatAsync(Cts.Token, "ApplicationNameAndVersion:{0}", Utils.ApplicationNameAndVersion);

            await Log.ReportInfoFormatAsync(Cts.Token, "ApplicationVersionLong:{0}", Utils.ApplicationVersionLong);

            await Log.ReportInfoFormatAsync(Cts.Token, "HasDotNet45:{0}", Utils.HasDotNet45());

            await Log.ReportInfoFormatAsync(Cts.Token, "HasSQLCE4:{0}", Utils.HasSQLCE4());

            await Log.ReportInfoFormatAsync(Cts.Token, "CommandLine:{0}", Environment.CommandLine);

            await Log.ReportInfoFormatAsync(Cts.Token, "CurrentDirectory:{0}", Environment.CurrentDirectory);

            await Log.ReportInfoFormatAsync(Cts.Token, "Is64BitOperatingSystem:{0}", Environment.Is64BitOperatingSystem);

            await Log.ReportInfoFormatAsync(Cts.Token, "Is64BitProcess:{0}", Environment.Is64BitProcess);

            await Log.ReportInfoFormatAsync(Cts.Token, "MachineName:{0}", Environment.MachineName);

            await Log.ReportInfoFormatAsync(Cts.Token, "OSVersion:{0}", Environment.OSVersion);

            await Log.ReportInfoFormatAsync(Cts.Token, "ProcessorCount:{0}", Environment.ProcessorCount);

            await Log.ReportInfoFormatAsync(Cts.Token, "UserDomainName:{0}", Environment.UserDomainName);

            await Log.ReportInfoFormatAsync(Cts.Token, "UserInteractive:{0}", Environment.UserInteractive);

            await Log.ReportInfoFormatAsync(Cts.Token, "UserName:{0}", Environment.UserName);

            await Log.ReportInfoFormatAsync(Cts.Token, "Version:{0}", Environment.Version);

            await Log.ReportInfoFormatAsync(Cts.Token, "WorkingSet:{0}", Environment.WorkingSet);

            await Log.ReportInfoAsync("--------------/DUMPING ENVIRONMENT--------------", Cts.Token);
#endif
            AppDomain.CurrentDomain.SetData("DataDirectory", Utils.AppDataPath);
            #endregion

            #region Checking for other running instances
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Checking for other running instances");
            await Task.Delay(10);

            try
            {
                _zvsMutex = Mutex.OpenExisting("zVirtualScenesGUIMutex");
                ProgramHasToClosePrompt(Utils.ApplicationName + " can't start because it is already running");
            }
            catch
            {
                //the specified mutex doesn't exist, we should create it
                _zvsMutex = new Mutex(true, "zVirtualScenesGUIMutex"); //these names need to match.
            }
            #endregion

            #region Check for .Net Framework 4.5
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Checking for .Net framework 4.5");
            await Task.Delay(10);

            if (!Utils.HasDotNet45())
            {
                ProgramHasToClosePrompt(
                    $"Microsoft .NET Framework 4.5 Full/Extended is required to run {Utils.ApplicationName}. \r\n\r\nPlease install Microsoft .NET Framework 4.5 and re-launch the application.");
            }
            #endregion

            #region Checking for Microsoft® SQL Server® Compact 4.0 SP1
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Checking for Microsoft® SQL Server® Compact 4.0 SP1");
            await Task.Delay(10);

            if (!Utils.HasSQLCE4())
            {
                ProgramHasToClosePrompt(
                    $"Microsoft® SQL Server® Compact 4.0 SP1 is required to run {Utils.ApplicationName}. \r\n\r\nPlease install Microsoft® SQL Server® Compact 4.0 SP1 and re-launch the application.");
            }
            #endregion

            #region Initializing and upgrading local database
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Initializing and migrating database");
            await Task.Delay(10);

            await Task.Run(() =>
            {
                using (var context = new ZvsContext())
                {
                    var configuration = new Configuration();
                    var migrator      = new DbMigrator(configuration);

                    migrator.Update();
                    context.Database.Initialize(true);
                }
            });

            #endregion

            //TODO: Check for VCRedist

            #region Start zvsEngine Services
            await Task.Delay(10);

            splashscreen.SetLoadingTextFormat("Starting zvsEngine services");
            await Task.Delay(10);

            //Initialize the zvsEngine

            try
            {
                await Task.Run(() => ZvsEngine.StartAsync(Cts.Token));
            }
            catch (Exception ex)
            {
                ProgramHasToClosePrompt(ex.Message);
            }

            #endregion

            //Create taskbar Icon
            TaskbarIcon = new ZVSTaskbarIcon();
            TaskbarIcon.ShowBalloonTip(Utils.ApplicationName, Utils.ApplicationNameAndVersion + " started", 3000, ToolTipIcon.Info);

            //close Splash Screen
            splashscreen.Close();

#if DEBUG
            sw.Stop();
            Debug.WriteLine("App Startup initialized in {0}", sw.Elapsed.ToString() as object);
#endif

            base.OnStartup(e);
        }
Ejemplo n.º 12
0
        public static async Task Updates_schedules_for_tasks_that_are_run()
        {
            var currentInstant = 30.December(2020).At(12, 07, 26).Utc();

            var dueTime    = currentInstant;
            var notDueTime = currentInstant.Plus(1.Seconds());

            var dailyNotificationSchedule  = new Schedule(ScheduledTaskType.DailyNotification, dueTime);
            var requestReminderSchedule    = new Schedule(ScheduledTaskType.RequestReminder, notDueTime);
            var weeklyNotificationSchedule = new Schedule(ScheduledTaskType.WeeklyNotification, dueTime);

            var schedules = new[]
            {
                dailyNotificationSchedule,
                requestReminderSchedule,
                weeklyNotificationSchedule
            };

            var mockScheduleRepository = new Mock <IScheduleRepository>();

            mockScheduleRepository.Setup(r => r.GetSchedules()).ReturnsAsync(schedules);

            var mockDateCalculator = new Mock <IDateCalculator>(MockBehavior.Strict);

            mockDateCalculator.Setup(d => d.ScheduleIsDue(dailyNotificationSchedule, null)).Returns(true);
            mockDateCalculator.Setup(d => d.ScheduleIsDue(requestReminderSchedule, null)).Returns(false);
            mockDateCalculator.Setup(d => d.ScheduleIsDue(weeklyNotificationSchedule, null)).Returns(true);

            var mockDailyNotification  = CreateMockScheduledTask(ScheduledTaskType.DailyNotification);
            var mockRequestReminder    = CreateMockScheduledTask(ScheduledTaskType.RequestReminder);
            var mockWeeklyNotification = CreateMockScheduledTask(ScheduledTaskType.WeeklyNotification);

            var dailyNotificationNextRunTime  = 31.December(2020).At(11, 0, 0).Utc();
            var weeklyNotificationNextRunTime = 31.December(2020).AtMidnight().Utc();

            mockDailyNotification.Setup(s => s.GetNextRunTime()).Returns(dailyNotificationNextRunTime);
            mockWeeklyNotification.Setup(s => s.GetNextRunTime()).Returns(weeklyNotificationNextRunTime);

            var scheduledTasks = new[]
            {
                mockDailyNotification.Object,
                mockRequestReminder.Object,
                mockWeeklyNotification.Object
            };

            var scheduledTaskRunner = new ScheduledTaskRunner(
                mockDateCalculator.Object,
                scheduledTasks,
                mockScheduleRepository.Object);

            await scheduledTaskRunner.RunScheduledTasks();

            mockScheduleRepository.Verify(r => r.GetSchedules(), Times.Once);
            mockScheduleRepository.Verify(
                r => r.UpdateSchedule(It.Is <Schedule>(s =>
                                                       s.ScheduledTaskType == ScheduledTaskType.DailyNotification &&
                                                       s.NextRunTime == dailyNotificationNextRunTime)),
                Times.Once);
            mockScheduleRepository.Verify(
                r => r.UpdateSchedule(It.Is <Schedule>(s =>
                                                       s.ScheduledTaskType == ScheduledTaskType.WeeklyNotification &&
                                                       s.NextRunTime == weeklyNotificationNextRunTime)),
                Times.Once);
            mockScheduleRepository.VerifyNoOtherCalls();
        }
        public async Task MultipleAsyncRequestsTest()
        {
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "MultipleAsyncRequestsTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());

            var logEntries = new List<LogEntry>();
            var ranstoredCommands = new List<int>();

            //Arrange 
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return Task.FromResult(0);
                }
            };

            var commandProcessor = new StubICommandProcessor
            {
                RunCommandAsyncNullableOfInt32StringStringCancellationToken = (commandId, argument, argument2, cancellationToken) =>
                {
                    if (commandId.HasValue) ranstoredCommands.Add(commandId.Value);
                    return Task.FromResult(Result.ReportSuccess());
                }
            };
            var currentTime = new StubITimeProvider { TimeGet = () => DateTime.Parse("5/21/14 15:02:20") };


            var cts = new CancellationTokenSource();
            var taskRunner = new ScheduledTaskRunner(log, commandProcessor, dbConnection, currentTime);

            await taskRunner.StartAsync(cts.Token);

            var command = new Command();
            var commandScheduledTask = new DataModel.ScheduledTask
            {
                IsEnabled = true,
                Name = "New Command added after start",
                Command = command
            };
            using (var context = new ZvsContext(dbConnection))
            {
                context.ScheduledTasks.Add(commandScheduledTask);
                var r2 = await context.TrySaveChangesAsync(cts.Token);
                Assert.IsFalse(r2.HasError, r2.Message);

                commandScheduledTask.StartTime = DateTime.Parse("5/20/14 15:02:20");
                var r = await context.TrySaveChangesAsync(cts.Token);
                Assert.IsFalse(r.HasError, r.Message);

                commandScheduledTask.StartTime = DateTime.Parse("5/20/14 15:02:21");
                var r3 = await context.TrySaveChangesAsync(cts.Token);
                Assert.IsFalse(r3.HasError, r.Message);
            }
            //Act
            await Task.Delay(2000, cts.Token);
            await taskRunner.StopAsync(cts.Token);

            //Assert
            Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Expected only info type log entries");
            Assert.IsTrue(ranstoredCommands.Count == 0, "Scheduled task runner did not run the correct amount of commands.");
        }
 public void ConstructorPath4()
 {
     //arrange, act
     var tm = new ScheduledTaskRunner(new StubIFeedback <LogEntry>(), new StubICommandProcessor(), new UnitTestDbConnection(), null);
     //assert - throws exception
 }
 public void ConstructorPath4()
 {
     //arrange, act
     var tm = new ScheduledTaskRunner(new StubIFeedback<LogEntry>(), new StubICommandProcessor(), new ZvsEntityContextConnection(), null);
     //assert - throws exception
 }
        public async Task NewTaskExecutesTest()
        {
            var dbConnection = new UnitTestDbConnection();

            Database.SetInitializer(new CreateFreshDbInitializer());

            var logEntries        = new List <LogEntry>();
            var ranstoredCommands = new List <int>();

            //Arrange
            var log = new StubIFeedback <LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return(Task.FromResult(0));
                }
            };

            var commandProcessor = new StubICommandProcessor
            {
                RunCommandAsyncNullableOfInt32StringStringCancellationToken = (commandId, argument, argument2, cancellationToken) =>
                {
                    if (commandId.HasValue)
                    {
                        ranstoredCommands.Add(commandId.Value);
                    }
                    return(Task.FromResult(Result.ReportSuccess()));
                }
            };
            var currentTime = new StubITimeProvider {
                TimeGet = () => DateTime.Parse("5/21/14 15:02:20")
            };


            var cts        = new CancellationTokenSource();
            var taskRunner = new ScheduledTaskRunner(log, commandProcessor, dbConnection, currentTime);

            var command = new Command();
            var commandScheduledTask = new DataModel.ScheduledTask
            {
                IsEnabled = true,
                Name      = "New Command added after start",
                Command   = command
            };

            using (var context = new ZvsContext(dbConnection))
            {
                context.ScheduledTasks.Add(commandScheduledTask);
                var r2 = await context.TrySaveChangesAsync(cts.Token);

                Assert.IsFalse(r2.HasError, r2.Message);

                await taskRunner.StartAsync(cts.Token);

                await Task.Delay(500, cts.Token);

                //Act
                commandScheduledTask.StartTime = DateTime.Parse("5/20/14 15:02:20");
                var r = await context.TrySaveChangesAsync(cts.Token);

                Assert.IsFalse(r.HasError, r.Message);

                await Task.Delay(1000, cts.Token);

                await taskRunner.StopAsync(cts.Token);
            }

            //Assert
            Assert.IsTrue(logEntries.All(o => o.Level == LogEntryLevel.Info), "Expected only info type log entries");
            Assert.IsTrue(ranstoredCommands.Count == 1, "Scheduled task runner did not run the correct amount of commands.");
        }
Ejemplo n.º 17
0
        public async Task StartAsyncTest()
        {
            //arrange 
            var dbConnection = new StubIEntityContextConnection { NameOrConnectionStringGet = () => "engine-StartAsyncTest" };
            Database.SetInitializer(new CreateFreshDbInitializer());

            var logEntries = new List<LogEntry>();
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return Task.FromResult(0);
                }
            };
            var isAdapterManagerInitialized = false;
            var isPluginManagerInitialized = false;
           

            var am = new StubIAdapterManager { StartAsyncCancellationToken = async (ct) =>isAdapterManagerInitialized = true };
            var pm = new StubIPluginManager { StartAsyncCancellationToken = async (ct) => isPluginManagerInitialized = true };
            var tr = new TriggerRunner(log, new StubICommandProcessor(), dbConnection);
            var st = new ScheduledTaskRunner(log, new StubICommandProcessor(), dbConnection,new CurrentTimeProvider());

            var engine = new ZvsEngine(log, am, pm, dbConnection, tr, st);

            //Act 
            await engine.StartAsync(CancellationToken.None);


            //assert 
            Assert.IsNotNull(engine);
            Assert.IsTrue(isAdapterManagerInitialized, "Adapter manager was not started!");
            Assert.IsTrue(isPluginManagerInitialized, "Plugin manager was not started!");
            Assert.IsTrue(engine.ScheduledTaskRunner.IsRunning, "Scheduled Task Runner was not started!");
            Assert.IsTrue(engine.TriggerRunner.IsRunning, "Trigger Runner was not started!");
        }
        public async Task StartPath2()
        {
            //Arrange 
            var logEntries = new List<LogEntry>();
            var log = new StubIFeedback<LogEntry>
            {
                ReportAsyncT0CancellationToken = (e, c) =>
                {
                    Console.WriteLine(e.ToString());
                    logEntries.Add(e);
                    return Task.FromResult(0);
                }
            };
            var cts = new CancellationTokenSource();
            var tm = new ScheduledTaskRunner(log, new StubICommandProcessor(), new ZvsEntityContextConnection(), new CurrentTimeProvider());

            //Act
            await tm.StartAsync(cts.Token);
            await tm.StartAsync(cts.Token);
            //Assert

            Assert.IsTrue(logEntries.Last().Level == LogEntryLevel.Warn);
        }