Пример #1
0
        public void TokenCleanup()
        {
            IPersistedGrantStore store = Fixture.GetService <IPersistedGrantStore>();
            IHostedService       svc   = Fixture.GetService <IHostedService>();

            Client client = CreateClient();

            Provider.AddClientAsync(client).Wait();

            svc.StartAsync(default(CancellationToken)).Wait();

            PersistedGrant grant1 = CreateGrant(client.ClientId, "aaa", "t1");
            PersistedGrant grant2 = CreateGrant(client.ClientId, "aaa");

            grant1.Expiration = DateTime.Now.Add(TimeSpan.FromSeconds(15));
            grant2.Expiration = DateTime.Now.Add(TimeSpan.FromSeconds(25));

            store.StoreAsync(grant1).Wait();
            store.StoreAsync(grant2).Wait();

            List <PersistedGrant> results = store.GetAllAsync("aaa").Result?.ToList();

            Assert.Equal(2, results.Count);

            Task.Delay(20000).Wait();

            results = store.GetAllAsync("aaa").Result?.ToList();
            Assert.Equal(1, results.Count);

            Task.Delay(10000).Wait();

            results = store.GetAllAsync("aaa").Result?.ToList();
            Assert.Equal(0, results.Count);
        }
Пример #2
0
        /// <summary>
        /// Main method of File Manager
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Set up configuration sources
            var builder = new ConfigurationBuilder()
                          .AddCloudFoundry();

            IConfiguration configuration = builder.Build();

            //setup our DI
            var serviceProvider = new ServiceCollection()
                                  .ConfigureCloudFoundryOptions(configuration)
                                  .AddSingleton <IConfiguration>(configuration)
                                  .AddSingleton <IHostedService, ScheduledService>()
                                  .AddSingleton <IScheduledTask, FileMonitorCheckInboundFolderTask>()
                                  .AddSingleton <IScheduledTask, FileMonitorArchiveTask>()
                                  .AddSingleton <IScheduledTask, FileMonitorSfgTask>()
                                  .AddAutoMapper(typeof(Program))
                                  .BuildServiceProvider();

            _cancellationTokenSource = new CancellationTokenSource();
            _scheduledService        = serviceProvider.GetService <IHostedService>();

            Console.CancelKeyPress += StopService;

            _scheduledService.StartAsync(_cancellationTokenSource.Token);
            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                _cancellationTokenSource.Token.WaitHandle.WaitOne(-1);
            }
        }
        public async Task CanComponentsStart(string componentToError, string expected)
        {
            IServiceCollection serviceCollection = this.GetServiceDescriptors();
            string             fromHeaders       = componentToError == "from" ? "?WillError=true" : string.Empty;
            string             toHeaders         = componentToError == "to" ? "?WillError=true" : string.Empty;
            string             actual            = string.Empty;

            try
            {
                Kyameru.Route.From($"injectiontest:///mememe{fromHeaders}")
                .Process(this.processComponent.Object)
                .To($"injectiontest:///somewhere{toHeaders}")
                .Build(serviceCollection);

                IServiceProvider provider = serviceCollection.BuildServiceProvider();
                IHostedService   service  = provider.GetService <IHostedService>();
                await service.StartAsync(CancellationToken.None);

                await service.StopAsync(CancellationToken.None);
            }
            catch (Exception ex)
            {
                actual = ex.Message;
            }

            Assert.AreEqual(expected, actual);
        }
        public async Task CanActivateAndRun()
        {
            IServiceCollection serviceCollection = this.GetServiceDescriptors();
            Routable           routable          = null;

            this.processComponent.Reset();
            this.processComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) =>
            {
                routable = x;
            });

            Kyameru.Route.From("injectiontest:///mememe")
            .Process(this.processComponent.Object)
            .To("injectiontest:///somewhere")
            .Build(serviceCollection);


            IServiceProvider provider = serviceCollection.BuildServiceProvider();
            IHostedService   service  = provider.GetService <IHostedService>();
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.AreEqual("Injected Test Complete", routable?.Body);
        }
 public async Task StartAsync(CancellationToken cancellationToken)
 {
     if (_next != null)
     {
         await _next.StartAsync(cancellationToken);
     }
 }
        public async Task StartAsync_RegisterRunTime_ShouldRegisterAllLifetimeCallbacks()
        {
            await hostedService.StartAsync(CancellationToken.None);

            lifetime.VerifyGet(x => x.ApplicationStarted, Times.Once);
            lifetime.VerifyGet(x => x.ApplicationStopping, Times.Once);
        }
