/// <inheritdoc/>
        public async Task CleanupAsync(IWrappedJobCancellationToken ct)
        {
            Ensure.ArgumentNotNull(ct, nameof(ct));

            try
            {
                var cts = CancellationTokenSource.CreateLinkedTokenSource(ct.ShutdownToken);
                if (configuration.Options.CleanupPeriod > 0)
                {
                    cts.CancelAfter(configuration.Options.CleanupPeriod * 1000);

                    // TODO: cleanup events as well
                    var command = new ClearObjectsCommand()
                    {
                        RefDate = DateTime.Now.AddMinutes(-configuration.Options.CleanupPeriod)
                    };

                    await mediator.Send(command, cts.Token);
                }
            }
            catch (OperationCanceledException)
            {
                logger.LogInformation($"Cleanup canceled.");
            }
            catch (Exception e)
            {
                logger.LogWarning(e, $"Cleanup failed. {e.Message}");
            }
        }
        public void ClearObjectsCommand_RefDate()
        {
            // Arrange
            var context  = GetService <IAmiUnitOfWork>();
            var mediator = GetService <IMediator>();
            var ct       = new CancellationToken();

            string filename1 = "SMIR.Brain.XX.O.CT.339203.nii";
            string dataPath1 = GetDataPath(filename1);
            var    command1  = new CreateObjectCommand()
            {
                OriginalFilename = filename1,
                SourcePath       = CreateTempFile(dataPath1)
            };

            string filename2 = "SMIR.Brain.XX.O.CT.346124.dcm";
            string dataPath2 = GetDataPath(filename2);
            var    command2  = new CreateObjectCommand()
            {
                OriginalFilename = filename2,
                SourcePath       = CreateTempFile(dataPath2)
            };

            string workingDir = GetWorkingDirectoryPath(string.Empty);
            var    command    = new ClearObjectsCommand()
            {
                RefDate = DateTime.Now
            };

            // Act
            var result1 = mediator.Send(command1, ct).Result;

            UpdateCreatedDate(context, result1, command.RefDate.Value.AddMinutes(-1));
            var result2 = mediator.Send(command2, ct).Result;

            var directories = Directory.EnumerateDirectories(workingDir);
            var result      = mediator.Send(command, ct).Result;

            // Assert
            Assert.IsNotNull(result1);
            Assert.IsNotNull(result2);
            Assert.IsTrue(result);
            Assert.IsTrue(Directory.Exists(workingDir));
            Assert.IsTrue(File.Exists(dataPath1));
            Assert.IsTrue(File.Exists(dataPath2));
            Assert.IsFalse(File.Exists(Path.Combine(workingDir, result1.SourcePath)));
            Assert.IsTrue(File.Exists(Path.Combine(workingDir, result2.SourcePath)));
        }
        public void ClearObjectsCommand()
        {
            // Arrange
            var    mediator   = GetService <IMediator>();
            var    ct         = new CancellationToken();
            string workingDir = GetWorkingDirectoryPath(string.Empty);
            var    command    = new ClearObjectsCommand();

            // Act
            var directories = Directory.EnumerateDirectories(workingDir);
            var result      = mediator.Send(command, ct).Result;

            // Assert
            Assert.IsTrue(result);
            Assert.IsTrue(Directory.Exists(workingDir));
            foreach (var directory in directories)
            {
                Assert.IsFalse(Directory.Exists(directory));
            }
        }
        /// <summary>
        /// Extension method used to initialize the application.
        /// </summary>
        /// <param name="builder">The application builder.</param>
        /// <param name="gatewayHubContext">The gateway hub context.</param>
        public static void InitApp(this IApplicationBuilder builder, IHubContext <GatewayHub> gatewayHubContext)
        {
            Ensure.ArgumentNotNull(builder, nameof(builder));
            Ensure.ArgumentNotNull(gatewayHubContext, nameof(gatewayHubContext));

            var serviceProvider = builder.ApplicationServices;

            if (serviceProvider == null)
            {
                throw new UnexpectedNullException($"{nameof(IServiceProvider)} could not be retrieved.");
            }

            var loggerFactory          = serviceProvider.EnsureGetService <ILoggerFactory>();
            var configuration          = serviceProvider.EnsureGetService <IApiConfiguration>();
            var mediator               = serviceProvider.EnsureGetService <IMediator>();
            var gatewayObserverService = serviceProvider.EnsureGetService <IGatewayObserverService>();
            var identityService        = serviceProvider.EnsureGetService <IIdentityService>();

            var logger = loggerFactory.CreateLogger <Startup>();

            logger.LogInformation("Add gateway observer.");
            gatewayObserverService.Add(new GatewayObserver(gatewayHubContext));

            logger.LogInformation("Ensure users exist.");
            identityService.EnsureUsersExistAsync(default(CancellationToken)).Wait();

            if (configuration.Options.CleanupPeriod > 0)
            {
                logger.LogInformation("Clear expired objects.");
                var command = new ClearObjectsCommand()
                {
                    RefDate = DateTime.UtcNow.AddMinutes(-configuration.Options.CleanupPeriod)
                };
                mediator.Send(command, default(CancellationToken)).Wait();
            }

            // logger.LogInformation("Reset tasks.");
            // mediator.Send(new ResetTaskStatusCommand(), default(CancellationToken)).Wait();
            logger.LogInformation("Application initialization finished.");
        }