Exemplo n.º 1
0
        private datamod.BarcodeScanLog BuildLogRecord(Guid barcodeGuid)
        {
            var barcodeScanLog = new datamod.BarcodeScanLog()
            {
                BarcodeId                    = barcodeGuid,
                BarcodeScanLogId             = Guid.NewGuid(),
                CreatedBy                    = DataRetrievalService.GetCurrentUserId().ToString(), //TODO: rts - convert to username
                CreatedUtcDate               = DateTime.UtcNow,
                DeviceOperatingSystem        = Device.RuntimePlatform,
                DeviceOperatingSystemVersion = DeviceInfo.VersionString,
                //Latitude = location != null ? (Double?)location.Latitude : null,
                IsDeleted       = false,
                ModifiedBy      = DataRetrievalService.GetCurrentUserId().ToString(), //TODO: rts - convert to username
                ModifiedUtcDate = DateTime.UtcNow,
                UserId          = DataRetrievalService.GetCurrentUserId()
            };

            if (location != null)
            {
                barcodeScanLog.Latitude  = location.Latitude;
                barcodeScanLog.Longitude = location.Longitude;
            }

            return(barcodeScanLog);
        }
        public async Task InsufficientStorageSpace()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.CancelAfter(1000);
            _storageInfoProvider.Setup(p => p.HasSpaceAvailableToRetrieve).Returns(false);
            _storageInfoProvider.Setup(p => p.AvailableFreeSpace).Returns(100);

            var store = new DataRetrievalService(
                _loggerFactory.Object,
                _httpClientFactory.Object,
                _logger.Object,
                _fileSystem,
                _dicomToolkit.Object,
                _serviceScopeFactory.Object,
                _cleanupQueue.Object,
                _storageInfoProvider.Object);

            await store.StartAsync(cancellationTokenSource.Token);

            Thread.Sleep(250);
            await store.StopAsync(cancellationTokenSource.Token);

            _logger.VerifyLogging($"Data Retriever Hosted Service is running.", LogLevel.Information, Times.Once());
            _logger.VerifyLogging($"Data Retriever Hosted Service is stopping.", LogLevel.Information, Times.Once());
            _storageInfoProvider.Verify(p => p.HasSpaceAvailableToRetrieve, Times.AtLeastOnce());
            _storageInfoProvider.Verify(p => p.AvailableFreeSpace, Times.AtLeastOnce());
        }
Exemplo n.º 3
0
        public override async Task Init()
        {
            await NavService.PushAlertPopupAsync("Loading...");

            CurrentUser    = StateService.GetCurrentUser();
            CurrentCompany = await DataRetrievalService.GetCompanyByIdOrNull(CurrentUser.CompanyId);

            await NavService.PopAlertPopupsAsync();
        }
Exemplo n.º 4
0
        public override async Task Init()
        {
            await NavService.PushAlertPopupAsync("Loading...");

            MeetingName = string.Empty;
            Users       = (await DataRetrievalService.GetUsersAsync()).ToObservableCollection();

            await NavService.PopAlertPopupsAsync();
        }
        public void GetKeyTwiceInDifferentTimeShouldHaveSameRetrievedOn()
        {
            DataRetrievalResult res1 = DataRetrievalService.GetMyData("DataFile1");
            DataRetrievalResult res2 = DataRetrievalService.GetMyData("DataFile1");

            Assert.IsTrue(res1.RetrievedOn == res2.RetrievedOn,
                          string.Format("RetrievedOn1={0} AND RetrievedOn2={1} should be same!", res1.RetrievedOn,
                                        res2.RetrievedOn));
        }
