コード例 #1
0
        public async Task Retrieve_Study_BadTransferSyntax()
        {
            var studyUid = DicomUIDGenerator.GenerateDerivedFromUUID();

            var response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = await _fixture.GenerateInstances(1, studyUid),
            };

            Mock <HttpMessageHandler> handlerMock;
            HttpClient httpClient;

            GenerateHttpClient(response, out handlerMock, out httpClient);

            var wado = new WadoService(httpClient);

            await Assert.ThrowsAsync <ArgumentException>(async() =>
            {
                await foreach (var instance in wado.Retrieve(studyUid.UID, DicomTransferSyntax.ImplicitVRLittleEndian))
                {
                }
            });
        }
コード例 #2
0
        public async Task RetrieveMetadata_Instance_BadUids()
        {
            var httpClient = new HttpClient();
            var wado       = new WadoService(httpClient, new Uri("http://dummy/api/"));

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await wado.RetrieveMetadata <string>(null, seriesInstanceUid: null, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <DicomValidationException>(async() =>
            {
                await wado.RetrieveMetadata <string>("bad uid", seriesInstanceUid: null, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await wado.RetrieveMetadata <string>(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: null, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <DicomValidationException>(async() =>
            {
                await wado.RetrieveMetadata <string>(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: "bad id", sopInstanceUid: "bad id");
            });

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await wado.RetrieveMetadata <string>(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: DicomUIDGenerator.GenerateDerivedFromUUID().UID, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <DicomValidationException>(async() =>
            {
                await wado.RetrieveMetadata <string>(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: DicomUIDGenerator.GenerateDerivedFromUUID().UID, sopInstanceUid: "bad id");
            });
        }
コード例 #3
0
 public DicomFileGenerator GenerateNewSeries()
 {
     baseDataset.AddOrUpdate(DicomTag.SeriesInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
     baseDataset.AddOrUpdate(DicomTag.SOPInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
     return(this);
 }
コード例 #4
0
        public async Task Retrieve_Instance_BadUids()
        {
            var httpClient = GetHttpClient();
            var wado       = new WadoService(httpClient);

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await wado.Retrieve(null, seriesInstanceUid: null, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <DicomValidationException>(async() =>
            {
                await wado.Retrieve("bad uid", seriesInstanceUid: null, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await wado.Retrieve(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: null, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <DicomValidationException>(async() =>
            {
                await wado.Retrieve(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: "bad id", sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <ArgumentNullException>(async() =>
            {
                await wado.Retrieve(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: DicomUIDGenerator.GenerateDerivedFromUUID().UID, sopInstanceUid: null);
            });

            await Assert.ThrowsAsync <DicomValidationException>(async() =>
            {
                await wado.Retrieve(DicomUIDGenerator.GenerateDerivedFromUUID().UID, seriesInstanceUid: DicomUIDGenerator.GenerateDerivedFromUUID().UID, sopInstanceUid: "bad uid");
            });
        }
コード例 #5
0
        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));
        }
コード例 #6
0
        // static private void StartGdcm()
        // {
        //     var s = new gdcm.Reader();
        //     s.SetFileName("/mnt/c/Users/nikol/Desktop/CR.1.871.3.1522049724.50292.18240.95439262.3570939512.1.1.1");
        //     bool b = s.CanRead();
        //     bool d = s.Read();
        // }

        static private unsafe void Main(string[] args)
        {
            // ComparingDicomFiles.Start(args);
            // return;
            // StartGdcm();

            Dicom.Imaging.Codec.TranscoderManager.SetImplementation(new NativeTranscoderManager());
            ImageManager.SetImplementation(WinFormsImageManager.Instance);
            const string filePath   = "/mnt/d/DICOM/Fluorography/favorite/jpeg-process14-1/sources/1.871.3.2050448135.34720.20335.72851334.2248937210.1.1.1";
            DicomFile    dicomFile  = DicomFile.Open(filePath);
            DicomDataset dataset    = dicomFile.Dataset;
            DicomImage   dicomImage = new DicomImage(dataset, 0);
            var          image      = dicomImage.RenderImage(0);
            var          bitmap     = image.AsSharedBitmap();

            bitmap.Save("/mnt/c/Users/nikol/Desktop/image-new.png");

            byte[] pixelData;
            Dictionary <string, string> meta;

            using (FileStream readStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                pixelData = DicomDatasetExtensions.DecodeImage(readStream, out meta).PixelData;
            // using (FileStream readStream = new FileStream(sc, FileMode.Open, FileAccess.Read))
            //     pixelData = DicomDatasetExtensions.DecodeImage(readStream, out meta).PixelData;
            ushort width  = dataset.GetValue <ushort>(DicomTag.Columns, 0);
            ushort height = dataset.GetValue <ushort>(DicomTag.Rows, 0);

            byte[] pixelData2   = new byte[pixelData.Length / 2 * 3];
            double windowCenter = dataset.GetValue <double>(DicomTag.WindowCenter, 0);
            double windowWidth  = dataset.GetValue <double>(DicomTag.WindowWidth, 0);

            fixed(byte *pPixelData = &pixelData[0])
            for (int pixelIndex = 0; pixelIndex != pixelData.Length / 2; pixelIndex++)
            {
                int rowIndex = pixelIndex / width;

                pixelData2[pixelIndex * 3 + (int)(rowIndex / (double)height * 3)] = (byte)(Math.Clamp((*(((ushort *)pPixelData) + pixelIndex) - windowCenter + windowWidth * 0.5), 0.0, windowWidth) / windowWidth * 255.0);
            }

            meta = new Dictionary <string, string>();
            foreach (var item in dataset)
            {
                try
                {
                    string value = dataset.GetValue <string>(item.Tag, 0);
                    int    count = dataset.GetValueCount(item.Tag);
                    for (int valueIndex = 1; valueIndex != count; valueIndex++)
                    {
                        value += $"\\{dataset.GetValue<string>(item.Tag, valueIndex)}";
                    }
                    meta.Add(item.Tag.ToString().Replace("(", string.Empty).Replace(")", string.Empty).Replace(',', '|'), value);
                }
                catch
                {
                }
            }

            fixed(byte *p = &pixelData2[0])
            {
                var im = itk.simple.SimpleITK.ImportAsUInt8(new IntPtr(p), new itk.simple.VectorUInt32(new uint[] { width, height }), new itk.simple.VectorDouble(new double[] { 1, 1 }), new itk.simple.VectorDouble(new double[] { 0, 0 }), new itk.simple.VectorDouble(new double[] { 1, 0, 0, 1 }), 3);

                itk.simple.ImageFileWriter writer = new itk.simple.ImageFileWriter();
                writer.SetFileName("/mnt/c/Users/nikol/Desktop/rewritten.dcm");
                writer.KeepOriginalImageUIDOff();
                foreach (var pair in meta)
                {
                    im.SetMetaData(pair.Key, pair.Value);
                }
                writer.SetImageIO("GDCMImageIO");
                writer.UseCompressionOff();
                writer.Execute(im);
                writer.Dispose();
                im.Dispose();
            }

            // dicomFile = DicomFile.Open("/mnt/c/Users/nikol/Desktop/CR.1.871.3.1522049724.50292.18240.95439262.3570939512.1.1.dcm");
            // dicomFile.Dataset.AddOrUpdate<string>(DicomTag.StudyInstanceUID, dicomFile.Dataset.GetSingleValue<string>(DicomTag.StudyInstanceUID));
            // dicomFile.Save("/mnt/c/Users/nikol/Desktop/CR.1.871.3.1522049724.50292.18240.95439262.3570939512.1.2.dcm");
            DicomDataset dataset2 = new DicomDataset();

            dataset.CopyTo(dataset2);
            dataset = dataset2;
            DicomPixelData dicomPixelData = DicomPixelData.Create(dataset, true);

            dicomPixelData.AddFrame(new MemoryByteBuffer(pixelData2));
            dataset.AddOrUpdate(DicomTag.StudyInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            dataset.AddOrUpdate(DicomTag.SeriesInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            dataset.AddOrUpdate(DicomTag.SOPInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            dataset.AddOrUpdate(DicomTag.BitsAllocated, (ushort)8);
            dataset.AddOrUpdate(DicomTag.BitsStored, (ushort)8);
            dataset.AddOrUpdate(DicomTag.HighBit, (ushort)7);
            dataset.AddOrUpdate(DicomTag.PixelRepresentation, (ushort)0);
            dataset.AddOrUpdate(DicomTag.SamplesPerPixel, (ushort)3);
            dataset.AddOrUpdate(DicomTag.PlanarConfiguration, (ushort)0);
            dataset.AddOrUpdate(DicomTag.PhotometricInterpretation, PhotometricInterpretation.Rgb.Value);
            dataset.AddOrUpdate(DicomTag.WindowCenter, 127.5);
            dataset.AddOrUpdate(DicomTag.WindowWidth, 255.0);

            dicomFile = new DicomFile(dataset);
            dicomFile.Save("/mnt/c/Users/nikol/Desktop/efferent-no-compression.dcm");

            var j2000lossy = dataset.Compress(DicomTransferSyntax.JPEGLSLossless, new DicomJpegLsLosslessCodec(), new Dicom.Imaging.Codec.DicomJpegLsParams());

            j2000lossy.AddOrUpdate(DicomTag.StudyInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            j2000lossy.AddOrUpdate(DicomTag.SeriesInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            j2000lossy.AddOrUpdate(DicomTag.SOPInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            dicomFile = new DicomFile(j2000lossy);
            dicomFile.Save("/mnt/c/Users/nikol/Desktop/efferent-ls-lossless.dcm");

            var j2000lossless = dataset.Compress(DicomTransferSyntax.JPEGLSNearLossless, new DicomJpegLsNearLosslessCodec(), new Dicom.Imaging.Codec.DicomJpegLsParams());

            j2000lossless.AddOrUpdate(DicomTag.StudyInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            j2000lossless.AddOrUpdate(DicomTag.SeriesInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            j2000lossless.AddOrUpdate(DicomTag.SOPInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID());
            dicomFile = new DicomFile(j2000lossless);
            dicomFile.Save("/mnt/c/Users/nikol/Desktop/efferent-ls-near-lossless.dcm");

            // RemovePixelDataProgram.Start(args);
            // ItkSimpleTestProgram.Start(args);
            // ImageTestProgram.Start(args);
            // CheckImageAttributesProgram.Start(args);
            // TestDicom48bpp.Start(args);
            // Testing3D.Start(args);
            // TestingWindowPresets.Start(args);
            // TestingMultiImageDicom.Start(args);
            // ComparingDicomFiles.Start(args);
            // PresentationState.Start(args);
            // PresentationStateAnalyzer.Start(args);
        }
コード例 #7
0
        public async Task <(DicomUID affectedInstanceUid, string studyInstanceUid, bool result)> SendMppsInProgressAsync(string serverIp, int serverPort, string serverAET, string localAET, DicomDataset worklistItem)
        {
            DicomSequence procedureStepSeq = worklistItem.GetSequence(DicomTag.ScheduledProcedureStepSequence);
            // A worklistitem may have a list of scheduledprocedureSteps.
            // For each of them you have to send separate MPPS InProgress- and Completed-messages.
            // there in this example we will only send for the first procedure step
            DicomDataset procedureStep = procedureStepSeq.First();

            // get study instance UID from MWL query resault
            string studyInstanceUID = worklistItem.GetSingleValueOrDefault(DicomTag.StudyInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID().UID);

            DicomDataset dataset = new DicomDataset
            {
                { DicomTag.PatientName, worklistItem.GetSingleValueOrDefault(DicomTag.PatientName, string.Empty) },
                { DicomTag.PatientID, worklistItem.GetSingleValueOrDefault(DicomTag.PatientID, string.Empty) },
                { DicomTag.PatientBirthDate, worklistItem.GetSingleValueOrDefault(DicomTag.PatientBirthDate, string.Empty) },
                { DicomTag.PatientSex, worklistItem.GetSingleValueOrDefault(DicomTag.PatientSex, string.Empty) },
                { DicomTag.StudyID, worklistItem.GetSingleValueOrDefault(DicomTag.StudyID, string.Empty) },
                { DicomTag.StudyInstanceUID, studyInstanceUID },

                { DicomTag.PerformedProcedureStepID, procedureStep.GetSingleValueOrDefault(DicomTag.ScheduledProcedureStepID, string.Empty) },
                { DicomTag.PerformedProcedureStepDescription, procedureStep.GetSingleValueOrDefault(DicomTag.ScheduledProcedureStepID, string.Empty) },

                // set status
                { DicomTag.PerformedProcedureStepStatus, IN_PROGRESS },
                { DicomTag.PerformedProcedureTypeDescription, string.Empty },

                { DicomTag.PerformedProcedureStepStartDate, DateTime.Now },
                { DicomTag.PerformedProcedureStepStartTime, DateTime.Now },
                { DicomTag.PerformedProcedureStepEndDate, string.Empty },
                { DicomTag.PerformedProcedureStepEndTime, string.Empty },
                { DicomTag.PerformedLocation, string.Empty },
                { DicomTag.PerformedStationAETitle, localAET },
                { DicomTag.PerformedStationName, localAET },
                // get modality from MWL query result
                { DicomTag.Modality, procedureStep.GetSingleValueOrDefault(DicomTag.Modality, string.Empty) },
                { DicomTag.PerformedProtocolCodeSequence, new DicomDataset() },
                { DicomTag.ProcedureCodeSequence, new DicomDataset() },
                { DicomTag.ReferencedPatientSequence, new DicomDataset() }
            };
            // set Attribute Sequence data
            DicomDataset content = new DicomDataset
            {
                { DicomTag.AccessionNumber, worklistItem.GetSingleValueOrDefault(DicomTag.AccessionNumber, string.Empty) },
                { DicomTag.StudyInstanceUID, studyInstanceUID },
                { DicomTag.ReferencedStudySequence, new DicomDataset() },
                { DicomTag.RequestedProcedureID, worklistItem.GetSingleValueOrDefault(DicomTag.RequestedProcedureID, string.Empty) },
                { DicomTag.RequestedProcedureDescription, worklistItem.GetSingleValueOrDefault(DicomTag.RequestedProcedureDescription, string.Empty) },
                { DicomTag.ScheduledProcedureStepID, procedureStep.GetSingleValueOrDefault(DicomTag.ScheduledProcedureStepID, string.Empty) },
                { DicomTag.ScheduledProcedureStepDescription, procedureStep.GetSingleValueOrDefault(DicomTag.ScheduledProcedureStepDescription, string.Empty) },
                { DicomTag.ScheduledProtocolCodeSequence, new DicomDataset() }
            };

            DicomSequence attr_Sequence = new DicomSequence(DicomTag.ScheduledStepAttributesSequence, content);//"Scheduled Step Attribute Sequence"

            dataset.Add(attr_Sequence);

            dataset.Add(DicomTag.PerformedSeriesSequence, new DicomDataset());

            // create an unique UID as the effectedinstamceUid, this id will be needed for the N-SET also
            DicomUID effectedinstamceUid = DicomUID.Generate();

            DicomNCreateRequest dicomStartRequest = new DicomNCreateRequest(DicomUID.ModalityPerformedProcedureStepSOPClass, effectedinstamceUid)
            {
                Dataset = dataset
            };

            bool result = false;

            dicomStartRequest.OnResponseReceived += (req, res) =>
            {
                if (res != null)
                {
                    if (res.Status == DicomStatus.Success)
                    {
                        Logger.Debug("Set study [{0}] [In Progress] Success.", studyInstanceUID);

                        result = true;
                    }
                    else
                    {
                        Logger.Warn("Set study [{0}] [In Progress] Failed. [{1}]", studyInstanceUID, res.Status);
                    }
                }
            };

            DicomClient client = new DicomClient(serverIp, serverPort, false, localAET, serverAET);
            await client.AddRequestAsync(dicomStartRequest);

            await client.SendAsync();

            return(effectedinstamceUid, studyInstanceUID, result);
        }
コード例 #8
0
        public async Task ClientHandleNEventReport_SynchronousEvent()
        {
            var port = Ports.GetNext();

            using (DicomServerFactory.Create <SimpleStorageComitmentProvider>(port))
            {
                DicomStatus status                   = null;
                int         verifiedInstances        = 0;
                DateTime    stampNActionResponse     = DateTime.MinValue;
                DateTime    stampNEventReportRequest = DateTime.MinValue;

                var dicomClient = DicomClientFactory.Create("127.0.0.1", port, false, "SCU", "ANY-SCP");

                var nActionDicomDataSet = new DicomDataset
                {
                    { DicomTag.TransactionUID, DicomUIDGenerator.GenerateDerivedFromUUID().UID },
                    {
                        DicomTag.ReferencedSOPSequence,
                        new DicomDataset()
                        {
                            { DicomTag.ReferencedSOPClassUID, "1.2.840.10008.5.1.4.1.1.1" },
                            { DicomTag.ReferencedSOPInstanceUID, "1.3.46.670589.30.2273540226.4.54" }
                        },
                        new DicomDataset()
                        {
                            { DicomTag.ReferencedSOPClassUID, "1.2.840.10008.5.1.4.1.1.1" },
                            { DicomTag.ReferencedSOPInstanceUID, "1.3.46.670589.30.2273540226.4.59" }
                        }
                    }
                };

                var nActionRequest = new DicomNActionRequest(DicomUID.StorageCommitmentPushModel, DicomUID.StorageCommitmentPushModel, 1)
                {
                    Dataset            = nActionDicomDataSet,
                    OnResponseReceived = (DicomNActionRequest request, DicomNActionResponse response) =>
                    {
                        status = response.Status;
                        stampNActionResponse = DateTime.Now;
                    },
                };

                await dicomClient.AddRequestAsync(nActionRequest);

                dicomClient.OnNEventReportRequest = (eventReq) =>
                {
                    var refSopSequence = eventReq.Dataset.GetSequence(DicomTag.ReferencedSOPSequence);
                    foreach (var item in refSopSequence.Items)
                    {
                        verifiedInstances += 1;
                    }
                    stampNEventReportRequest = DateTime.Now;
                    return(Task.FromResult(new DicomNEventReportResponse(eventReq, DicomStatus.Success)));
                };

                dicomClient.ClientOptions.AssociationLingerTimeoutInMs = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
                await dicomClient.SendAsync().ConfigureAwait(false);

                Assert.Equal(DicomStatus.Success, status);
                Assert.Equal(2, verifiedInstances);
                Assert.True(stampNActionResponse < stampNEventReportRequest);
            }
        }
コード例 #9
0
        static private DicomPre CreatePresentationState(string[] sourceFilePaths, bool colorSoftcopy, string seriesDescription, int layerCount = 1)
        {
            DicomPre pre = default;

            DicomSource[] sources = new DicomSource[sourceFilePaths.Length];
            for (int sourceFileIndex = 0; sourceFileIndex != sourceFilePaths.Length; sourceFileIndex++)
            {
                DicomDataset sourceDataset = DicomFile.Open(sourceFilePaths[sourceFileIndex]).Dataset;
                sources[sourceFileIndex].StudyInstanceUid  = sourceDataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
                sources[sourceFileIndex].SeriesInstanceUid = sourceDataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID);
                sources[sourceFileIndex].SopInstanceUid    = sourceDataset.GetSingleValue <string>(DicomTag.SOPInstanceUID);
                sources[sourceFileIndex].SopClassUid       = sourceDataset.GetSingleValue <string>(DicomTag.SOPClassUID);
                sources[sourceFileIndex].Columns           = sourceDataset.GetSingleValue <ushort>(DicomTag.Columns);
                sources[sourceFileIndex].Rows          = sourceDataset.GetSingleValue <ushort>(DicomTag.Rows);
                sources[sourceFileIndex].PixelSpacings = sourceDataset.GetValues <double>(DicomTag.PixelSpacing);
                sources[sourceFileIndex].WindowCenters = sourceDataset.GetValues <double>(DicomTag.WindowCenter);
                sources[sourceFileIndex].WindowWidths  = sourceDataset.GetValues <double>(DicomTag.WindowWidth);
            }
            pre.PresentationStateDataset = new DicomDataset();
            pre.Columns = sources[0].Columns;
            pre.Rows    = sources[0].Rows;

            pre.PresentationStateDataset.Add(DicomTag.StudyInstanceUID, sources[0].StudyInstanceUid);
            pre.PresentationStateDataset.Add(DicomTag.SeriesInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID().UID);
            pre.PresentationStateDataset.Add(DicomTag.SOPInstanceUID, DicomUIDGenerator.GenerateDerivedFromUUID().UID);
            pre.PresentationStateDataset.Add(DicomTag.SOPClassUID, colorSoftcopy ? DicomUID.ColorSoftcopyPresentationStateStorage : DicomUID.GrayscaleSoftcopyPresentationStateStorage);
            pre.PresentationStateDataset.Add(DicomTag.Modality, "PR");
            pre.PresentationStateDataset.Add(DicomTag.SpecificCharacterSet, "ISO_IR 192");
            pre.PresentationStateDataset.AddOrUpdate(DicomTag.SeriesDescription, seriesDescription);

            DicomSequence referencedSeriesSequence = new DicomSequence(DicomTag.ReferencedSeriesSequence);

            DicomDataset[] referencedSeriesDatasets = new DicomDataset[sourceFilePaths.Length];

            for (int sourceFileIndex = 0; sourceFileIndex != sourceFilePaths.Length; sourceFileIndex++)
            {
                referencedSeriesDatasets[sourceFileIndex] = new DicomDataset().NotValidated();
                referencedSeriesDatasets[sourceFileIndex].Add(DicomTag.SeriesInstanceUID, sources[0].SeriesInstanceUid);
                DicomSequence referencedImageSequence = new DicomSequence(DicomTag.ReferencedImageSequence);
                DicomDataset  referencedImageDataset  = new DicomDataset();
                referencedImageDataset.Add(DicomTag.ReferencedSOPClassUID, sources[sourceFileIndex].SopClassUid);
                referencedImageDataset.Add(DicomTag.ReferencedSOPInstanceUID, sources[sourceFileIndex].SopInstanceUid);
                referencedImageSequence.Items.Add(referencedImageDataset);
                referencedSeriesDatasets[sourceFileIndex].Add(referencedImageSequence);
                referencedSeriesSequence.Items.Add(referencedSeriesDatasets[sourceFileIndex]);
            }
            pre.PresentationStateDataset.Add(referencedSeriesSequence);

            DicomSequence graphicLayerSequence = new DicomSequence(DicomTag.GraphicLayerSequence);

            for (int layerIndex = 0; layerIndex != layerCount; layerIndex++)
            {
                DicomDataset graphicLayerDataset = new DicomDataset();
                graphicLayerDataset.Add(DicomTag.GraphicLayer, layerIndex.ToString());
                graphicLayerDataset.Add(DicomTag.GraphicLayerOrder, layerIndex);
                graphicLayerSequence.Items.Add(graphicLayerDataset);
            }
            pre.PresentationStateDataset.Add(graphicLayerSequence);

            DicomSequence graphicAnnotationSequence = new DicomSequence(DicomTag.GraphicAnnotationSequence);

            pre.GraphicObjectSequences = new DicomSequence[sourceFilePaths.Length][];
            pre.TextObjectSequences    = new DicomSequence[sourceFilePaths.Length][];
            for (int sourceFileIndex = 0; sourceFileIndex != sourceFilePaths.Length; sourceFileIndex++)
            {
                pre.GraphicObjectSequences[sourceFileIndex] = new DicomSequence[layerCount];
                pre.TextObjectSequences[sourceFileIndex]    = new DicomSequence[layerCount];
                for (int layerIndex = 0; layerIndex != layerCount; layerIndex++)
                {
                    DicomDataset graphicAnnotationDataset = new DicomDataset();
                    graphicAnnotationDataset.Add(referencedSeriesDatasets[sourceFileIndex].GetSequence(DicomTag.ReferencedImageSequence));
                    pre.GraphicObjectSequences[sourceFileIndex][layerIndex] = new DicomSequence(DicomTag.GraphicObjectSequence);
                    pre.TextObjectSequences[sourceFileIndex][layerIndex]    = new DicomSequence(DicomTag.TextObjectSequence);
                    graphicAnnotationDataset.Add(pre.GraphicObjectSequences[sourceFileIndex][layerIndex]);
                    graphicAnnotationDataset.Add(pre.TextObjectSequences[sourceFileIndex][layerIndex]);
                    graphicAnnotationDataset.Add(DicomTag.GraphicLayer, layerIndex.ToString());
                    graphicAnnotationSequence.Items.Add(graphicAnnotationDataset);
                }
            }
            pre.PresentationStateDataset.Add(graphicAnnotationSequence);

            DicomSequence displayedAreaSelectionSequence = new DicomSequence(DicomTag.DisplayedAreaSelectionSequence);

            for (int sourceFileIndex = 0; sourceFileIndex != sourceFilePaths.Length; sourceFileIndex++)
            {
                DicomDataset displayedAreaSelectionDataset = new DicomDataset();
                displayedAreaSelectionDataset.Add(referencedSeriesDatasets[sourceFileIndex].GetSequence(DicomTag.ReferencedImageSequence));
                displayedAreaSelectionDataset.Add(DicomTag.DisplayedAreaTopLeftHandCorner, 1, 1);
                displayedAreaSelectionDataset.Add(DicomTag.DisplayedAreaBottomRightHandCorner, (int)pre.Columns, (int)pre.Rows);
                displayedAreaSelectionDataset.Add(DicomTag.PresentationSizeMode, "SCALE TO FIT");
                displayedAreaSelectionDataset.Add(DicomTag.PresentationPixelSpacing, sources[sourceFileIndex].PixelSpacings);
                displayedAreaSelectionSequence.Items.Add(displayedAreaSelectionDataset);
            }
            pre.PresentationStateDataset.Add(displayedAreaSelectionSequence);

            DicomSequence softcopyVoiLutSequence = new DicomSequence(DicomTag.SoftcopyVOILUTSequence);
            DicomDataset  softcopyVoiLutDataset  = new DicomDataset();

            softcopyVoiLutDataset.Add(DicomTag.WindowCenter, sources[0].WindowCenters);
            softcopyVoiLutDataset.Add(DicomTag.WindowWidth, sources[0].WindowWidths);
            softcopyVoiLutSequence.Items.Add(softcopyVoiLutDataset);
            pre.PresentationStateDataset.Add(softcopyVoiLutSequence);

            return(pre);
        }