protected void Application_Start(object sender, EventArgs e)
 {
     var connectionString = ConfigurationManager.ConnectionStrings["Storage"].ConnectionString;
     var storageAccount = CloudStorageAccount.Parse(connectionString);
     BackgroundWorker = new BackgroundWorkerService(storageAccount);
     Task.Run(() => BackgroundWorker.DoWork("Application_Start"));
 }
        public async Task CheckStateOnFinishedWork()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            bool finishedExecuting = false;
            bool continueExecution = true;

            service.RunAsync(CreateTestTaskAsync(300, token =>
            {
                if (!continueExecution)
                {
                    finishedExecuting = true;
                }
                return(continueExecution);
            }));

            // Our service should now be processing the task until we set the tas as finished
            Assert.IsTrue(service.IsProcessingTasks, "Service did not process the work");

            continueExecution = false; // We set the task as finished
            while (!finishedExecuting) // We wait until our work has noticed our flag
            {
                await Task.Delay(100);
            }

            // At this point our artificial work should have finished.
            // The service should no longer be processing work.
            Assert.IsFalse(service.IsProcessingTasks, "Service did not finish processing work");
        }
Beispiel #3
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            _cts = new CancellationTokenSource();

            Task.Run(() => {
                try
                {
                    BackgroundWorkerService.RunBackgroundWorkerService(_cts.Token).Wait();
                }
                catch (System.OperationCanceledException ex)
                {
                    throw;
                }
                finally
                {
                    if (_cts.IsCancellationRequested)
                    {
                        var message = new CancelledMessage();
                        Device.BeginInvokeOnMainThread(
                            () => MessagingCenter.Send(message, "CancelledMessage")
                            );
                    }
                }
            }, _cts.Token);

            return(StartCommandResult.Sticky);
        }
        public async Task StopServiceWithWorkUngracefulShutdown()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            int stopCheckDelay          = 300;
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            bool allowStop             = false;
            bool cancellationWasCalled = false;
            var  workTask = CreateTestTaskAsync(stopCheckDelay, cancellationToken =>
            {
                if (allowStop)
                {
                    cancellationWasCalled = cancellationToken.IsCancellationRequested;
                    return(false);
                }

                return(true);
            });

            service.RunAsync(workTask);
            service.Dispose();
            Assert.IsFalse(service.IsStarted, "Service was still runing despite being disposed");
            Assert.IsTrue(service.IsProcessingTasks, "Service was not processing unfinished work when disposed");
            allowStop = true;
            var waitDelay = stopCheckDelay * 2;
            await Task.Delay(waitDelay); // Make sure our work has a chance to react

            Assert.IsFalse(service.IsProcessingTasks, $"Service was still processing work { waitDelay } milliseconds after stopping");
            Assert.IsTrue(cancellationWasCalled, "Cancellation was not called");
        }
        public BackgroundWorkerServiceTests()
        {
            _subscriberMock      = new Mock <IMQSubscriber>();
            _producerMock        = new Mock <IProducer>();
            _consumerfactoryMock = new Mock <IConsumerFactory>();

            sut = new BackgroundWorkerService(_subscriberMock.Object, _producerMock.Object, _consumerfactoryMock.Object);
        }
        public async Task StartService()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            Assert.IsTrue(service.IsStarted, "Service was not started");
        }
 static void Main()
 {
     Console.WriteLine("Starting web job");
     var connectionString = ConfigurationManager.ConnectionStrings["Storage"].ConnectionString;
     var storageAccount = CloudStorageAccount.Parse(connectionString);
     var backgroundWorker = new BackgroundWorkerService(storageAccount);
     Task.Run(() => backgroundWorker.DoWork("WebJob")).Wait();
 }
        public async Task StopService()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            await service.StopAsync(cancellationTokenSource.Token);

            Assert.IsFalse(service.IsStarted, "Service did not stop");
        }
        public async Task CheckStateOnRegistredWork()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            bool continueExecution = true;

            service.RunAsync(CreateTestTaskAsync(1000, token =>
            {
                return(continueExecution);
            }));
            Assert.IsTrue(service.IsProcessingTasks, "Service did not start processing work");
            continueExecution = false;
        }
Beispiel #10
0
        public async Task ExceptionEventWithoutSubscriber()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            service.RunAsync(async token =>
            {
                throw new Exception("Win!");
            });

            await Task.Delay(100); // Since our test task does not contain anything asynchronous we will have to wait for it to execute

            // We only need to determine that the exception does not disrupt the application outside of the task in progress
        }
