Exemple #1
0
        /// <summary>
        /// Start Dicom data receiver on a given port and check it is listening.
        /// </summary>
        /// <param name="dicomDataReceiver">Dicom data receiver.</param>
        /// <param name="port">Port.</param>
        protected void StartDicomDataReceiver(
            ListenerDataReceiver dicomDataReceiver,
            int port)
        {
            var started = dicomDataReceiver.StartServer(port, BuildAcceptedSopClassesAndTransferSyntaxes, TimeSpan.FromSeconds(2));

            Assert.IsTrue(started);
            Assert.IsTrue(dicomDataReceiver.IsListening);
        }
Exemple #2
0
        /// <summary>
        /// Start Dicom data receiver on a given port and check it is listening.
        /// </summary>
        /// <param name="dicomDataReceiver">Dicom data receiver.</param>
        /// <param name="port">Port.</param>
        protected static void StartDicomDataReceiver(
            ListenerDataReceiver dicomDataReceiver,
            int port)
        {
            dicomDataReceiver = dicomDataReceiver ?? throw new ArgumentNullException(nameof(dicomDataReceiver));

            var started = dicomDataReceiver.StartServer(port, BuildAcceptedSopClassesAndTransferSyntaxes, TimeSpan.FromSeconds(2));

            Assert.IsTrue(started);
            Assert.IsTrue(dicomDataReceiver.IsListening);
        }
Exemple #3
0
        public async Task DicomDataReceiverServerStarts()
        {
            var applicationEntity = new GatewayApplicationEntity("RListenerTest", 191, "127.0.0.1");
            var resultsDirectory  = CreateTemporaryDirectory();

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultsDirectory.FullName)))
            {
                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                Assert.ThrowsException <DicomNetworkException>(() => StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port));

                var dataSender = new DicomDataSender();
                var echoResult = await dataSender.DicomEchoAsync(
                    "RListener",
                    applicationEntity.Title,
                    applicationEntity.Port,
                    applicationEntity.IpAddress);

                // Check echo
                Assert.IsTrue(echoResult == DicomOperationResult.Success);

                DcmtkHelpers.SendFileUsingDCMTK(
                    @"Images\1ValidSmall\1.dcm",
                    applicationEntity.Port,
                    ScuProfile.LEExplicitCT,
                    TestContext);

                // Wait for all events to finish on the data received
                SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromSeconds(10));

                // Check the file exists
                Assert.IsTrue(File.Exists(Path.Combine(folderPath, @"1.2.840.113619.2.81.290.1.36662.3.1.20151027.220159.dcm")));

                dicomDataReceiver.StopServer();
            }
        }
        public async Task DicomSendFilesTest()
        {
            var dataSender        = new DicomDataSender();
            var applicationEntity = new GatewayApplicationEntity("RListenerTest", 131, "127.0.0.1");

            var dicomFiles = new DirectoryInfo(@"Images\1ValidSmall\").GetFiles().Select(x => DicomFile.Open(x.FullName)).ToArray();
            var rtFile     = await DicomFile.OpenAsync(@"Images\LargeSeriesWithContour\rtstruct.dcm").ConfigureAwait(false);

            var resultsDirectory = CreateTemporaryDirectory();

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultsDirectory.FullName)))
            {
                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                var results = await dataSender.SendFilesAsync(
                    "Hello",
                    applicationEntity.Title,
                    applicationEntity.Port,
                    applicationEntity.IpAddress,
                    dicomFiles).ConfigureAwait(false);

                foreach (var result in results)
                {
                    // Check we can send non-RT files
                    Assert.AreEqual(DicomOperationResult.Success, result.Item2);
                }

                var rtResult = await dataSender.SendFilesAsync(
                    "Hello",
                    applicationEntity.Title,
                    applicationEntity.Port,
                    applicationEntity.IpAddress,
                    rtFile).ConfigureAwait(false);

                Assert.AreEqual(1, rtResult.Count());

                foreach (var result in rtResult)
                {
                    // Check we can send RT files
                    Assert.AreEqual(DicomOperationResult.Success, result.Item2);
                }

                dicomDataReceiver.StopServer();
            }
        }