Exemplo n.º 6
0
        public override async Task Init()
        {
            await NavService.PushAlertPopupAsync("Loading...");

            if (!_hasLoaded)
            {
                /* TOGGLE DEMO MODE HERE */

                /* DEMO MODE ON */
                //For development only -> Demo mode
                //StateService.SetCurrentUser(DemoUser.UserGeorge.ToModelObj());
                //await ((App)Application.Current).SetModeAndSync(true);

                /* DEMO MODE OFF - BYPASS AZURE AD AUTHENTICATION */
                // Hardcode authentication by doing this - robin's dev user - already in the db
                //await DataDownloadService.InsertOrReplaceAuthenticatedUser(Guid.Parse("b79ed0e3-ddb9-4920-8900-ffc55a73b4b5"));
                //var user = await DataRetrievalService.GetUserByEmailOrNullAsync("*****@*****.**");

                /* DEMO MODE OFF - USE AZURE AD AUTHENTICATION */
                //Assuming here that we will be using the same user that just authenticated
                //now that the user has logged in, we need to see if they are a bingoBuzz user, if not, we can add them
                //TODO: should probably do a try parse here if we add more providers
                await DataDownloadService.InsertOrReplaceAuthenticatedUser(
                    StateService.GetAuthEmail(),
                    Guid.Parse(StateService.GetAuthId()),
                    StateService.GetAuthGivenName(),
                    StateService.GetAuthSurName()
                    );

                var user = await DataRetrievalService.GetUserByEmailOrNullAsync(StateService.GetAuthEmail());

                /* END TOGGLE DEMO MODE HERE */

                if (user != null)
                {
                    StateService.SetCurrentUser(user);
                }
                else
                {
                    string whatHappened = "Can't find this BingoBuzz user!";
                    LoggingService.Error(whatHappened, LogMessageType.Instance.Info_Synchronization);
                    throw new Exception(whatHappened);
                }
                await((App)Application.Current).SetModeAndSync(user.UserId, false);

                //Load the contents of the welcome page
                Meetings   = (await DataRetrievalService.GetMeetingsAsync()).ToObservableCollection();
                _hasLoaded = true;
            }
            await CheckAppCenter();

            await NavService.PopAlertPopupsAsync();
        }
Exemplo n.º 7
0
        public override async Task Init()
        {
            await NavService.PushAlertPopupAsync("Loading...");

            NumSquaresClicked = await DataRetrievalService.GetTotalNumberOfSquareClicks();

            NumBingos = await DataRetrievalService.GetTotalNumberOfBingos();

            NumGames = await DataRetrievalService.GetTotalNumberOfGames();

            await NavService.PopAlertPopupsAsync();
        }
Exemplo n.º 8
0
        public async override Task Init()
        {
            await base.CheckAppCenter();

            await base.CheckBadQueuedRecords();

            UserList = (await DataRetrievalService.GetAllUsers()).ToObservableCollection();
            if (UserList.Any())
            {
                SelectedUser = UserList[0];
            }
        }
Exemplo n.º 9
0
        public async void RecordStatus(GeofenceRegion region, GeofenceStatus status)
        {
            var activity = new ModelsData.GeofenceActivity()
            {
                ActivityUtcDateTime = System.DateTime.UtcNow,
                Region             = region.Identifier,
                Status             = status.ToString(),
                GeofenceActivityId = System.Guid.NewGuid()
            };

            activity.Longitude = currentLocation.Longitude;
            activity.Latitude  = currentLocation.Latitude;

            await DataRetrievalService.WriteGeofencingActivityRecord(activity);

            await RefreshRecentGeofenceStatus();
        }
Exemplo n.º 10
0
        public override async Task Init()
        {
            FeedbackTypeList = (await DataRetrievalService.GetAllFeedbackTypes()).ToObservableCollection();
            VehicleList      = (await DataRetrievalService.GetAllVehicles()).ToObservableCollection();

            if (FeedbackTypeList.Any())
            {
                SelectedFeedbackType = FeedbackTypeList[0];
            }

            //SelectedVehicle = VehicleList[0];

            //use this opportunity to grab the long/lat.
            var request          = new GeolocationRequest(GeolocationAccuracy.Medium);
            var locationRealtime = await Geolocation.GetLocationAsync(request);

            location = (locationRealtime == null) ? await Geolocation.GetLastKnownLocationAsync() : locationRealtime;
        }
Exemplo n.º 11
0
        internal async Task RecordScanAsync(Guid id)
        {
            var logRecord = BuildLogRecord(id);

            if (1 == await DataRetrievalService.WriteBarcodeScanRecord(logRecord))
            {
                //Queue up the record for upload to the Azure Database
                await DataRetrievalService.QueueAsync(logRecord.BarcodeScanLogId, QueueableObjects.BarcodeScanLog);

                //See if right now is a good time to upload the data - 10 records at a time
                DataRetrievalService.StartSafeQueuedUpdates();
                //navigate
                await NavService.NavigateTo <LoyaltyBonusViewModel>();
            }
            else
            {
                //TODO: rts - everything did not work out very well - write code here
            }
        }