Beispiel #11
0
 public void RejectWorkOnUnstartedService()
 {
     try
     {
         var service = new BackgroundWorkerService();
         Assert.ThrowsException <InvalidOperationException>(() =>
         {
             service.RunAsync((cancellationToken) => Task.CompletedTask);
         }, "No exception was thrown");
     }
     catch (Exception ex) when(!(ex is InvalidOperationException) && !(ex is AssertFailedException))
     {
         Assert.Fail($"Wrong exception was thrown: '{ ex.GetType().Name }'");
     }
 }
        public async void TestRunBackgroundWorker()
        {
            var platformServicesFake = A.Fake <IPlatformServices>();

            Device.PlatformServices = platformServicesFake;

            DatabaseMigrator.Migrate(_connection, _migrationSkriptFolderPath);


            MessagingCenter.Subscribe <StartBackgroundWorkingServiceMessage>(this, MessageHelper.START_BACKGROUND_WORKING_SERVICE_MESSAGE, message =>
            {
                var msg = new DiagnosticMessage("Start Background Working Service");
                output.WriteLine("{0}", msg.Message);
            });

            MessagingCenter.Subscribe <StopBackgroundWorkingServiceMessage>(this, MessageHelper.STOP_BACKGROUND_WORKING_SERVICE_MESSAGE, message =>
            {
                var msg = new DiagnosticMessage("Stop Background Working Service");
                output.WriteLine("{0}", msg.Message);
            });

            MessagingCenter.Subscribe <ElementFinishedMessage>(this, MessageHelper.ELEMENT_FINISHED_MESSAGE, message =>
            {
                var msg = new DiagnosticMessage("Element processed");
                output.WriteLine("{0}", msg.Message);
            });

            var deleteAll = BackgroundQueueService.EmptyQueue(_connection).Result;

            Assert.True(deleteAll);

            var testSpotGuid = Guid.NewGuid();
            var testLat      = 48.45;
            var testLng      = 13.9167;

            var result = BackgroundQueueService.PushWheaterRequestToBackgroundQueue(_connection, testSpotGuid, testLat, testLng).Result;

            Assert.True(result != Guid.Empty);

            await BackgroundWorkerService.RunBackgroundWorkerService(_connection, new CancellationToken(false));

            int cnt = BackgroundQueueService.GetQueueElementCount(_connection).Result;

            Assert.Equal(0, cnt);
        }
Beispiel #13
0
        public async Task StopServiceWithWorkGracefulShutdown()
        {
            int stopCheckDelay          = 300;
            var cancellationTokenSource = new CancellationTokenSource();
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            bool allowStop             = false;
            bool cancellationWasCalled = false;

            service.RunAsync(CreateTestTaskAsync(stopCheckDelay, (token) =>
            {
                // If we want to stop the work
                if (allowStop)
                {
                    cancellationWasCalled = token.IsCancellationRequested;
                    return(false);
                }

                return(true);
            }));

            // We will stop the service, this should not stop the work from finishing
            // We cannot await this task at this point in time as it will not be able to finish until stopToken.IsStopped is set further down (deadlock).
            // We can call await after we have stopped the work to view the status
            var stoppingTask = service.StopAsync(cancellationTokenSource.Token);

            Assert.IsFalse(service.IsStarted, "Service was still runing despite being told to stop");
            Assert.IsTrue(service.IsProcessingTasks, "Service stopped processing unfinished work when stopped");

            // Now we will simulate our work finishing.
            allowStop = true;
            var waitDelay = (stopCheckDelay * 2) + 1;
            await Task.Delay(waitDelay); // We will wait until we are 100% sure our testwork has registered the stop.

            Assert.IsFalse(service.IsProcessingTasks, $"Service was still processing work { waitDelay } milliseconds after stopping");
            await stoppingTask;

            Assert.IsTrue(stoppingTask.IsCompletedSuccessfully, "Stopping task did not complete successfully");
            Assert.IsTrue(cancellationWasCalled, "Cancellation was not called");
        }