Exemple #5
0
        public void DicomDataReceiverSamePort()
        {
            var applicationEntity = new GatewayApplicationEntity("RListenerTest", 120, "127.0.0.1");
            var resultsDirectory  = CreateTemporaryDirectory();

            using (var dicomDataReceiver1 = new ListenerDataReceiver(new ListenerDicomSaver(resultsDirectory.FullName)))
            {
                StartDicomDataReceiver(dicomDataReceiver1, applicationEntity.Port);

                using (var dicomDataReceiver2 = new ListenerDataReceiver(new ListenerDicomSaver(resultsDirectory.FullName)))
                {
                    Assert.ThrowsException <DicomNetworkException>(() => StartDicomDataReceiver(dicomDataReceiver2, applicationEntity.Port));

                    // Check you can start again and on a different port with the same AE title and IP address.
                    StartDicomDataReceiver(dicomDataReceiver2, applicationEntity.Port + 1);
                }
            }
        }
Exemple #6
0
        public void DicomDataReceiverMutlipleAssociations()
        {
            const int numberOfAssociations = 10;
            const int port = 122;

            var applicationEntity = new GatewayApplicationEntity("RListenerTest", port, "127.0.0.1");
            var resultsDirectory  = CreateTemporaryDirectory();

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultsDirectory.FullName)))
            {
                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                var associationsReceivedCount = 0;
                var receivedAssociations      = new string[numberOfAssociations];

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    if (e.ProgressCode == DicomReceiveProgressCode.AssociationEstablished)
                    {
                        receivedAssociations[int.Parse(e.DicomAssociation.CallingAE)] = e.DicomAssociation.CallingAE;
                        Interlocked.Increment(ref associationsReceivedCount);
                    }
                };

                Parallel.For(0, numberOfAssociations, i =>
                {
                    var dcmtkResult = DcmtkHelpers.SendFileUsingDCMTK(
                        @"Images\1ValidSmall\1.dcm",
                        port,
                        ScuProfile.LEExplicitCT,
                        TestContext,
                        waitForExit: false,
                        applicationEntityTitle: i.ToString());
                });

                SpinWait.SpinUntil(() => associationsReceivedCount == numberOfAssociations, TimeSpan.FromMinutes(1));

                for (var i = 0; i < numberOfAssociations; i++)
                {
                    Assert.IsTrue(receivedAssociations[i] == i.ToString());
                }
            }
        }
        public async Task DicomEchoTest()
        {
            var dataSender = new DicomDataSender();

            var applicationEntity = new GatewayApplicationEntity(
                title: "RListenerTest",
                port: new Random().Next(130, ApplicationEntityValidationHelpers.MaximumPortNumber),
                ipAddress: "127.0.0.1");

            var resultsDirectory = CreateTemporaryDirectory();

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultsDirectory.FullName)))
            {
                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                var result1 = await dataSender.DicomEchoAsync(
                    "Hello",
                    applicationEntity.Title,
                    applicationEntity.Port,
                    applicationEntity.IpAddress).ConfigureAwait(false);

                Assert.AreEqual(DicomOperationResult.Success, result1);

                dicomDataReceiver.StopServer();
            }

            var result2 = await dataSender.DicomEchoAsync(
                "Hello",
                applicationEntity.Title,
                applicationEntity.Port,
                applicationEntity.IpAddress).ConfigureAwait(false);

            Assert.AreEqual(DicomOperationResult.NoResponse, result2);

            // Try ping with IPv6 Address
            var result3 = await dataSender.DicomEchoAsync("Hello", "RListenerTest", 105, "2a00:1450:4009:800::200e").ConfigureAwait(false);

            Assert.AreEqual(DicomOperationResult.NoResponse, result3);
        }