Exemplo n.º 12
0
        public void CancellationTokenShallCancelTheService()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.Cancel();

            var store = new DataRetrievalService(
                _dicomWebClient.Object,
                _logger.Object,
                _inferenceRequestStore.Object,
                _fileSystem,
                _dicomToolkit.Object,
                _jobStore.Object);

            store.StartAsync(cancellationTokenSource.Token);
            store.StopAsync(cancellationTokenSource.Token);

            _logger.VerifyLogging($"Data Retriever Hosted Service is running.", LogLevel.Information, Times.Once());
            _logger.VerifyLogging($"Data Retriever Hosted Service is stopping.", LogLevel.Information, Times.Once());
        }
Exemplo n.º 13
0
        public HomeController(IHttpContextAccessor httpContextAccessor)
        {
            this._httpContextAccessor = httpContextAccessor;
            service = new DataRetrievalService();
            ivm     = new IndexViewModel();
            string userid = httpContextAccessor.HttpContext.Request.Cookies["userCookie"];

            if (userid == null || userid == "")
            {
                if (httpContextAccessor.HttpContext.Request.Cookies["sessionCookie"] == null || httpContextAccessor.HttpContext.Request.Cookies["sessionCookie"] == "" || httpContextAccessor.HttpContext.Request.Cookies["sessionCookie"].Length <= 5)
                {
                    string        guid    = Guid.NewGuid().ToString();
                    CookieOptions session = new CookieOptions
                    {
                        Expires = DateTime.Now.AddDays(1)
                    };

                    httpContextAccessor.HttpContext.Response.Cookies.Append("sessionCookie", guid, session);
                    Carts c = new Carts
                    {
                        Guid = guid
                    };
                    if (service.CreateCart(c))
                    {
                        ivm.Guid = guid;
                    }
                }
                else
                {
                    CookieOptions session = new CookieOptions
                    {
                        Expires = DateTime.Now.AddDays(1)
                    };

                    httpContextAccessor.HttpContext.Response.Cookies.Append("sessionCookie", service.GetCartByUserId(int.Parse(userid)).Guid, session);
                }
            }
        }
Exemplo n.º 14
0
        public override async Task Init(Guid meetingId)
        {
            await NavService.PushAlertPopupAsync("Loading...");

            Meeting = await DataRetrievalService.GetMeetingOrNullAsync(meetingId);

            if (Meeting != null)
            {
                var players = await DataRetrievalService.GetMeetingAttendeesAsync(meetingId);

                List <PlayerViewModel> playerVms = new List <PlayerViewModel>();
                foreach (var p in players)
                {
                    playerVms.Add(new PlayerViewModel()
                    {
                        PlayerName = $"{p.User_UserId.FirstName}  {p.User_UserId.LastName.Substring(0, 1)}.",
                        Score      = 0 //TODO: need to wire this up
                    });
                }
                Players = playerVms;
                RaisePropertyChanged(nameof(Players));

                BingoInstance = await DataRetrievalService.GetCurrentBingoInstanceOrNullAsync(meetingId);

                if (BingoInstance == null)
                {
                    //we need to make a new instance of this meeting, and make new content too
                    BingoInstance = await DataRetrievalService.CreateNewBingoInstance(meetingId);
                }

                BingoInstanceContent = await DataRetrievalService.GetBingoInstanceContentAsync(BingoInstance.BingoInstanceId);

                RaisePropertyChanged(nameof(BingoInstanceContent));
            }

            await NavService.PopAlertPopupsAsync();
        }