Beispiel #14
0
        public async Task ExceptionEventWithSubscriber()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            bool exceptionCallbackWasCalled = false;

            service.OnException += (sender, e) =>
            {
                exceptionCallbackWasCalled = true;
            };
            service.RunAsync(async token =>
            {
                throw new Exception("Win!");
            });

            await Task.Delay(100); // Since our test task does not contain anything asynchronous we will have to wait for it to execute

            Assert.IsTrue(exceptionCallbackWasCalled, "Exception event was not raised");
        }
        public void Setup()
        {
            if (Directory.Exists(SitesPath))
            {
                Directory.Delete(SitesPath, true);
            }

            if (Directory.Exists(ExePath))
            {
                Directory.Delete(ExePath, true);
            }

            Directory.CreateDirectory(Path.Combine(SitesPath, SiteName));
            Directory.CreateDirectory(Path.Combine(SitesPath, SiteName2));
            Directory.CreateDirectory(ExePath);

            File.WriteAllText(Path.Combine(SitesPath, SiteName, "web.config"), WebConfigContents);
            File.WriteAllText(Path.Combine(SitesPath, SiteName2, "web.config"), WebConfig2Contents);

            _service = new BackgroundWorkerService(SitesPath, ExePath, new ConsoleFactory(), LoggerLevel.Debug);
        }
        /// <inheritdoc />
        protected override void Load(ContainerBuilder builder)
        {
            var iotaRepository = new RestIotaRepository(
                new FallbackIotaClient(new List <string> {
                "https://nodes.devnet.thetangle.org:443"
            }, 5000),
                new PoWService(new CpuPearlDiver()));

            var channelFactory      = new MamChannelFactory(CurlMamFactory.Default, CurlMerkleTreeFactory.Default, iotaRepository);
            var subscriptionFactory = new MamChannelSubscriptionFactory(iotaRepository, CurlMamParser.Default, CurlMask.Default);

            var encryption      = new RijndaelEncryption("somenicekey", "somenicesalt");
            var resourceTracker = new ResourceTracker(
                channelFactory,
                subscriptionFactory,
                encryption,
                $"{DependencyResolver.LocalStoragePath}\\resources.sqlite");

            var seedManager = new SeedManager(
                resourceTracker,
                new IssSigningHelper(new Curl(), new Curl(), new Curl()),
                new AddressGenerator(),
                iotaRepository,
                encryption,
                $"{DependencyResolver.LocalStoragePath}\\seedmanager.sqlite");

            var fhirRepository   = new IotaFhirRepository(iotaRepository, new FhirJsonTryteSerializer(), resourceTracker, seedManager);
            var fhirParser       = new FhirJsonParser();
            var searchRepository = new SearchRepository($"{DependencyResolver.LocalStoragePath}\\search.sqlite");

            var createInteractor     = new CreateResourceInteractor(fhirRepository, fhirParser, searchRepository);
            var readInteractor       = new ReadResourceInteractor(fhirRepository, searchRepository);
            var validationInteractor = new ValidateResourceInteractor(fhirRepository, fhirParser);
            var searchInteractor     = new SearchResourcesInteractor(fhirRepository, searchRepository);

            var resourceImporter = new ResourceImporter(searchRepository, fhirRepository, seedManager);

            builder.RegisterInstance(searchRepository).As <ISearchRepository>();
            builder.RegisterInstance(resourceTracker).As <IResourceTracker>();

            builder.RegisterInstance(createInteractor);
            builder.RegisterInstance(readInteractor);
            builder.RegisterInstance(validationInteractor);
            builder.RegisterInstance(searchInteractor);
            builder.RegisterInstance(resourceImporter);
            builder.RegisterInstance(seedManager).As <ISeedManager>();
            builder.RegisterInstance(subscriptionFactory);
            builder.RegisterInstance(fhirRepository).As <IFhirRepository>();
            builder.RegisterInstance(new AndroidLogout()).As <ILogout>();

            var backgroundWorker = new BackgroundWorkerService();

            var glucoseService = new FhirGlucoseService(
                new CreateResourceInteractor(fhirRepository, fhirParser, searchRepository),
                new UpdateResourceInteractor(fhirRepository, fhirParser),
                new ReadResourceInteractor(fhirRepository, searchRepository),
                searchRepository);
            var glucoseRepository = new DexcomGlucoseManagementRepository(new RestClient("https://sandbox-api.dexcom.com"));

            //backgoundWorker.RegisterTaskWorker(new ContinuousGlucoseTaskWorker(glucoseService, glucoseRepository));
            backgroundWorker.RegisterTaskWorker(new AggregateGlucoseTaskWorker(glucoseService, glucoseRepository));
        }