Exemple #8
0
        public async Task DownloadServiceLiveCloudMockConfigEndToEndTest()
        {
            var resultDirectory = CreateTemporaryDirectory();

            var(segmentationId, modelId, data) = await StartFakeSegmentationAsync(@"Images\1ValidSmall\").ConfigureAwait(false);

            var applicationEntity = new GatewayApplicationEntity("RListenerTest", 140, "localhost");

            // Create a Data receiver to receive the RT struct result
            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(CreateTemporaryDirectory().FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                using (var mockSegmentationClient = GetMockInnerEyeSegmentationClient())
                    using (var pushService = CreatePushService())
                        using (var downloadService = CreateDownloadService(mockSegmentationClient))
                            using (var downloadQueue = downloadService.DownloadQueue)
                            {
                                pushService.Start();
                                downloadService.Start();

                                TransactionalEnqueue(
                                    downloadQueue,
                                    new DownloadQueueItem(
                                        segmentationId: segmentationId,
                                        modelId: modelId,
                                        resultsDirectory: resultDirectory.FullName,
                                        referenceDicomFiles: data,
                                        calledApplicationEntityTitle: applicationEntity.Title,
                                        callingApplicationEntityTitle: applicationEntity.Title,
                                        destinationApplicationEntity: applicationEntity,
                                        tagReplacementJsonString: JsonConvert.SerializeObject(_defaultTagReplacement),
                                        associationGuid: Guid.NewGuid(),
                                        associationDateTime: DateTime.UtcNow,
                                        isDryRun: false));

                                // Wait for all events to finish on the data received
                                SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(3));
                            }

                dicomDataReceiver.StopServer();

#pragma warning disable CA1508 // Avoid dead conditional code
                Assert.IsFalse(string.IsNullOrWhiteSpace(folderPath));
#pragma warning restore CA1508 // Avoid dead conditional code

                var files = new DirectoryInfo(folderPath).GetFiles();

                // Check we have a file
                Assert.AreEqual(1, files.Length);

                var dicomFile = await DicomFile.OpenAsync(files[0].FullName).ConfigureAwait(false);

                Assert.IsNotNull(dicomFile);
            }
        }
