Example #1
0
        public void Should_add_tasks_2level()
        {
            //              ROOT
            //              /  \
            //          TASK1   TASK2
            //Arrange
            var root          = new TaskItem("Root");
            var task1         = new TaskItem("Task1");
            var task2         = new TaskItem("Task2");
            var taskStructure = taskFactory.Create <ITask>();

            taskStructure.AddRoot(root);
            taskStructure.AddChild(root, task1);
            taskStructure.AddChild(root, task2);

            //Act
            var actual = taskStructure.Execute(root);

            //Assert
            var expected = new List <string>()
            {
                "Task2", "Task1", "Root"
            };

            Assert.AreEqual(actual.Count, expected.Count);
            for (int i = 0; i < actual.Count; i++)
            {
                Assert.AreEqual(actual[i], expected[i]);
            }
        }
        private void Start(string queueName, bool privateQueue, LocaleQueueMode localeQueueMode, bool transactional, Action <object, CancellationToken> messageHandler, Action heartbeatHandler, int heartRateMilliseconds, bool multiThreadedHandler, bool syncMode, CancellationToken cancellationToken)
        {
            if (_cancellationTokenSource != null)
            {
                throw new ArgumentException("Handler not stopped");
            }

            if (heartRateMilliseconds <= 0 && heartbeatHandler != null)
            {
                throw new ArgumentException("Invalid Heart Rate", nameof(heartRateMilliseconds));
            }

            _queueName = queueName;
            _cancellationTokenSource = new CancellationTokenSource();
            _syncMode                      = syncMode;
            _queue                         = _queueFactory.CreateLocale(_queueName, privateQueue, localeQueueMode, transactional, AccessMode.Receive);
            _messageHandler                = messageHandler ?? throw new ArgumentNullException(nameof(messageHandler));
            _heartbeatHandler              = heartbeatHandler;
            _heartRateMilliseconds         = heartRateMilliseconds;
            _multiThreadedHandler          = multiThreadedHandler;
            _cancellationTokenRegistration = cancellationToken.Register(Stop);

            if (_syncMode)
            {
                Process();
            }
            else
            {
                _processTask = _taskFactory.Create();
                _processTask.Start(Process, _cancellationTokenSource.Token);
            }

            _logger.Information("Queue Handler started {QueueName}", _queueName);
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="hd"></param>
        private void CreateDevices(Hardware hd)
        {
            // device
            //
            foreach (IDPU dpu in this.DPUs)
            {
                IDeviceSourceProvider deviceSourceProvider = dpu.DeviceSourceProvider;
                deviceSourceProvider.SourceConfigs = this.SourceConfigs;
                IDeviceSource[] deviceSources = deviceSourceProvider.GetDeviceSources();
                foreach (IDeviceSource deviceSource in deviceSources)
                {
                    IDeviceFactory factory = dpu.DeviceFactory;
                    IDevice        device  = factory.Create(deviceSource);


                    device.DeviceSource = deviceSource;

                    // find station by device
                    //
                    Guid     stationGuid = deviceSource.StationGuid;
                    IStation station     = hd.Stations.Find(stationGuid);
                    if (station == null)
                    {
                        string s = string.Format("not find station by guid '{0}'", stationGuid);
                        throw new Exception(s);
                    }
                    station.Devices.Add(device);
                    device.Station = station;

                    ITaskFactory taskFactory = dpu.TaskFactory;
                    taskFactory.Create(device);
                }
            }
        }
Example #4
0
        public void Do <TTask>()
            where TTask : ITask <TSubject>
        {
            CheckForSubject();

            var task = factory.Create <TTask>();

            task.Run(subject);
        }
        public QueueHandlerSyncTests()
        {
            _queue = Substitute.For <ILocaleQueue>();

            _queueFactory = Substitute.For <IQueueFactory>();
            _queueFactory.CreateLocale(Arg.Any <string>(), Arg.Any <bool>(), Arg.Any <LocaleQueueMode>(), Arg.Any <bool>(), Arg.Any <AccessMode>()).Returns(_queue);
            _taskFactory = Substitute.For <ITaskFactory>();
            _taskFactory.Create().Returns(new SyncTestTask());
            _cancellationToken = new CancellationToken();
        }
Example #6
0
        private void SaveTask(TaskDto task, int userId)
        {
            var user    = _userRepository.GetByUserID(userId);
            var project = _projectRepository.GetById(task.ProjectId);

            Trex.Server.Core.Model.Task parentTask = null;

            if (task.ParentTaskId.HasValue)
            {
                parentTask = _taskRepository.GetById(task.ParentTaskId.Value);
            }

            if (!_taskRepository.ExistsByGuid(task.Guid))
            {
                var newTask = _taskFactory.Create(task.Guid,
                                                  task.CreateDate,
                                                  task.ChangeDate,
                                                  task.Name,
                                                  task.Description,
                                                  user,
                                                  project,
                                                  null,
                                                  parentTask,
                                                  task.WorstCaseEstimate,
                                                  task.BestCaseEstimate,
                                                  task.RealisticEstimate,
                                                  task.TimeEstimated,
                                                  task.TimeLeft
                                                  );

                _taskRepository.SaveOrUpdate(newTask);
                task.Id   = newTask.TaskID;
                task.Guid = newTask.Guid;
            }
            else
            {
                var originalTask = _taskRepository.GetByGuid(task.Guid);

                originalTask.TaskName          = task.Name;
                originalTask.Description       = task.Description;
                originalTask.ParentTask        = parentTask;
                originalTask.Project           = project;
                originalTask.RealisticEstimate = task.RealisticEstimate;
                originalTask.BestCaseEstimate  = task.BestCaseEstimate;
                originalTask.WorstCaseEstimate = task.WorstCaseEstimate;
                originalTask.TimeEstimated     = task.TimeEstimated;
                originalTask.TimeLeft          = task.TimeLeft;

                _taskRepository.SaveOrUpdate(originalTask);
            }
        }
Example #7
0
        public TaskItem Add(TaskItem item)
        {
            try
            {
                var task   = _mapper.Map <TaskDTO>(item);
                var result = _factory.Create(task);
                return(result);
            }
            catch (Exception e)
            {
                _logger.LogError($"There is a problem with save Task : {e}");
            }

            return(null);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="command"></param>
        public TaskCreateResult Create(TaskCreateCommand command)
        {
            using (var transaction = new TransactionScope())
            {
                var taskName     = new TaskName(command.TaskName);
                var categoryName = new CategoryName(command.CategoryName);

                var task = taskFactory.Create(taskName, categoryName);

                taskRepository.Save(task);

                transaction.Complete();

                return(new TaskCreateResult(task));
            }
        }
Example #9
0
        public IPromise Create(Action action, PromisePriority priority)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("PromiseFactory");
            }

            switch (priority)
            {
            case PromisePriority.Normal:
                return(new NormalPromise(this, _taskFactory, _taskFactory.Create(action)));

            case PromisePriority.Immediate:
                return(new NormalPromise(this, _taskFactory, _taskFactory.CreateImmediately(action)));

            default:
                return(new NormalPromise(this, _taskFactory, _taskFactory.Create(action, (int)priority)));
            }
        }