Пример #7
0
        private async Task <bool> RunProcess(string callsContain)
        {
            Component.Test.GlobalCalls.Calls.Clear();
            IHostedService service = this.GetRoute();
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            return(Kyameru.Component.Test.GlobalCalls.Calls.Contains(callsContain));
        }
Пример #8
0
        public async Task CanExecuteAtomic()
        {
            Component.Test.GlobalCalls.Calls.Clear();
            IHostedService service = this.GetNoErrorChain();
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.AreEqual(6, this.GetCallCount());
        }
Пример #9
0
        public async Task AddHeaderErrors(bool secondFunction)
        {
            Component.Test.GlobalCalls.Calls.Clear();
            IHostedService service = this.GetHeaderError(secondFunction);
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.AreEqual(6, this.GetCallCount());
        }
Пример #10
0
        public async Task CanExecuteMultipleChains()
        {
            Component.Test.GlobalCalls.Calls.Clear();
            IHostedService service = this.AddComponent(true);

            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.AreEqual(20, this.GetCallCount());
        }
Пример #11
0
 public IActionResult PublishWeeklyStats()
 {
     try
     {
         _timeHostedService.StopAsync(new System.Threading.CancellationToken());
         _timeHostedService.StartAsync(new System.Threading.CancellationToken());
         return(Ok("Published"));
     }
     catch (Exception e)
     {
         return(Ok("Not published: \n" + e.Message));
     }
 }
Пример #12
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                await _service.StartAsync(cancellationToken);

                _logger.LogInformation($"Service {_service.GetType().FullName} started");
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, $"Error starting hosted service {_service.GetType().FullName}");
                _applicationLifetime.StopApplication();
            }
        }
Пример #13
0
        /// <summary>启动服务</summary>
        /// <param name="service"></param>
        public override void Run(IHostedService service)
        {
            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }

            _service = service;

            var source = new CancellationTokenSource();

            service.StartAsync(source.Token);

            // 阻塞
            Thread.Sleep(-1);
        }
Пример #14
0
        public async Task RunAsync(CancellationToken cancellationToken)
        {
            async Task Serve(CancellationToken token)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                await _service.StartAsync(cancellationToken);

                while (!token.IsCancellationRequested)
                {
                    await Task.Delay(1000);
                }

                await _service.StopAsync(default);
Пример #15
0
        public async Task AtomicError()
        {
            Routable routable = null;

            this.errorComponent.Reset();
            this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) =>
            {
                routable = x;
            });
            this.processComponent.Reset();

            IHostedService service = this.GetHostedService(false, false, true);
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.IsTrue(this.IsInError(routable, "Atomic Component"));
        }
Пример #16
0
        public async Task FromException()
        {
            Routable routable = null;

            this.errorComponent.Reset();
            this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) =>
            {
                routable = x;
            });
            this.processComponent.Reset();

            IHostedService service = this.GetHostedService(true);
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.IsNull(routable);
        }
Пример #17
0
        public async Task ErrorComponentErrors()
        {
            Routable routable = null;

            this.errorComponent.Reset();
            this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) =>
            {
                routable = x;
                throw new ProcessException("Manual Error", new IndexOutOfRangeException("Random index"));
            });

            IHostedService service = this.GetHostedService(false, false, true);
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.IsTrue(this.IsInError(routable, "Error Component"));
        }
Пример #18
0
        public async Task CanRunDIComponent()
        {
            AutoResetEvent autoResetEvent = new AutoResetEvent(false);
            Routable       routable       = null;

            this.diProcessor.Reset();
            this.diProcessor.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) =>
            {
                routable = x;
            });
            IHostedService service = this.SetupDIComponent();

            await service.StartAsync(CancellationToken.None);

            autoResetEvent.WaitOne(TimeSpan.FromSeconds(5));
            await service.StopAsync(CancellationToken.None);

            Assert.AreEqual("Yes", routable.Headers["ComponentRan"]);
        }