Exemple #9
0
        public async Task DownloadServiceNoApiConnection()
        {
            var(segmentationId, modelId, data) = await StartFakeSegmentationAsync(@"Images\1ValidSmall\").ConfigureAwait(false);

            var applicationEntity = new GatewayApplicationEntity("RListenerTest", 144, "127.0.0.1");

            // Create a Data receiver to receive the RT struct result
            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(CreateTemporaryDirectory().FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                using (var mockSegmentationClient = GetMockInnerEyeSegmentationClient())
                    using (var pushService = CreatePushService())
                        using (var downloadService = CreateDownloadService(mockSegmentationClient))
                            using (var downloadQueue = downloadService.DownloadQueue)
                                using (var deadLetterQueue = downloadService.DeadletterMessageQueue)
                                {
                                    // Fake a no response when getting progress
                                    mockSegmentationClient.SegmentationResultException = new HttpRequestException();

                                    pushService.Start();
                                    downloadService.Start();

                                    downloadQueue.Clear();

                                    TransactionalEnqueue(
                                        downloadQueue,
                                        new DownloadQueueItem(
                                            segmentationId: segmentationId,
                                            modelId: modelId,
                                            resultsDirectory: CreateTemporaryDirectory().FullName,
                                            referenceDicomFiles: data,
                                            calledApplicationEntityTitle: applicationEntity.Title,
                                            callingApplicationEntityTitle: applicationEntity.Title,
                                            destinationApplicationEntity: applicationEntity,
                                            tagReplacementJsonString: JsonConvert.SerializeObject(_defaultTagReplacement),
                                            associationGuid: Guid.NewGuid(),
                                            associationDateTime: DateTime.UtcNow,
                                            isDryRun: false));

                                    // Wait
                                    await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);

                                    // Null the exception from the mock client
                                    mockSegmentationClient.SegmentationResultException = null;

                                    // Wait for all events to finish on the data received
                                    SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(5));

                                    WaitUntilNoMessagesOnQueue(downloadQueue);

                                    // Check this message has been de-queued
                                    Assert.ThrowsException <MessageQueueReadException>(() => TransactionalDequeue <DownloadQueueItem>(downloadQueue));

                                    Assert.ThrowsException <MessageQueueReadException>(() => TransactionalDequeue <DownloadQueueItem>(deadLetterQueue));
                                }

                dicomDataReceiver.StopServer();

#pragma warning disable CA1508 // Avoid dead conditional code
                Assert.IsFalse(string.IsNullOrWhiteSpace(folderPath));
#pragma warning restore CA1508 // Avoid dead conditional code

                var files = new DirectoryInfo(folderPath).GetFiles();

                // Check we have a file
                Assert.AreEqual(1, files.Length);

                var dicomFile = await DicomFile.OpenAsync(files[0].FullName).ConfigureAwait(false);

                Assert.IsNotNull(dicomFile);
            }
        }
        public async Task ProcessorServiceRestartTest()
        {
            var configurationDirectory = CreateTemporaryDirectory().FullName;

            var expectedGatewayProcessorConfig1 = TestGatewayProcessorConfigProvider.Config.With(
                configurationServiceConfig: new ConfigurationServiceConfig(
                    configurationRefreshDelaySeconds: 1));

            ConfigurationProviderTests.Serialise(expectedGatewayProcessorConfig1, configurationDirectory, GatewayProcessorConfigProvider.GatewayProcessorConfigFileName);

            var tempFolder = CreateTemporaryDirectory();

            foreach (var file in new DirectoryInfo(@"Images\1ValidSmall\").GetFiles())
            {
                file.CopyTo(Path.Combine(tempFolder.FullName, file.Name));
            }

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(CreateTemporaryDirectory().FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                var testAETConfigModel = GetTestAETConfigModel();

                StartDicomDataReceiver(dicomDataReceiver, testAETConfigModel.AETConfig.Destination.Port);

                using (var client = GetMockInnerEyeSegmentationClient())
                    using (var pushService = CreatePushService())
                        using (var uploadService = CreateUploadService(client))
                            using (var uploadQueue = uploadService.UploadQueue)
                                using (var downloadService = CreateDownloadService(client))
                                    using (var gatewayProcessorConfigProvider = CreateGatewayProcessorConfigProvider(configurationDirectory))
                                        using (var configurationService = CreateConfigurationService(
                                                   client,
                                                   gatewayProcessorConfigProvider.ConfigurationServiceConfig,
                                                   downloadService,
                                                   uploadService,
                                                   pushService))
                                        {
                                            // Start the service
                                            configurationService.Start();

                                            uploadQueue.Clear(); // Clear the message queue

                                            // Save a new config, this should be picked up and the services restart in 10 seconds.
                                            var expectedGatewayProcessorConfig2 = TestGatewayProcessorConfigProvider.Config.With(
                                                configurationServiceConfig: new ConfigurationServiceConfig(
                                                    expectedGatewayProcessorConfig1.ConfigurationServiceConfig.ConfigCreationDateTime.AddSeconds(5),
                                                    expectedGatewayProcessorConfig1.ConfigurationServiceConfig.ApplyConfigDateTime.AddSeconds(10)));

                                            ConfigurationProviderTests.Serialise(expectedGatewayProcessorConfig2, configurationDirectory, GatewayProcessorConfigProvider.GatewayProcessorConfigFileName);

                                            SpinWait.SpinUntil(() => pushService.StartCount == 2);
                                            SpinWait.SpinUntil(() => uploadService.StartCount == 2);
                                            SpinWait.SpinUntil(() => downloadService.StartCount == 2);

                                            TransactionalEnqueue(
                                                uploadQueue,
                                                new UploadQueueItem(
                                                    calledApplicationEntityTitle: testAETConfigModel.CalledAET,
                                                    callingApplicationEntityTitle: testAETConfigModel.CallingAET,
                                                    associationFolderPath: tempFolder.FullName,
                                                    rootDicomFolderPath: tempFolder.FullName,
                                                    associationGuid: Guid.NewGuid(),
                                                    associationDateTime: DateTime.UtcNow));

                                            SpinWait.SpinUntil(() => eventCount >= 3);

#pragma warning disable CA1508 // Avoid dead conditional code
                                            Assert.IsFalse(string.IsNullOrWhiteSpace(folderPath));
#pragma warning restore CA1508 // Avoid dead conditional code

                                            var dicomFile = await DicomFile.OpenAsync(new DirectoryInfo(folderPath).GetFiles()[0].FullName).ConfigureAwait(false);

                                            Assert.IsNotNull(dicomFile);
                                        }
            }
        }
        public async Task GatewayLiveEndToEndTest()
        {
            var testAETConfigModel = GetTestAETConfigModel();

            var resultDirectory = CreateTemporaryDirectory();

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, testAETConfigModel.AETConfig.Destination.Port);

                var receivePort = 141;

                using (var segmentationClient = GetMockInnerEyeSegmentationClient())
                    using (var deleteService = CreateDeleteService())
                        using (var pushService = CreatePushService())
                            using (var downloadService = CreateDownloadService(segmentationClient))
                                using (var uploadService = CreateUploadService(segmentationClient))
                                    using (var receiveService = CreateReceiveService(receivePort))
                                    {
                                        deleteService.Start();
                                        pushService.Start();
                                        downloadService.Start();
                                        uploadService.Start();
                                        receiveService.Start();

                                        var dicomDataSender = new DicomDataSender();
                                        var echoResult      = await dicomDataSender.DicomEchoAsync(
                                            testAETConfigModel.CallingAET,
                                            testAETConfigModel.CalledAET,
                                            receivePort,
                                            "127.0.0.1").ConfigureAwait(false);

                                        Assert.IsTrue(echoResult == DicomOperationResult.Success);

                                        DcmtkHelpers.SendFolderUsingDCMTK(
                                            @"Images\1ValidSmall",
                                            receivePort,
                                            ScuProfile.LEExplicitCT,
                                            TestContext,
                                            applicationEntityTitle: testAETConfigModel.CallingAET,
                                            calledAETitle: testAETConfigModel.CalledAET);

                                        // Wait for all events to finish on the data received
                                        SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(3));

#pragma warning disable CA1508 // Avoid dead conditional code
                                        Assert.IsFalse(string.IsNullOrWhiteSpace(folderPath));
#pragma warning restore CA1508 // Avoid dead conditional code

                                        var dicomFile = await DicomFile.OpenAsync(new DirectoryInfo(folderPath).GetFiles()[0].FullName).ConfigureAwait(false);

                                        Assert.IsNotNull(dicomFile);
                                    }
            }
        }
        public async Task PushServiceTest()
        {
            var tempFolder = CreateTemporaryDirectory();

            // Copy all files in the P4_Prostate directory to the temporary directory
            Directory.EnumerateFiles(@"Images\1ValidSmall\")
            .Select(x => new FileInfo(x))
            .ToList()
            .ForEach(x => x.CopyTo(Path.Combine(tempFolder.FullName, x.Name)));

            var applicationEntity = new GatewayApplicationEntity("RListenerTest", 108, "127.0.0.1");
            var resultDirectory   = CreateTemporaryDirectory();

            // Create a Data receiver to receive the RT struct result
            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
            {
                var eventCount = 0;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, applicationEntity.Port);

                var dataSender = new DicomDataSender();
                var echoResult = await dataSender.DicomEchoAsync("RListener", applicationEntity.Title, applicationEntity.Port, applicationEntity.IpAddress);

                // Check echo
                Assert.IsTrue(echoResult == DicomOperationResult.Success);

                var testAETConfigModel = GetTestAETConfigModel();

                using (var deleteService = CreateDeleteService())
                    using (var pushService = CreatePushService())
                        using (var pushQueue = pushService.PushQueue)
                        {
                            deleteService.Start();
                            pushService.Start();

                            TransactionalEnqueue(
                                pushQueue,
                                new PushQueueItem(
                                    destinationApplicationEntity: applicationEntity,
                                    calledApplicationEntityTitle: testAETConfigModel.CalledAET,
                                    callingApplicationEntityTitle: applicationEntity.Title,
                                    associationGuid: Guid.NewGuid(),
                                    associationDateTime: DateTime.UtcNow,
                                    filePaths: tempFolder.GetFiles().Select(x => x.FullName).ToArray()));

                            // Wait for all events to finish on the data received
                            SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(3));

                            SpinWait.SpinUntil(() => new DirectoryInfo(tempFolder.FullName).Exists == false, TimeSpan.FromSeconds(30));

                            Assert.IsFalse(new DirectoryInfo(tempFolder.FullName).Exists);

                            Assert.AreEqual(20, resultDirectory.GetDirectories()[0].GetFiles().Length);
                        }
            }
        }
        public async Task PushServiceBadAetTest()
        {
            var testAETConfigModel = GetTestAETConfigModel();
            var destination        = testAETConfigModel.AETConfig.Destination;

            var tempFolder = CreateTemporaryDirectory();

            // Grab a structure set file
            var file = new FileInfo(@"Images\LargeSeriesWithContour\rtstruct.dcm");

            file.CopyTo(Path.Combine(tempFolder.FullName, file.Name));

            var resultDirectory = CreateTemporaryDirectory();

            // Create a Data receiver to receive the RT struct result
            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, destination.Port);

                var dataSender = new DicomDataSender();
                var echoResult = await dataSender.DicomEchoAsync(
                    "RListener",
                    destination.Title,
                    destination.Port,
                    destination.Ip);

                // Check echo
                Assert.IsTrue(echoResult == DicomOperationResult.Success);

                using (var deleteService = CreateDeleteService())
                    using (var pushService = CreatePushService())
                        using (var pushQueue = pushService.PushQueue)
                        {
                            deleteService.Start();
                            pushService.Start();

                            TransactionalEnqueue(
                                pushQueue,
                                new PushQueueItem(
                                    destinationApplicationEntity: new GatewayApplicationEntity("", -1, "ababa"),
                                    calledApplicationEntityTitle: testAETConfigModel.CalledAET,
                                    callingApplicationEntityTitle: testAETConfigModel.CallingAET,
                                    associationGuid: Guid.NewGuid(),
                                    associationDateTime: DateTime.UtcNow,
                                    filePaths: tempFolder.GetFiles().Select(x => x.FullName).ToArray()));

                            // Wait for all events to finish on the data received
                            SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(3));

                            SpinWait.SpinUntil(() => new DirectoryInfo(tempFolder.FullName).Exists == false, TimeSpan.FromSeconds(30));

                            Assert.IsFalse(new DirectoryInfo(tempFolder.FullName).Exists);
                        }
            }
        }