Example #10
0
        public IActionResult DownloadReports([FromBody] DownloadReportsRequest request)
        {
            string downloadDirectory = Path.Combine(_hostingEnvironment.ContentRootPath, "Reports");

            if (!Directory.Exists(downloadDirectory))
            {
                Directory.CreateDirectory(downloadDirectory);
            }

            string dirName = "Reports";

            if (!string.IsNullOrEmpty(request.DownloadFromSubDirectory))
            {
                var destDirPath = Path.GetFullPath(Path.Combine(downloadDirectory + Path.DirectorySeparatorChar));
                downloadDirectory = Path.GetFullPath(Path.Combine(downloadDirectory, request.DownloadFromSubDirectory));

                if (!downloadDirectory.StartsWith(destDirPath))
                {
                    throw new HttpError(HttpStatusCode.Forbidden);
                }

                dirName = request.DownloadFromSubDirectory;
            }

            var zipDirectory = Path.Combine(downloadDirectory, "output");

            var task = _taskFactory.Create <PackageTask>(zipDirectory);

            string zipFilename = string.IsNullOrEmpty(request.DownloadFromSubDirectory)
                ? "Reports.zip"
                : $"{request.DownloadFromSubDirectory}.zip";

            if (Directory.GetFiles(downloadDirectory).Length == 0)
            {
                throw new HttpError(HttpStatusCode.NotFound, "NoReportsFound");
            }

            task.AddDirectoryToPackage(downloadDirectory, dirName, false).ZipPackage(zipFilename, false).Execute(_taskSession);
            string zipPath = Path.Combine(zipDirectory, zipFilename);

            Stream fs = System.IO.File.OpenRead(zipPath);

            return(File(fs, "application/zip", zipFilename));
        }
Example #11
0
        public object Post()
        {
            var statuses = _repository.GetStatuses().ToDictionary(x => x.Name, x => x.Id);
            var task     = _factory.Create(statuses);

            _repository.Create(task);

            _repository.UpdateStatus(task.Guid, statuses["running"]);

            var background = System.Threading.Tasks.Task.Run(async() =>
            {
                await BackgroundWork(task.Guid, statuses);
            });

            Response.StatusCode = 202;

            return(new {
                Guid = task.Guid
            });
        }