Пример #19
0
        private async void bOperation_Click(object sender, EventArgs e)
        {
            switch (HostedServiceStatus)
            {
            case HostedServiceStatus.Starting:
            case HostedServiceStatus.Stopping:
                break;

            case HostedServiceStatus.Running:
                UpdateServiceStatus(HostedServiceStatus.Stopping);
                try
                {
                    await bindedService.StopAsync();
                }
                catch (Exception ex)
                {
                    logError("停止服务时出错:" + ex.Message, ex);
                    UpdateServiceStatus(HostedServiceStatus.Running, true);
                    break;
                }
                UpdateServiceStatus(HostedServiceStatus.Stopped);
                break;

            case HostedServiceStatus.Stopped:
                UpdateServiceStatus(HostedServiceStatus.Starting);
                try
                {
                    await bindedService.StartAsync();
                }
                catch (Exception ex)
                {
                    logError("启动服务时出错:" + ex.Message, ex);
                    UpdateServiceStatus(HostedServiceStatus.Stopped, true);
                    break;
                }
                UpdateServiceStatus(HostedServiceStatus.Running);
                break;

            default:
                break;
            }
        }
Пример #20
0
        private void ServiceQueuedMainCallback(Object state)
        {
            //var args = (String[])state;
            try
            {
                //OnStart(args);
                var source = new CancellationTokenSource();
                _service.StartAsync(source.Token);
                //WriteLogEntry(SR.StartSuccessful);
                _status.checkPoint   = 0;
                _status.waitHint     = 0;
                _status.currentState = ServiceControllerStatus.Running;
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);

                _status.currentState = ServiceControllerStatus.Stopped;
            }
            _startCompletedSignal.Set();
        }
Пример #21
0
        public async Task ComponentError()
        {
            Routable routable = null;

            this.errorComponent.Reset();
            this.errorComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) =>
            {
                routable = x;
            });
            this.processComponent.Reset();
            this.processComponent.Setup(x => x.Process(It.IsAny <Routable>())).Callback((Routable x) =>
            {
                throw new Kyameru.Core.Exceptions.ProcessException("Manual Error");
            });

            IHostedService service = this.GetHostedService();
            await service.StartAsync(CancellationToken.None);

            await service.StopAsync(CancellationToken.None);

            Assert.IsTrue(this.IsInError(routable, "Processing component"));
        }
Пример #22
0
        public void SaveResults(User currentUser, TrainingSetupModel model)
        {
            var session = new TrainingSession
            {
                StartDate    = model.StartDate,
                User         = currentUser,
                TrainingLogs = new List <TrainingLog>(),
                Status       = TrainingSessionStatus.InProgress,
                EmotionType  = EmotionUtil.GetEmotionType(model.SelectedEmotion)
            };
            var sources = model.Sources.Select(x => new TrainingSource
            {
                SourceUrl       = x,
                TrainingSession = session
            });

            session.TrainingSources = sources.ToList();
            trainingRepository.Add(session);


            // HERE WE SHOULD START LOGGING PROCESS
            hostedService.StartAsync(new CancellationToken(false));
        }
Пример #23
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var scope = _logger.BeginScope(GetScopeState());

            _logger.LogInformation("Starting...");
            var stopwatch = Stopwatch.StartNew();

            try
            {
                await _inner.StartAsync(cancellationToken);

                var elapsed = Math.Round(stopwatch.Elapsed.TotalMilliseconds, 0).ToString(CultureInfo.InvariantCulture);
                _logger.LogInformation($"Took {elapsed}ms to start.");
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, ex.Message);
                throw;
            }
            finally
            {
                scope.Dispose();
            }
        }
Пример #24
0
 public void ShouldInitEventScopeAndSubscribeToAccessorEventTest()
 {
     _messagingService.StartAsync(CancellationToken.None);
     _eventConnectionContextMock.Verify(x => x.EventScope(), Times.Once);
     _taskEventAccessorMock.Verify(x => x.OnStatusUpdated(It.IsAny <Action <ITaskStatusUpdatedMessage> >()), Times.Once);
 }
Пример #25
0
 /// <inheritdoc />
 public Task StartAsync(CancellationToken cancellationToken)
 => _hostedServiceImplementation.StartAsync(cancellationToken);
Пример #26
0
 public void Start()
 {
     Task.Factory
     .StartNew(async() => await _service.StartAsync(CancellationToken.None));
 }
        public async Task AddHostedService(IHostedService service)
        {
            _services.Add(service);

            await service.StartAsync(_lifetime.ApplicationStopping);
        }
Пример #28
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     return(_hostedService.StartAsync(cancellationToken));
 }
Пример #29
0
        public async Task <IActionResult> StartCounter()
        {
            await counterService.StartAsync(new CancellationToken(false));

            return(Ok("Counter Service Started"));
        }
Пример #30
0
 public Task StartAsync(CancellationToken cancellationToken) => _underlyingService.StartAsync(cancellationToken);