Exemplo n.º 15
0
        public async override void ViewAppeared()
        {
            Products = ProductService.GetAllProducts();
            Events   = EventService.GetAllEvents();

            ProductsLoaded = (ProductCount > 0);
            EventsLoaded   = (EventCount > 0);

            //if we're connected lets check for data
            if (IsConnected)
            {
                ProgressBarTitle = "Syncing...";
                await Task.Delay(100);

                //if either the products or events aren't loaded, lets go get them.
                if (!ProductsLoaded || !EventsLoaded)
                {
                    //something's not loaded, lets go get it.
                    if (!ProductsLoaded)
                    {
                        ProgressBarTitle = "Retrieving Products...";
                        try
                        {
                            if (Products == null)
                            {
                                Products = new List <Product>();
                            }
                            var productData = await DataRetrievalService.GetProductData();

                            ProgressBarProgress = 10;
                            await Task.Delay(100);

                            //uncomment to pitch error here
                            //int i = 0;
                            //int text = 15 / i;

                            ProgressBarTitle = "Saving Products...";

                            int progress    = 10;
                            var numProducts = 0;
                            foreach (Product p in productData.data)
                            {
                                numProducts = numProducts + ProductService.SaveProduct(p);
                                if (numProducts % 25 == 0)
                                {
                                    progress++;
                                    ProgressBarProgress = progress;
                                    await Task.Delay(10);
                                }
                            }

                            await Task.Delay(100);

                            Products       = ProductService.GetAllProducts();
                            ProductsLoaded = true;
                        }
                        catch
                        {
                            //if we're in error, set the message, isnoterror and bail, we can't do any more.
                            ErrorMessage = "We couldn't load that.";
                            IsNotError   = false;
                            return;
                        }
                    }
                    ProgressBarTitle = "Products Loaded!";
                    await Task.Delay(250);

                    if (!EventsLoaded)
                    {
                        ProgressBarTitle    = "Retrieving Events...";
                        ProgressBarProgress = 50;
                        try
                        {
                            if (Events == null)
                            {
                                Events = new List <Event>();
                            }
                            var eventData = await DataRetrievalService.GetEventData();

                            ProgressBarTitle = "Saving Events...";

                            int progress  = 50;
                            var numEvents = 0;
                            foreach (Event e in eventData.data)
                            {
                                numEvents = numEvents + EventService.SaveEvent(e);
                                if (numEvents % 25 == 0)
                                {
                                    progress++;
                                    ProgressBarProgress = progress;
                                    await Task.Delay(10);
                                }
                            }
                            Events              = EventService.GetAllEvents();
                            EventsLoaded        = true;
                            ProgressBarTitle    = "Events Loaded.";
                            ProgressBarProgress = 100;
                            await Task.Delay(100);
                        }
                        catch
                        {
                            //if we're in error, set the message, isnoterror and bail, we can't do any more.
                            //ErrorMessage = "We couldn't load that.";
                            IsNotError = false;
                            return;
                        }
                    }
                    ProgressBarTitle    = "Data Loaded!";
                    ProgressBarProgress = 100;

                    await Task.Delay(1000);

                    if (ProductsLoaded && EventsLoaded)
                    {
                        await _navigationService.Navigate <ProductsViewModel>();
                    }
                }
                else if (ProductsLoaded && EventsLoaded)
                {
                    //everything's loaded, lets ski-daddle!
                    ProgressBarProgress = 100;
                    ProgressBarTitle    = "Data Loaded!";
                    await Task.Delay(2000);

                    await _navigationService.Navigate <ProductsViewModel>();
                }
            }

            base.ViewAppeared();
        }
Exemplo n.º 16
0
 public async Task RefreshRecentGeofenceStatus()
 {
     RecentGeofenceActivity = (await DataRetrievalService.GetRecentGeofenceActivity(20)).ToObservableCollection();
 }
        public void GetDataBasedOnKnownKeyShouldBeOK()
        {
            DataRetrievalResult res = DataRetrievalService.GetMyData("DataFile1");

            Assert.IsNotNull(res, string.Format("retrieving file should not end up in null!"));
        }
Exemplo n.º 18
0
        public async Task ProcessorRequest_ShallRestorePreviouslyRetrievedFiles()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var storagePath             = "/store";

            _fileSystem.Directory.CreateDirectory(storagePath);
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "file1.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "file2.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "file3.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "corrupted.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "text.txt"));
            var request = new InferenceRequest
            {
                PayloadId     = Guid.NewGuid().ToString(),
                JobId         = Guid.NewGuid().ToString(),
                TransactionId = Guid.NewGuid().ToString()
            };

            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.Algorithm,
                ConnectionDetails = new InputConnectionDetails()
            });
            request.ConfigureTemporaryStorageLocation(storagePath);

            _dicomToolkit.Setup(p => p.HasValidHeader(It.IsAny <string>()))
            .Returns((string filename) =>
            {
                if (filename.EndsWith("text.txt"))
                {
                    return(false);
                }
                else if (filename.EndsWith("corrupted.dcm"))
                {
                    return(false);
                }
                return(true);
            });

            _dicomToolkit.Setup(p => p.Open(It.IsAny <string>()))
            .Returns(() => InstanceGenerator.GenerateDicomFile());

            _inferenceRequestStore.SetupSequence(p => p.Take(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(request))
            .Returns(() =>
            {
                cancellationTokenSource.Cancel();
                throw new OperationCanceledException("canceled");
            });

            _jobStore.Setup(p => p.Add(It.IsAny <Job>(), It.IsAny <string>(), It.IsAny <IList <InstanceStorageInfo> >()));

            var store = new DataRetrievalService(
                _dicomWebClient.Object,
                _logger.Object,
                _inferenceRequestStore.Object,
                _fileSystem,
                _dicomToolkit.Object,
                _jobStore.Object);

            await store.StartAsync(cancellationTokenSource.Token);

            BlockUntilCancelled(cancellationTokenSource.Token);

            _logger.VerifyLoggingMessageBeginsWith($"Restored previously retrieved instance", LogLevel.Debug, Times.Exactly(3));
            _logger.VerifyLoggingMessageBeginsWith($"Restored previously retrieved instance", LogLevel.Debug, Times.Exactly(3));
            _logger.VerifyLoggingMessageBeginsWith($"Unable to restore previously retrieved instance from", LogLevel.Warning, Times.Once());
            _jobStore.Verify(p => p.Add(It.IsAny <Job>(), It.IsAny <string>(), It.IsAny <IList <InstanceStorageInfo> >()), Times.Once());
        }