Example #12
0
 internal T CreateTask <T>()
     where T : ITask
 {
     return(_taskFactory.Create <T>());
 }
        public async Task <IActionResult> Prepare()
        {
            string frameworkName = Assembly.GetEntryAssembly()?.GetCustomAttribute <TargetFrameworkAttribute>()
                                   ?.FrameworkName;
            var  isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            bool isNetCore = frameworkName.StartsWith(".NETCoreApp");

            var latestRelease = await _client.Repository.Release.GetLatest(_owner, _reponame);

            List <ReleaseAsset> assets;

            ReleaseAsset asset = null;

            if (isNetCore)
            {
                string netCoreVersion = frameworkName.Replace(".NETCoreApp,Version=", string.Empty);
                if (isWindows)
                {
                    assets = latestRelease.Assets.Where(x => x.Name.Contains("Windows")).ToList();
                }
                else
                {
                    assets = latestRelease.Assets.Where(x => x.Name.Contains("Linux")).ToList();
                }

                switch (netCoreVersion.ToLowerInvariant())
                {
                case "v2.1":
                {
                    asset = assets.FirstOrDefault(x => x.Name.Contains("NetCoreApp2.1"));
                    break;
                }

                case "v2.0":
                {
                    asset = assets.FirstOrDefault(x => x.Name.Contains("NetCoreApp2.0"));
                    break;
                }

                case "v1.1":
                {
                    asset = assets.FirstOrDefault(x => x.Name.Contains("NetCoreApp1.1"));
                    break;
                }
                }
            }
            else
            {
                asset = latestRelease.Assets.FirstOrDefault(x => x.Name.Contains("Net462"));
            }

            var rootDir = _hostingEnvironment.ContentRootPath;

            if (!Directory.Exists(Path.Combine(rootDir, "Updates")))
            {
                Directory.CreateDirectory(Path.Combine(rootDir, "Updates"));
            }

            if (!Directory.Exists(Path.Combine(rootDir, "Updates/WebApi")))
            {
                Directory.CreateDirectory(Path.Combine(rootDir, "Updates/WebApi"));
            }

            var filename = Path.Combine(rootDir, "Updates/FlubuCoreWebApi_LatestRelease.zip");

#if !NETCOREAPP1_1
            var wc = new WebClient();
            await wc.DownloadFileTaskAsync(asset.BrowserDownloadUrl, filename);
#endif
            var unzipTask = _taskFactory.Create <UnzipTask>(filename, Path.Combine(rootDir, "Updates/WebApi"));
            unzipTask.Execute(_taskSession);

            _taskFactory
            .Create <UpdateJsonFileTask>(Path.Combine(rootDir, "Updates/WebApi/DeploymentConfig.json"))
            .Update("DeploymentPath", rootDir)
            .Update("IsUpdate", "true").Execute(_taskSession);

            return(View());
        }
Example #14
0
 public void Initialise()
 {
     taskFactory = new TaskFactory();
     //Factory creates instance
     taskStructure = taskFactory.Create <ITask>();
 }
Example #15
0
        private async Task ExecuteTaskAsync(TaskInfo taskInfo, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(taskInfo, nameof(taskInfo));

            using ITask task = _taskFactory.Create(taskInfo);
            task.RunId       = task.RunId ?? taskInfo.RunId;

            if (task == null)
            {
                _logger.LogWarning("Not supported task type: {taskTypeId}", taskInfo.TaskTypeId);
                return;
            }

            TaskResultData result = null;

            try
            {
                try
                {
                    if (taskInfo.IsCanceled)
                    {
                        // For cancelled task, try to execute it for potential cleanup.
                        task.Cancel();
                    }

                    Task <TaskResultData> runningTask = Task.Run(() => task.ExecuteAsync());
                    _activeTaskRecordsForKeepAlive[taskInfo.TaskId] = task;

                    result = await runningTask;
                }
                catch (RetriableTaskException ex)
                {
                    _logger.LogError(ex, "Task {taskId} failed with retriable exception.", taskInfo.TaskId);

                    try
                    {
                        await _consumer.ResetAsync(taskInfo.TaskId, new TaskResultData(TaskResult.Fail, ex.Message), taskInfo.RunId, cancellationToken);
                    }
                    catch (Exception resetEx)
                    {
                        _logger.LogError(resetEx, "Task {taskId} failed to reset.", taskInfo.TaskId);
                    }

                    // Not complete the task for retriable exception.
                    return;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Task {taskId} failed.", taskInfo.TaskId);
                    result = new TaskResultData(TaskResult.Fail, ex.Message);
                }

                try
                {
                    await _consumer.CompleteAsync(taskInfo.TaskId, result, task.RunId, cancellationToken);

                    _logger.LogInformation("Task {taskId} completed.", taskInfo.TaskId);
                }
                catch (Exception completeEx)
                {
                    _logger.LogError(completeEx, "Task {taskId} failed to complete.", taskInfo.TaskId);
                }
            }
            finally
            {
                _activeTaskRecordsForKeepAlive.Remove(taskInfo.TaskId, out _);
            }
        }