Exemple #14
0
        public async Task IntegrationTestEndToEnd()
        {
            var sourceDirectory = CreateTemporaryDirectory();
            var resultDirectory = CreateTemporaryDirectory();

            var random = new Random();

            // Get file names for all in directory
            var sourceDicomFileNames = new DirectoryInfo(@"Images\HN").GetFiles().ToArray();
            // Load all DICOM files
            var sourceDicomFiles = sourceDicomFileNames.Select(f => DicomFile.Open(f.FullName, FileReadOption.ReadAll)).ToArray();

            // Add/Update random tags for the source DICOM files.
            DicomAnonymisationTests.AddRandomTags(random, sourceDicomFiles);

            // Save them all to the sourceDirectory.
            var sourcePairs = sourceDicomFileNames.Zip(sourceDicomFiles, (f, d) => Tuple.Create(f, d)).ToArray();

            foreach (var sourcePair in sourcePairs)
            {
                var sourceImageFilePath = Path.Combine(sourceDirectory.FullName, sourcePair.Item1.Name);

                sourcePair.Item2.Save(sourceImageFilePath);
            }

            // Keep the first as a reference for deanonymization later.
            var originalSlice = sourceDicomFiles.First();

            var testAETConfigModel = GetTestAETConfigModel();

            var receivePort = 160;

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
                using (var deleteService = CreateDeleteService())
                    using (var pushService = CreatePushService())
                        using (var downloadService = CreateDownloadService())
                            using (var uploadService = CreateUploadService())
                                using (var receiveService = CreateReceiveService(receivePort))
                                {
                                    // Start a DICOM receiver for the final DICOM-RT file
                                    var eventCount = new ConcurrentDictionary <DicomReceiveProgressCode, int>();
                                    var folderPath = string.Empty;

                                    dicomDataReceiver.DataReceived += (sender, e) =>
                                    {
                                        folderPath = e.FolderPath;
                                        eventCount.AddOrUpdate(e.ProgressCode, 1, (k, v) => v + 1);
                                    };

                                    StartDicomDataReceiver(dicomDataReceiver, testAETConfigModel.AETConfig.Destination.Port);

                                    // Start the services.
                                    deleteService.Start();
                                    pushService.Start();
                                    downloadService.Start();
                                    uploadService.Start();
                                    receiveService.Start();

                                    // Try a DICOM C-ECHO
                                    var dicomDataSender = new DicomDataSender();

                                    var echoResult = await dicomDataSender.DicomEchoAsync(
                                        testAETConfigModel.CallingAET,
                                        testAETConfigModel.CalledAET,
                                        receivePort,
                                        "127.0.0.1").ConfigureAwait(false);

                                    Assert.IsTrue(echoResult == DicomOperationResult.Success);

                                    // Send the image stack
                                    DcmtkHelpers.SendFolderUsingDCMTK(
                                        sourceDirectory.FullName,
                                        receivePort,
                                        ScuProfile.LEExplicitCT,
                                        TestContext,
                                        applicationEntityTitle: testAETConfigModel.CallingAET,
                                        calledAETitle: testAETConfigModel.CalledAET);

                                    // Wait for DICOM-RT file to be received.
                                    Func <DicomReceiveProgressCode, int, bool> TestEventCount = (progressCode, count) =>
                                                                                                eventCount.ContainsKey(progressCode) && eventCount[progressCode] == count;

                                    SpinWait.SpinUntil(() => TestEventCount(DicomReceiveProgressCode.AssociationEstablished, 1));
                                    SpinWait.SpinUntil(() => TestEventCount(DicomReceiveProgressCode.FileReceived, 1));
                                    SpinWait.SpinUntil(() => TestEventCount(DicomReceiveProgressCode.AssociationReleased, 1));
                                    SpinWait.SpinUntil(() => TestEventCount(DicomReceiveProgressCode.ConnectionClosed, 1));

                                    Assert.IsTrue(eventCount[DicomReceiveProgressCode.AssociationEstablished] == 1);
                                    Assert.IsTrue(eventCount[DicomReceiveProgressCode.FileReceived] == 1);
                                    Assert.IsTrue(eventCount[DicomReceiveProgressCode.AssociationReleased] == 1);
                                    Assert.IsTrue(eventCount[DicomReceiveProgressCode.ConnectionClosed] == 1);

                                    var receivedFiles = new DirectoryInfo(folderPath).GetFiles();
                                    Assert.AreEqual(1, receivedFiles.Length);

                                    var receivedFilePath = receivedFiles.First().FullName;

                                    var dicomFile = await DicomFile.OpenAsync(receivedFilePath, FileReadOption.ReadAll).ConfigureAwait(false);

                                    Assert.IsNotNull(dicomFile);

                                    var matchedModel = ApplyAETModelConfigProvider.ApplyAETModelConfig(testAETConfigModel.AETConfig.Config.ModelsConfig, sourceDicomFiles);

                                    var segmentationClient = TestGatewayProcessorConfigProvider.CreateInnerEyeSegmentationClient().Invoke();

                                    DicomAnonymisationTests.AssertDeanonymizedFile(
                                        originalSlice,
                                        dicomFile,
                                        segmentationClient.TopLevelReplacements,
                                        matchedModel.Result.TagReplacements,
                                        false);

                                    AssertIsDicomRtFile(DateTime.UtcNow, dicomFile, matchedModel.Result.ModelId);
                                }
        }
        public async Task ProcessorServiceRestartTest()
        {
            var tempFolder = CreateTemporaryDirectory();

            foreach (var file in new DirectoryInfo(@"Images\1ValidSmall\").GetFiles())
            {
                file.CopyTo(Path.Combine(tempFolder.FullName, file.Name));
            }

            var client = GetMockInnerEyeSegmentationClient();

            var mockConfigurationServiceConfigProvider = new MockConfigurationProvider <ConfigurationServiceConfig>();

            var configurationServiceConfig1 = new ConfigurationServiceConfig(
                configurationRefreshDelaySeconds: 1);

            var configurationServiceConfig2 = new ConfigurationServiceConfig(
                configurationServiceConfig1.ConfigCreationDateTime.AddSeconds(5),
                configurationServiceConfig1.ApplyConfigDateTime.AddSeconds(10));

            mockConfigurationServiceConfigProvider.ConfigurationQueue.Enqueue(configurationServiceConfig1);
            mockConfigurationServiceConfigProvider.ConfigurationQueue.Enqueue(configurationServiceConfig2);

            var resultDirectory = CreateTemporaryDirectory();

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                var testAETConfigModel = GetTestAETConfigModel();

                StartDicomDataReceiver(dicomDataReceiver, testAETConfigModel.AETConfig.Destination.Port);

                using (var pushService = CreatePushService())
                    using (var uploadService = CreateUploadService(client))
                        using (var uploadQueue = uploadService.UploadQueue)
                            using (var downloadService = CreateDownloadService(client))
                                using (var configurationService = CreateConfigurationService(
                                           client,
                                           mockConfigurationServiceConfigProvider.GetConfiguration,
                                           downloadService,
                                           uploadService,
                                           pushService))
                                {
                                    // Start the service
                                    configurationService.Start();

                                    uploadQueue.Clear(); // Clear the message queue

                                    SpinWait.SpinUntil(() => pushService.StartCount == 2);
                                    SpinWait.SpinUntil(() => uploadService.StartCount == 2);
                                    SpinWait.SpinUntil(() => downloadService.StartCount == 2);

                                    TransactionalEnqueue(
                                        uploadQueue,
                                        new UploadQueueItem(
                                            calledApplicationEntityTitle: testAETConfigModel.CalledAET,
                                            callingApplicationEntityTitle: testAETConfigModel.CallingAET,
                                            associationFolderPath: tempFolder.FullName,
                                            rootDicomFolderPath: tempFolder.FullName,
                                            associationGuid: Guid.NewGuid(),
                                            associationDateTime: DateTime.UtcNow));

                                    SpinWait.SpinUntil(() => eventCount >= 3);

                                    Assert.IsFalse(string.IsNullOrWhiteSpace(folderPath));

                                    var dicomFile = await DicomFile.OpenAsync(new DirectoryInfo(folderPath).GetFiles()[0].FullName);

                                    Assert.IsNotNull(dicomFile);

                                    dicomFile = null;

                                    TryDeleteDirectory(folderPath);
                                }
            }
        }
        public void UploadServiceLiveSendImageTest()
        {
            var tempFolder = CreateTemporaryDirectory();

            foreach (var file in new DirectoryInfo(@"Images\1ValidSmall\").GetFiles())
            {
                file.CopyTo(Path.Combine(tempFolder.FullName, file.Name));
            }

            var testAETConfigModel = GetTestAETConfigModel();

            var newTestAETConfigModel = testAETConfigModel.With(
                aetConfig: testAETConfigModel.AETConfig.With(
                    config: new AETConfig(
                        AETConfigType.Model,
                        new[]
            {
                new ModelConstraintsConfig(
                    "b033d049-0233-4068-bc0f-c64cec48e8fa",
                    new [] { new ModelChannelConstraints("ct", new GroupConstraint(Array.Empty <DicomConstraint>(), LogicalOperator.And), new GroupConstraint(Array.Empty <DicomConstraint>(), LogicalOperator.And), -1, -1) },
                    Array.Empty <TagReplacement>()),
            }),
                    shouldReturnImage: true));

            var aetConfigProvider = new MockAETConfigProvider(newTestAETConfigModel);

            var resultDirectory = CreateTemporaryDirectory();

            using (var dicomDataReceiver = new ListenerDataReceiver(new ListenerDicomSaver(resultDirectory.FullName)))
            {
                var eventCount = 0;
                var folderPath = string.Empty;

                dicomDataReceiver.DataReceived += (sender, e) =>
                {
                    folderPath = e.FolderPath;
                    Interlocked.Increment(ref eventCount);
                };

                StartDicomDataReceiver(dicomDataReceiver, newTestAETConfigModel.AETConfig.Destination.Port);

                using (var segmentationClient = GetMockInnerEyeSegmentationClient())
                    using (var deleteService = CreateDeleteService())
                        using (var uploadService = CreateUploadService(segmentationClient, aetConfigProvider.AETConfigModels))
                            using (var uploadQueue = uploadService.UploadQueue)
                                using (var downloadService = CreateDownloadService(segmentationClient))
                                    using (var downloadQueue = downloadService.DownloadQueue)
                                        using (var pushService = CreatePushService(aetConfigProvider.AETConfigModels))
                                            using (var pushQueue = pushService.PushQueue)
                                            {
                                                deleteService.Start();
                                                uploadService.Start();
                                                downloadService.Start();
                                                pushService.Start();

                                                Enqueue(
                                                    uploadQueue,
                                                    new UploadQueueItem(
                                                        calledApplicationEntityTitle: newTestAETConfigModel.CalledAET,
                                                        callingApplicationEntityTitle: newTestAETConfigModel.CallingAET,
                                                        associationFolderPath: tempFolder.FullName,
                                                        rootDicomFolderPath: CreateTemporaryDirectory().FullName,
                                                        associationGuid: Guid.NewGuid(),
                                                        associationDateTime: DateTime.UtcNow),
                                                    true);

                                                // Leave enough time to allow upload
                                                SpinWait.SpinUntil(() => new DirectoryInfo(tempFolder.FullName).Exists == false, TimeSpan.FromSeconds(90));

                                                // Check the association folder is deleted.
                                                Assert.IsFalse(new DirectoryInfo(tempFolder.FullName).Exists);

                                                // Wait for all events to finish on the data received
                                                SpinWait.SpinUntil(() => eventCount >= 3, TimeSpan.FromMinutes(3));

                                                // Make sure the item was dequeued
                                                Assert.ThrowsException <MessageQueueReadException>(() => TransactionalDequeue <UploadQueueItem>(uploadQueue));
                                                Assert.ThrowsException <MessageQueueReadException>(() => TransactionalDequeue <DownloadQueueItem>(downloadQueue));
                                                Assert.ThrowsException <MessageQueueReadException>(() => TransactionalDequeue <PushQueueItem>(pushQueue));

#pragma warning disable CA1508 // Avoid dead conditional code
                                                Assert.IsFalse(string.IsNullOrWhiteSpace(folderPath));
#pragma warning restore CA1508 // Avoid dead conditional code

                                                // Check we received the image in the result
                                                Assert.AreEqual(21, new DirectoryInfo(folderPath).GetFiles().Length);
                                            }
            }
        }