Exemplo n.º 19
0
 public DataRetrievalController(IHttpContextAccessor httpContextAccessor)
 {
     this._httpContextAccessor = httpContextAccessor;
     service = new DataRetrievalService();
 }
Exemplo n.º 20
0
 public async Task RefreshMeetings()
 {
     Meetings = (await DataRetrievalService.GetMeetingsAsync()).ToObservableCollection();
 }
        public async Task ProcessorRequest_ShallRetrieveFhirResources()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var storagePath             = "/store";

            _fileSystem.Directory.CreateDirectory(storagePath);

            #region Test Data

            var url     = "http://uri.test/";
            var request = new InferenceRequest
            {
                PayloadId     = Guid.NewGuid().ToString(),
                JobId         = Guid.NewGuid().ToString(),
                TransactionId = Guid.NewGuid().ToString(),
            };
            request.InputMetadata = new InferenceRequestMetadata
            {
                Details = new InferenceRequestDetails
                {
                    Type      = InferenceRequestType.FhireResource,
                    Resources = new List <FhirResource>()
                    {
                        new FhirResource
                        {
                            Id   = "1",
                            Type = "Patient"
                        }
                    }
                },
                Inputs = new List <InferenceRequestDetails>()
                {
                    new InferenceRequestDetails
                    {
                        Type      = InferenceRequestType.FhireResource,
                        Resources = new List <FhirResource>()
                        {
                            new FhirResource
                            {
                                Id   = "2",
                                Type = "Observation"
                            }
                        }
                    }
                }
            };
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.Algorithm,
                ConnectionDetails = new InputConnectionDetails()
            });
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.Fhir,
                ConnectionDetails = new InputConnectionDetails
                {
                    AuthId   = "token",
                    AuthType = ConnectionAuthType.Bearer,
                    Uri      = url
                }
            });

            Assert.True(request.IsValid(out string _));
            #endregion Test Data

            request.ConfigureTemporaryStorageLocation(storagePath);

            _inferenceRequestStore.SetupSequence(p => p.Take(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(request))
            .Returns(() =>
            {
                cancellationTokenSource.Cancel();
                throw new OperationCanceledException("canceled");
            });

            _jobStore.Setup(p => p.Add(It.IsAny <InferenceJob>(), It.IsAny <bool>()));

            _handlerMock = new Mock <HttpMessageHandler>();
            _handlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(() => new HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new StringContent("{}")
            });

            _httpClientFactory.Setup(p => p.CreateClient(It.IsAny <string>()))
            .Returns(new HttpClient(_handlerMock.Object));

            _storageInfoProvider.Setup(p => p.HasSpaceAvailableToRetrieve).Returns(true);
            _storageInfoProvider.Setup(p => p.AvailableFreeSpace).Returns(100);

            var store = new DataRetrievalService(
                _loggerFactory.Object,
                _httpClientFactory.Object,
                _logger.Object,
                _fileSystem,
                _dicomToolkit.Object,
                _serviceScopeFactory.Object,
                _cleanupQueue.Object,
                _storageInfoProvider.Object);

            await store.StartAsync(cancellationTokenSource.Token);

            BlockUntilCancelled(cancellationTokenSource.Token);

            _handlerMock.Protected().Verify(
                "SendAsync",
                Times.Once(),
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get &&
                                               req.RequestUri.PathAndQuery.Contains("Patient/1")),
                ItExpr.IsAny <CancellationToken>());
            _handlerMock.Protected().Verify(
                "SendAsync",
                Times.Once(),
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get &&
                                               req.RequestUri.PathAndQuery.Contains("Observation/2")),
                ItExpr.IsAny <CancellationToken>());

            _jobStore.Verify(p => p.Add(It.IsAny <InferenceJob>(), false), Times.Once());

            _storageInfoProvider.Verify(p => p.HasSpaceAvailableToRetrieve, Times.AtLeastOnce());
            _storageInfoProvider.Verify(p => p.AvailableFreeSpace, Times.Never());
            _cleanupQueue.Verify(p => p.QueueInstance(It.IsAny <string>()), Times.Exactly(2));
        }
        public async Task ProcessorRequest_ShallQueryByAccessionNumberAndRetrieve()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var storagePath             = "/store";

            _fileSystem.Directory.CreateDirectory(storagePath);

            #region Test Data

            var url     = "http://uri.test/";
            var request = new InferenceRequest
            {
                PayloadId     = Guid.NewGuid().ToString(),
                JobId         = Guid.NewGuid().ToString(),
                TransactionId = Guid.NewGuid().ToString(),
            };
            request.InputMetadata = new InferenceRequestMetadata
            {
                Details = new InferenceRequestDetails
                {
                    Type            = InferenceRequestType.AccessionNumber,
                    AccessionNumber = new List <string>()
                    {
                        "ABC"
                    }
                }
            };
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.Algorithm,
                ConnectionDetails = new InputConnectionDetails()
            });
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.DicomWeb,
                ConnectionDetails = new InputConnectionDetails
                {
                    AuthId   = "token",
                    AuthType = ConnectionAuthType.Basic,
                    Uri      = url
                }
            });

            Assert.True(request.IsValid(out string _));
            #endregion Test Data

            request.ConfigureTemporaryStorageLocation(storagePath);

            _dicomToolkit.Setup(p => p.Save(It.IsAny <DicomFile>(), It.IsAny <string>()));

            _inferenceRequestStore.SetupSequence(p => p.Take(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(request))
            .Returns(() =>
            {
                cancellationTokenSource.Cancel();
                throw new OperationCanceledException("canceled");
            });

            _jobStore.Setup(p => p.Add(It.IsAny <InferenceJob>(), It.IsAny <bool>()));

            var studyInstanceUids = new List <string>()
            {
                DicomUIDGenerator.GenerateDerivedFromUUID().UID,
                DicomUIDGenerator.GenerateDerivedFromUUID().UID
            };
            _handlerMock = new Mock <HttpMessageHandler>();
            _handlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.Is <HttpRequestMessage>(p => p.RequestUri.Query.Contains("ABC")),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(() =>
            {
                return(GenerateQueryResult(DicomTag.AccessionNumber, "ABC", studyInstanceUids));
            });
            _handlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.Is <HttpRequestMessage>(p => !p.RequestUri.Query.Contains("ABC")),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(() =>
            {
                return(GenerateMultipartResponse());
            });

            _httpClientFactory.Setup(p => p.CreateClient(It.IsAny <string>()))
            .Returns(new HttpClient(_handlerMock.Object));
            _storageInfoProvider.Setup(p => p.HasSpaceAvailableToRetrieve).Returns(true);
            _storageInfoProvider.Setup(p => p.AvailableFreeSpace).Returns(100);

            var store = new DataRetrievalService(
                _loggerFactory.Object,
                _httpClientFactory.Object,
                _logger.Object,
                _fileSystem,
                _dicomToolkit.Object,
                _serviceScopeFactory.Object,
                _cleanupQueue.Object,
                _storageInfoProvider.Object);

            await store.StartAsync(cancellationTokenSource.Token);

            BlockUntilCancelled(cancellationTokenSource.Token);

            _handlerMock.Protected().Verify(
                "SendAsync",
                Times.Once(),
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get &&
                                               req.RequestUri.Query.Contains("00080050=ABC")),
                ItExpr.IsAny <CancellationToken>());

            foreach (var studyInstanceUid in studyInstanceUids)
            {
                _handlerMock.Protected().Verify(
                    "SendAsync",
                    Times.Once(),
                    ItExpr.Is <HttpRequestMessage>(req =>
                                                   req.Method == HttpMethod.Get &&
                                                   req.RequestUri.ToString().StartsWith($"{url}studies/{studyInstanceUid}")),
                    ItExpr.IsAny <CancellationToken>());
            }
            _jobStore.Verify(p => p.Add(It.IsAny <InferenceJob>(), false), Times.Once());

            _dicomToolkit.Verify(p => p.Save(It.IsAny <DicomFile>(), It.IsAny <string>()), Times.Exactly(studyInstanceUids.Count));
            _storageInfoProvider.Verify(p => p.HasSpaceAvailableToRetrieve, Times.AtLeastOnce());
            _storageInfoProvider.Verify(p => p.AvailableFreeSpace, Times.Never());
            _cleanupQueue.Verify(p => p.QueueInstance(It.IsAny <string>()), Times.Exactly(2));
        }
        public async Task ProcessorRequest_ShallRestorePreviouslyRetrievedFiles()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var storagePath             = "/store";

            _fileSystem.Directory.CreateDirectory(storagePath);
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "file1.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "file2.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "file3.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "corrupted.dcm"));
            _fileSystem.File.Create(_fileSystem.Path.Combine(storagePath, "text.txt"));
            var request = new InferenceRequest
            {
                PayloadId     = Guid.NewGuid().ToString(),
                JobId         = Guid.NewGuid().ToString(),
                TransactionId = Guid.NewGuid().ToString(),
                InputMetadata = new InferenceRequestMetadata()
            };

            request.InputMetadata.Details = new InferenceRequestDetails()
            {
                Type      = InferenceRequestType.DicomPatientId,
                PatientId = "123"
            };
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.Algorithm,
                ConnectionDetails = new InputConnectionDetails()
            });
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.DicomWeb,
                ConnectionDetails = new InputConnectionDetails()
                {
                    Uri      = "http://valid.uri/api",
                    AuthType = ConnectionAuthType.None
                }
            });
            request.ConfigureTemporaryStorageLocation(storagePath);
            Assert.True(request.IsValid(out string _));

            _dicomToolkit.Setup(p => p.HasValidHeader(It.IsAny <string>()))
            .Returns((string filename) =>
            {
                if (filename.EndsWith("text.txt"))
                {
                    return(false);
                }
                else if (filename.EndsWith("corrupted.dcm"))
                {
                    return(false);
                }
                return(true);
            });

            _dicomToolkit.Setup(p => p.Open(It.IsAny <string>()))
            .Returns(() => InstanceGenerator.GenerateDicomFile());

            _inferenceRequestStore.SetupSequence(p => p.Take(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(request))
            .Returns(() =>
            {
                cancellationTokenSource.Cancel();
                throw new OperationCanceledException("canceled");
            });

            _jobStore.Setup(p => p.Add(It.IsAny <InferenceJob>(), It.IsAny <bool>()));

            _handlerMock = new Mock <HttpMessageHandler>();
            _handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(() =>
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.OK)
                {
                    Content = new StringContent("[]")
                });
            });

            _httpClientFactory.Setup(p => p.CreateClient(It.IsAny <string>()))
            .Returns(new HttpClient(_handlerMock.Object));
            _storageInfoProvider.Setup(p => p.HasSpaceAvailableToRetrieve).Returns(true);
            _storageInfoProvider.Setup(p => p.AvailableFreeSpace).Returns(100);
            _cleanupQueue.Setup(p => p.QueueInstance(It.IsAny <string>()));

            var store = new DataRetrievalService(
                _loggerFactory.Object,
                _httpClientFactory.Object,
                _logger.Object,
                _fileSystem,
                _dicomToolkit.Object,
                _serviceScopeFactory.Object,
                _cleanupQueue.Object,
                _storageInfoProvider.Object);

            await store.StartAsync(cancellationTokenSource.Token);

            BlockUntilCancelled(cancellationTokenSource.Token);

            _logger.VerifyLoggingMessageBeginsWith($"Restored previously retrieved instance", LogLevel.Debug, Times.Exactly(3));
            _logger.VerifyLoggingMessageBeginsWith($"Restored previously retrieved instance", LogLevel.Debug, Times.Exactly(3));
            _logger.VerifyLoggingMessageBeginsWith($"Unable to restore previously retrieved instance from", LogLevel.Warning, Times.Once());
            _jobStore.Verify(p => p.Add(It.IsAny <InferenceJob>(), false), Times.Once());
            _storageInfoProvider.Verify(p => p.HasSpaceAvailableToRetrieve, Times.AtLeastOnce());
            _storageInfoProvider.Verify(p => p.AvailableFreeSpace, Times.Never());
        }
Exemplo n.º 24
0
        public async Task ProcessorRequest_ShallRetrieveViaDicomWebWithDicomUid()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var storagePath             = "/store";

            _fileSystem.Directory.CreateDirectory(storagePath);

            #region Test Data

            var request = new InferenceRequest
            {
                PayloadId     = Guid.NewGuid().ToString(),
                JobId         = Guid.NewGuid().ToString(),
                TransactionId = Guid.NewGuid().ToString()
            };
            request.InputMetadata = new InferenceRequestMetadata
            {
                Details = new InferenceRequestDetails
                {
                    Type    = InferenceRequestType.DicomUid,
                    Studies = new List <RequestedStudy>
                    {
                        new RequestedStudy
                        {
                            StudyInstanceUid = "1",
                            Series           = new List <RequestedSeries>
                            {
                                new RequestedSeries
                                {
                                    SeriesInstanceUid = "1.1",
                                    Instances         = new List <RequestedInstance>
                                    {
                                        new RequestedInstance
                                        {
                                            SopInstanceUid = new List <string>
                                            {
                                                "1.1.2",
                                                "1.1.3"
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        new RequestedStudy
                        {
                            StudyInstanceUid = "2",
                            Series           = new List <RequestedSeries>
                            {
                                new RequestedSeries
                                {
                                    SeriesInstanceUid = "2.1"
                                }
                            }
                        },
                        new RequestedStudy
                        {
                            StudyInstanceUid = "3"
                        },
                    }
                }
            };
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.Algorithm,
                ConnectionDetails = new InputConnectionDetails()
            });
            request.InputResources.Add(
                new RequestInputDataResource
            {
                Interface         = InputInterfaceType.DicomWeb,
                ConnectionDetails = new InputConnectionDetails
                {
                    AuthId   = "token",
                    AuthType = ConnectionAuthType.Basic,
                    Uri      = "http://uri.test/"
                }
            });

            #endregion Test Data

            request.ConfigureTemporaryStorageLocation(storagePath);

            _dicomToolkit.Setup(p => p.Save(It.IsAny <DicomFile>(), It.IsAny <string>()));

            _inferenceRequestStore.SetupSequence(p => p.Take(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(request))
            .Returns(() =>
            {
                cancellationTokenSource.Cancel();
                throw new OperationCanceledException("canceled");
            });

            _jobStore.Setup(p => p.Add(It.IsAny <Job>(), It.IsAny <string>(), It.IsAny <IList <InstanceStorageInfo> >()));

            _wadoService.Setup(p => p.Retrieve(It.IsAny <string>(), It.IsAny <DicomTransferSyntax[]>()))
            .Returns((string studyInstanceUid, DicomTransferSyntax[] dicomTransferSyntaxes) => GenerateInstance(studyInstanceUid));
            _wadoService.Setup(p => p.Retrieve(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DicomTransferSyntax[]>()))
            .Returns((string studyInstanceUid, string seriesInstanceUid, DicomTransferSyntax[] dicomTransferSyntaxes) => GenerateInstance(studyInstanceUid, seriesInstanceUid));
            _wadoService.Setup(p => p.Retrieve(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DicomTransferSyntax[]>()))
            .Returns((string studyInstanceUid, string seriesInstanceUid, string sopInstanceUid, DicomTransferSyntax[] dicomTransferSyntaxes) =>
            {
                return(Task.FromResult(InstanceGenerator.GenerateDicomFile(studyInstanceUid, seriesInstanceUid, sopInstanceUid, _fileSystem)));
            });

            var store = new DataRetrievalService(
                _dicomWebClient.Object,
                _logger.Object,
                _inferenceRequestStore.Object,
                _fileSystem,
                _dicomToolkit.Object,
                _jobStore.Object);

            await store.StartAsync(cancellationTokenSource.Token);

            BlockUntilCancelled(cancellationTokenSource.Token);

            _jobStore.Verify(p => p.Add(It.IsAny <Job>(), It.IsAny <string>(), It.IsAny <IList <InstanceStorageInfo> >()), Times.Once());
            _wadoService.Verify(p => p.Retrieve(It.IsAny <string>(), It.IsAny <DicomTransferSyntax[]>()), Times.Once());
            _wadoService.Verify(p => p.Retrieve(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DicomTransferSyntax[]>()), Times.Once());
            _wadoService.Verify(p => p.Retrieve(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DicomTransferSyntax[]>()), Times.Exactly(2));
            _dicomToolkit.Verify(p => p.Save(It.IsAny <DicomFile>(), It.IsAny <string>()), Times.Exactly(4));
        }