コード例 #1
0
        /// <summary>
        /// Saves specified <code>InstanceStorage</code> to disk.
        /// </summary>
        /// <param name="request">Instance of <code>DicomCStoreRequest</code> to be stored to disk.</param>
        /// <param name="instanceStorage">Instance of <code>InstanceStorage</code></param>
        public void Save(DicomCStoreRequest request, InstanceStorageInfo instanceStorage)
        {
            Guard.Against.Null(instanceStorage, nameof(instanceStorage));

            if (ShouldBeIgnored(instanceStorage.SopClassUid))
            {
                _logger.Log(LogLevel.Warning, "Instance with SOP Class {0} ignored based on configured AET {1}", instanceStorage.SopClassUid, Configuration.AeTitle);
                return;
            }

            Policy.Handle <Exception>()
            .WaitAndRetry(3,
                          (retryAttempt) =>
            {
                return(retryAttempt == 1 ? TimeSpan.FromMilliseconds(250) : TimeSpan.FromMilliseconds(500));
            },
                          (exception, retryCount, context) =>
            {
                _logger.Log(LogLevel.Error, "Failed to save instance, retry count={retryCount}: {exception}", retryCount, exception);
            })
            .Execute(() =>
            {
                if (ShouldSaveInstance(instanceStorage))
                {
                    _logger.Log(LogLevel.Information, "Saving {path}.", instanceStorage.InstanceStorageFullPath);
                    _dicomToolkit.Save(request.File, instanceStorage.InstanceStorageFullPath);
                    _logger.Log(LogLevel.Debug, "Instance saved successfully.");
                    _instanceStoredNotificationService.NewInstanceStored(instanceStorage);
                    _logger.Log(LogLevel.Information, "Instance stored and notified successfully.");
                }
            });
        }
コード例 #2
0
        public IEnumerable <DicomCGetResponse> OnCGetRequest(DicomCGetRequest request)
        {
            IDicomImageFinderService finderService = QRServer.CreateFinderService;
            List <string>            matchingFiles = null;

            switch (request.Level)
            {
            case DicomQueryRetrieveLevel.Patient:
                matchingFiles = finderService.FindFilesByUID(request.Dataset.Get <string>(DicomTag.PatientID), string.Empty, string.Empty);
                break;

            case DicomQueryRetrieveLevel.Study:
                matchingFiles = finderService.FindFilesByUID(string.Empty, request.Dataset.Get <string>(DicomTag.StudyInstanceUID), string.Empty);
                break;

            case DicomQueryRetrieveLevel.Series:
                matchingFiles = finderService.FindFilesByUID(string.Empty, string.Empty, request.Dataset.Get <string>(DicomTag.SeriesInstanceUID));
                break;

            case DicomQueryRetrieveLevel.Image:
                yield return(new DicomCGetResponse(request, DicomStatus.QueryRetrieveUnableToPerformSuboperations));

                yield break;
            }

            foreach (var matchingFile in matchingFiles)
            {
                var storeRequest = new DicomCStoreRequest(matchingFile);
                SendRequest(storeRequest);
            }

            yield return(new DicomCGetResponse(request, DicomStatus.Success));
        }
コード例 #3
0
        public async Task OnCStoreRequestAsync_PreferedTransfersyntax()
        {
            var port = Ports.GetNext();

            using (DicomServerFactory.Create <AsyncDicomCStoreProviderPreferingUncompressedTS>(port, logger: _logger.IncludePrefix("DicomServer")))
            {
                var client = DicomClientFactory.Create("127.0.0.1", port, false, "SCU", "ANY-SCP");
                client.Logger = _logger.IncludePrefix(typeof(DicomClient).Name);

                int numberOfContexts           = 0;
                DicomTransferSyntax accpetedTS = null;
                // create a request with a jpeg-encoded file
                var request = new DicomCStoreRequest(TestData.Resolve("CT1_J2KI"));
                client.AssociationAccepted += (sender, e) =>
                {
                    numberOfContexts = e.Association.PresentationContexts.Count;
                    accpetedTS       = e.Association.PresentationContexts.First().AcceptedTransferSyntax;
                };
                await client.AddRequestAsync(request).ConfigureAwait(false);

                await client.SendAsync().ConfigureAwait(false);

                Assert.Equal(2, numberOfContexts); // one for the jpeg2k TS and one for the mandatory ImplicitLittleEndian
                Assert.Equal(DicomTransferSyntax.JPEG2000Lossy, accpetedTS);
            }
        }
コード例 #4
0
ファイル: DicomSCU.cs プロジェクト: Moshekri/DicomTransformer
 public void Send(string filePath, string ipAddress, string callingAe, string targetAeTitle, int port)
 {
     locker = new object();
     lock (locker)
     {
         try
         {
             var         req    = new DicomCStoreRequest(filePath);
             DicomClient client = new DicomClient();
             client.NegotiateAsyncOps();
             client.AddRequest(req);
             client.Send(ipAddress, port, false, callingAe, targetAeTitle);
         }
         catch (Exception ex)
         {
             if (retryCount > 10)
             {
                 throw new Exception($"Remote Host {ipAddress}:{port} did not respond ...  ");
             }
             retryCount++;
             string error = ex.Message;
             if (error.Contains("TemporaryCongestion"))
             {
                 Thread.Sleep(5000);
                 Send(filePath, ipAddress, callingAe, targetAeTitle, port);
             }
         }
     }
 }
コード例 #5
0
        public void HandleCStoreRequest(DicomCStoreRequest request, string calledAeTitle, uint associationId)
        {
            Guard.Against.Null(request, nameof(request));

            if (!_aeTitleManagers.ContainsKey(calledAeTitle))
            {
                throw new ArgumentException($"Called AE Title '{calledAeTitle}' is not configured");
            }

            if (!_storageInfoProvider.HasSpaceAvailableToStore)
            {
                throw new InsufficientStorageAvailableException($"Insufficient storage available.  Available storage space: {_storageInfoProvider.AvailableFreeSpace:D}");
            }

            _logger.Log(LogLevel.Information, $"Preparing to save instance received for {calledAeTitle} in {_aeTitleManagers[calledAeTitle].Value.AeStorageRootFullPath}.");

            var instanceStorage = InstanceStorageInfo.CreateInstanceStorageInfo(request, _aeTitleManagers[calledAeTitle].Value.AeStorageRootFullPath, calledAeTitle, associationId);

            using (_logger.BeginScope("SOPInstanceUID={0}", instanceStorage.SopInstanceUid))
            {
                _logger.Log(LogLevel.Information, "Patient ID: {PatientId}", instanceStorage.PatientId);
                _logger.Log(LogLevel.Information, "Study Instance UID: {StudyInstanceUid}", instanceStorage.StudyInstanceUid);
                _logger.Log(LogLevel.Information, "Series Instance UID: {SeriesInstanceUid}", instanceStorage.SeriesInstanceUid);
                _logger.Log(LogLevel.Information, "Storage File Path: {InstanceStorageFullPath}", instanceStorage.InstanceStorageFullPath);

                _aeTitleManagers[calledAeTitle].Value.Save(request, instanceStorage);
                _logger.Log(LogLevel.Debug, $"Instance saved with handler {instanceStorage.InstanceStorageFullPath}");
            }
        }
コード例 #6
0
        public async Task OnCStoreRequestAsync_ShouldRespond()
        {
            var port = Ports.GetNext();

            using (DicomServerFactory.Create <AsyncDicomCStoreProvider>(port, logger: _logger.IncludePrefix("DicomServer")))
            {
                var client = DicomClientFactory.Create("127.0.0.1", port, false, "SCU", "ANY-SCP");
                client.Logger = _logger.IncludePrefix(typeof(DicomClient).Name);

                DicomCStoreResponse             response = null;
                DicomRequest.OnTimeoutEventArgs timeout  = null;
                var request = new DicomCStoreRequest(TestData.Resolve("10200904.dcm"))
                {
                    OnResponseReceived = (req, res) => response = res,
                    OnTimeout          = (sender, args) => timeout = args
                };

                await client.AddRequestAsync(request).ConfigureAwait(false);

                await client.SendAsync().ConfigureAwait(false);

                Assert.NotNull(response);
                Assert.Equal(DicomStatus.Success, response.Status);
                Assert.Null(timeout);
            }
        }
コード例 #7
0
        public async Task SendAsync_SingleRequest_DataSufficientlyTransported()
        {
            int port = Ports.GetNext();

            using var _ = DicomServerFactory.Create <SimpleCStoreProvider>(port);

            DicomDataset command = null, dataset = null;
            var          request = new DicomCStoreRequest(TestData.Resolve("CT1_J2KI"));

            request.OnResponseReceived = (req, res) =>
            {
                command = request.Command;
                dataset = request.Dataset;
            };

            var client = DicomClientFactory.Create("127.0.0.1", port, false, "SCU", "ANY-SCP");
            await client.AddRequestAsync(request).ConfigureAwait(false);

            await client.SendAsync().ConfigureAwait(false);

            var commandField = command.GetSingleValue <ushort>(DicomTag.CommandField);

            Assert.Equal((ushort)1, commandField);

            var modality = dataset.GetSingleValue <string>(DicomTag.Modality);

            Assert.Equal("CT", modality);
        }
コード例 #8
0
        public void CStoreRequestSend_VideoFileServerSupportsMPEG2_TransferSuccessful()
        {
            const string fileName = "GH526.dcm";

            using (var webClient = new WebClient())
            {
                webClient.DownloadFile(
                    @"https://www.creatis.insa-lyon.fr/~jpr/PUBLIC/gdcm/gdcmSampleData/DICOM_MPEG_from_ETIAM/ETIAM_video_002.dcm",
                    fileName);
            }

            var success = false;
            var handle  = new ManualResetEventSlim();

            var port = Ports.GetNext();

            using (DicomServer.Create <VideoCStoreProvider>(port))
            {
                var request = new DicomCStoreRequest(fileName);
                request.OnResponseReceived = (req, rsp) =>
                {
                    success = req.Dataset.InternalTransferSyntax.Equals(DicomTransferSyntax.MPEG2) &&
                              rsp.Status == DicomStatus.Success;
                    handle.Set();
                };

                var client = new DicomClient();
                client.AddRequest(request);
                client.Send("localhost", port, false, "STORESCU", "STORESCP");
                handle.Wait(10000);

                Assert.True(success);
            }
        }
コード例 #9
0
        public DicomCStoreResponse OnCStoreRequest(DicomCStoreRequest request)
        {
            var patientid   = request.Dataset.GetSingleValue <string>(DicomTag.PatientID);
            var patientName = request.Dataset.GetSingleValue <string>(DicomTag.PatientName);

            patientName = patientName.Replace("^", " ");
            patientName = Regex.Replace(patientName, "[ ]+", " ");
            var studyUid = request.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            var instUid  = request.SOPInstanceUID.UID;

            var path = Path.GetFullPath(RetrieveSaveFolder);

            path = Path.Combine(path, patientName + "_" + patientid);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, studyUid);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            path = Path.Combine(path, instUid) + ".dcm";

            request.File.Save(path);

            return(new DicomCStoreResponse(request, DicomStatus.Success));
        }
コード例 #10
0
        public async Task AcceptStoreContexts()
        {
            int port = Ports.GetNext();

            using (DicomServerFactory.Create <AcceptOnlyEchoStoreProvider>(port))
            {
                var         echoReq    = new DicomCEchoRequest();
                DicomStatus echoStatus = DicomStatus.Pending;
                echoReq.OnResponseReceived += (req, resp) => echoStatus = resp.Status;

                var         storeReq    = new DicomCStoreRequest(TestData.Resolve("CT1_J2KI"));
                DicomStatus storeStatus = DicomStatus.Pending;
                storeReq.OnResponseReceived += (req, resp) => storeStatus = resp.Status;

                var         filmSession = new FilmSession(DicomUID.BasicFilmSession, DicomUID.Generate());
                var         printReq    = new DicomNCreateRequest(filmSession.SOPClassUID, filmSession.SOPInstanceUID);
                DicomStatus printStatus = DicomStatus.Pending;
                printReq.OnResponseReceived += (req, resp) => printStatus = resp.Status;

                var client = DicomClientFactory.Create("127.0.0.1", port, false, "SCU", "ANY-SCP");
                await client.AddRequestsAsync(new DicomRequest[] { echoReq, storeReq, printReq });

                await client.SendAsync();

                Assert.Equal(DicomStatus.Success, echoStatus);
                Assert.Equal(DicomStatus.Success, storeStatus);
                Assert.Equal(DicomStatus.SOPClassNotSupported, printStatus);
            }
        }
コード例 #11
0
        public IEnumerable <DicomCMoveResponse> OnCMoveRequest(DicomCMoveRequest request)
        {
            List <DicomCMoveResponse> response = new List <DicomCMoveResponse>();
            List <Pathmodel>          pathList = qrm.CMove(request.Dataset, request.Level);
            DicomClient cstoreClient           = new DicomClient();

            try
            {
                foreach (Pathmodel p in pathList)
                {
                    DicomCStoreRequest cstorerq = new DicomCStoreRequest(p.Path);
                    cstorerq.OnResponseReceived = (rq, rs) =>
                    {
                        if (rs.Status == DicomStatus.Success)
                        {
                            DicomCMoveResponse rsp = new DicomCMoveResponse(request, DicomStatus.Pending);
                            SendResponse(rsp);
                        }
                    };
                    cstoreClient.AddRequest(cstorerq);
                    cstoreClient.Send("127.0.0.1", 2222, false, this.Association.CalledAE, request.DestinationAE);
                }
                return(response);
            }
            catch
            {
                DicomCMoveResponse rs = new DicomCMoveResponse(request, DicomStatus.StorageStorageOutOfResources);
                response.Add(rs);
                return(response);
            }
        }
コード例 #12
0
        public DicomCStoreResponse OnCStoreRequest(DicomCStoreRequest request)
        {
            var studyUid       = request.Dataset.GetString(DicomTag.StudyInstanceUID);
            var patientId      = request.Dataset.GetString(DicomTag.PatientID);
            var seriesNumber   = request.Dataset.GetString(DicomTag.InstanceNumber);
            var studyDate      = request.Dataset.GetString(DicomTag.StudyDate);
            var sOPInstanceUID = request.Dataset.GetString(DicomTag.SOPInstanceUID);
            var instUid        = $"1.2.840.113619.2.81.290.{studyDate}.{patientId}";

            request.Dataset.Remove(DicomTag.StudyInstanceUID);
            request.Dataset.AddOrUpdate(DicomTag.StudyInstanceUID, instUid);
            var instUidAux = $"1.2.840.113619.2.81.290.{studyDate}.{patientId}";

            request.Dataset.Remove(DicomTag.SeriesInstanceUID);
            request.Dataset.AddOrUpdate(DicomTag.SeriesInstanceUID, instUidAux + $".{seriesNumber}");
            //var path = Path.GetFullPath(@".\DICOM");
            request.Dataset.Remove(DicomTag.SOPInstanceUID);
            request.Dataset.AddOrUpdate(DicomTag.SOPInstanceUID, sOPInstanceUID + $".{patientId}");

            var path = "C:\\INFINITT\\Spool";

            path = Path.Combine(path, instUid + $".{seriesNumber}" + ".dcm");

            //if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            //path = Path.Combine(path, instUid) + ".dcm";

            request.File.Save(path);

            return(new DicomCStoreResponse(request, DicomStatus.Success));
        }
コード例 #13
0
    // Update is called once per frame
    private void Update()
    {
        var fileName = _fileNames[_currIdx++];

        if (_currIdx == _fileNames.Length)
        {
            _currIdx = 0;
        }

        var path = $"{FileLocation}{fileName}.bytes";

        Debug.LogFormat("Path: {0}", path);

        var file = DicomFile.Open(path);

        Debug.LogFormat("File format: {0}", file.Format);

        var request = new DicomCStoreRequest(file);

        request.OnResponseReceived = (rq, rsp) =>
        {
            Debug.LogFormat("Transfer syntax: {0}, SOP instance UID: {1}", rq.TransferSyntax, rq.SOPInstanceUID.UID);
            Debug.LogFormat("Response status: {0}", rsp.Status);
        };

        Debug.LogFormat("Request created, instance UID: {0}, transfer syntax: {1}", request.SOPInstanceUID.UID,
                        request.TransferSyntax);

        _client.AddRequest(request);
        _client.Send("127.0.0.1", 11112, false, "STORESCU", "STORESCP");
    }
コード例 #14
0
        static async Task SendTask(TransmissionInfo info)
        {
            try
            {
                var client = new DicomClient();

                foreach (var file in info.Folder.GetFiles("*.*", SearchOption.AllDirectories))
                {
                    DicomCStoreRequest request = new DicomCStoreRequest(file.FullName);
                    request.OnResponseReceived += (req, rsp) =>
                    {
                        //             Console.WriteLine(rsp.Status + $"{req.MessageID}, {Thread.CurrentThread.ManagedThreadId}");
                    };
                    client.AddRequest(request);
                }

                var task1 = AbortTask(client, info.Token, info.TaskId);

                var node  = PacsNode.Strongs;
                var task2 = client.SendAsync(node.Host, node.Port, false, "SCU", node.AET);

                await Task.WhenAny(task1, task2);

                client.Release();
                Console.WriteLine($"Complete {info.TaskId}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {info.TaskId} " + ex.Message);
            }
        }
コード例 #15
0
ファイル: QRService.cs プロジェクト: derek-cap/FodicomTest
        public IEnumerable <DicomCGetResponse> OnCGetRequest(DicomCGetRequest request)
        {
            List <string> matchingFiles = new List <string>();

            switch (request.Level)
            {
            case DicomQueryRetrieveLevel.Patient:
                break;

            case DicomQueryRetrieveLevel.Study:
                break;

            case DicomQueryRetrieveLevel.Series:
                break;

            case DicomQueryRetrieveLevel.Image:
                yield return(new DicomCGetResponse(request, DicomStatus.QueryRetrieveUnableToPerformSuboperations));

                yield break;
            }

            foreach (var matchingFile in matchingFiles)
            {
                var storeRequest = new DicomCStoreRequest(matchingFile);
                SendRequestAsync(storeRequest).Wait();
            }
            yield return(new DicomCGetResponse(request, DicomStatus.Success));
        }
コード例 #16
0
        private InstanceStorageInfo(DicomCStoreRequest request, string storageRootFullPath, string calledAeTitle, uint associationId, IFileSystem fileSystem)
        {
            Guard.Against.Null(request, nameof(request));
            Guard.Against.NullOrWhiteSpace(storageRootFullPath, nameof(storageRootFullPath));
            Guard.Against.NullOrWhiteSpace(calledAeTitle, nameof(calledAeTitle));
            Guard.Against.Null(fileSystem, nameof(fileSystem));

            _fileSystem = fileSystem;

            AeStoragePath = storageRootFullPath;
            CalledAeTitle = calledAeTitle;

            var temp        = string.Empty;
            var missingTags = new List <DicomTag>();

            if (!request.Dataset.TryGetSingleValue(DicomTag.PatientID, out temp))
            {
                missingTags.Add(DicomTag.PatientID);
            }
            else
            {
                PatientId = temp;
            }

            if (!request.Dataset.TryGetSingleValue(DicomTag.StudyInstanceUID, out temp))
            {
                missingTags.Add(DicomTag.StudyInstanceUID);
            }
            else
            {
                StudyInstanceUid = temp;
            }
            if (!request.Dataset.TryGetSingleValue(DicomTag.SeriesInstanceUID, out temp))
            {
                missingTags.Add(DicomTag.SeriesInstanceUID);
            }
            else
            {
                SeriesInstanceUid = temp;
            }

            if (missingTags.Count != 0)
            {
                throw new MissingRequiredTagException(missingTags.ToArray());
            }

            SopClassUid    = request.SOPClassUID.UID;
            SopInstanceUid = request.SOPInstanceUID.UID;

            AeStoragePath      = fileSystem.Path.Combine(AeStoragePath, associationId.ToString());
            AeStoragePath      = fileSystem.Path.GetDicomStoragePath(AeStoragePath);
            PatientStoragePath = fileSystem.Path.Combine(AeStoragePath, PatientId.RemoveInvalidPathChars());

            StudyStoragePath  = fileSystem.Path.Combine(PatientStoragePath, StudyInstanceUid.RemoveInvalidPathChars());
            SeriesStoragePath = fileSystem.Path.Combine(StudyStoragePath, SeriesInstanceUid.RemoveInvalidPathChars());

            fileSystem.Directory.CreateDirectoryIfNotExists(SeriesStoragePath);

            InstanceStorageFullPath = fileSystem.Path.Combine(SeriesStoragePath, SopInstanceUid.RemoveInvalidPathChars()) + ".dcm";
        }
コード例 #17
0
        public async Task StoreImageAsync(string serverIp, int serverPort, string serverAET, string localAET, IEnumerable <CStoreItem> items)
        {
            DicomClient client = new DicomClient(serverIp, serverPort, false, localAET, serverAET);

            client.NegotiateAsyncOps();

            foreach (CStoreItem item in items)
            {
                DicomCStoreRequest request = new DicomCStoreRequest(item.File)
                {
                    OnResponseReceived = (req, res) =>
                    {
                        if (res.Status != DicomStatus.Success)
                        {
                            Logger.Error("C-STORE send failed. Instance UID - [{0}]", req.SOPInstanceUID);
                            item.Status = CStoreItemStatus.Failed;
                        }
                        else
                        {
                            item.Status = CStoreItemStatus.Success;
                        }
                    }
                };

                await client.AddRequestAsync(request);
            }

            await client.SendAsync();
        }
コード例 #18
0
        private void GenerateRequests(
            OutputJob job,
            DicomClient client,
            CountdownEvent countDownEventHandle)
        {
            while (job.PendingDicomFiles.Count > 0)
            {
                try
                {
                    var request = new DicomCStoreRequest(job.PendingDicomFiles.Dequeue());

                    request.OnResponseReceived += (req, response) =>
                    {
                        if (response.Status != DicomStatus.Success)
                        {
                            job.FailedDicomFiles.Add(request.File, response.Status.ToString());
                        }
                        else
                        {
                            job.ProcessedDicomFiles.Add(request.File);
                            job.Logger.LogInformation("Instance {0} sent successfully", request.File.FileMetaInfo.MediaStorageSOPInstanceUID.UID);
                        }
                        countDownEventHandle.Signal();
                    };

                    client.AddRequestAsync(request).ConfigureAwait(false);
                }
                catch (Exception exception)
                {
                    job.Logger.LogError("Error while adding DICOM C-STORE request: {0}", exception);
                }
            }
        }
コード例 #19
0
ファイル: GH526.cs プロジェクト: fo-dicom/fo-dicom
        public async Task CStoreRequestSend_VideoFileServerSupportsMPEG4_TransferSuccessful()
        {
            string fileName = TestData.Resolve("test_720.dcm");
            var    success  = false;
            var    handle   = new ManualResetEventSlim();

            var port = Ports.GetNext();

            using var server = DicomServerFactory.Create <VideoCStoreProvider>(port);
            server.Logger    = _logger.IncludePrefix("VideoCStoreProvider");

            var request = new DicomCStoreRequest(fileName)
            {
                OnResponseReceived = (req, rsp) =>
                {
                    success = req.Dataset.InternalTransferSyntax.Equals(
                        DicomTransferSyntax.Lookup(DicomUID.MPEG4HP41)) &&
                              rsp.Status == DicomStatus.Success;
                    handle.Set();
                }
            };

            var client = DicomClientFactory.Create("localhost", port, false, "STORESCU", "STORESCP");

            client.Logger = _logger.IncludePrefix("DicomClient");

            await client.AddRequestAsync(request).ConfigureAwait(false);

            await client.SendAsync().ConfigureAwait(false);

            handle.Wait(10000);

            Assert.True(success);
        }
コード例 #20
0
        public DicomCStoreResponse OnCStoreRequest(DicomCStoreRequest request)
        {
            string studyUid = request.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID);
            string instUid  = request.SOPInstanceUID.UID;

            // 设置中应该支持设置存储目录
            string path = Path.GetFullPath(StoreServer.Default.DcmDirPath);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            path = Path.Combine(path, studyUid);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            path = Path.Combine(path, instUid) + ".dcm";

            request.File.Save(path);

            receivedFiles.Add(path);

            return(new DicomCStoreResponse(request, DicomStatus.Success));
        }
コード例 #21
0
        public void OldCStoreRequestSend_VideoFileServerSupportsMPEG4_TransferSuccessful()
        {
            const string fileName = @"Test Data/test_720.dcm";
            var          success  = false;
            var          handle   = new ManualResetEventSlim();

            var port = Ports.GetNext();

            using (DicomServer.Create <VideoCStoreProvider>(port))
            {
                var request = new DicomCStoreRequest(fileName);
                request.OnResponseReceived = (req, rsp) =>
                {
                    success = req.Dataset.InternalTransferSyntax.Equals(
                        DicomTransferSyntax.Lookup(DicomUID.MPEG4HP41)) &&
                              rsp.Status == DicomStatus.Success;
                    handle.Set();
                };

                var client = new Network.DicomClient();
                client.AddRequest(request);
                client.Send("localhost", port, false, "STORESCU", "STORESCP");
                handle.Wait(10000);

                Assert.True(success);
            }
        }
コード例 #22
0
ファイル: GH526.cs プロジェクト: fo-dicom/fo-dicom
        public async Task CStoreRequestSend_VideoFileServerSupportsMPEG2_TransferSuccessful()
        {
            string fileName = TestData.Resolve("ETIAM_video_002.dcm");

            var success = false;
            var handle  = new ManualResetEventSlim();

            var port = Ports.GetNext();

            using (DicomServerFactory.Create <VideoCStoreProvider>(port))
            {
                var request = new DicomCStoreRequest(fileName);
                request.OnResponseReceived = (req, rsp) =>
                {
                    success = req.Dataset.InternalTransferSyntax.Equals(DicomTransferSyntax.MPEG2) &&
                              rsp.Status == DicomStatus.Success;
                    handle.Set();
                };

                var client = DicomClientFactory.Create("localhost", port, false, "STORESCU", "STORESCP");
                await client.AddRequestAsync(request).ConfigureAwait(false);

                await client.SendAsync().ConfigureAwait(false);

                handle.Wait(10000);

                Assert.True(success);
            }
        }
コード例 #23
0
        private static void saveSeries(DicomCStoreRequest request)
        {
            string path = File.ReadAllLines("pathForDownload.txt")[0];

            // get parameters
            string SOPInstanceUID = "";

            request.Dataset.TryGetSingleValue(DicomTag.SOPInstanceUID, out SOPInstanceUID);

            var configuration = new Configuration();

            // Anonymize all files
            if (configuration.anonymizeData)
            {
                request.Dataset = request.Dataset.AddOrUpdate(DicomTag.PatientName, "random");
                request.Dataset = request.Dataset.AddOrUpdate(DicomTag.PatientID, "random");
                request.Dataset = request.Dataset.AddOrUpdate(DicomTag.StudyDate, DateTime.Now);
            }

            // save
            string filePath = Path.Combine(path, SOPInstanceUID + ".dcm");

            request.File.Save(filePath);

            updateDatabase();
        }
コード例 #24
0
ファイル: DicomServerTest.cs プロジェクト: fo-dicom/fo-dicom
        public async Task Send_PrivateRegisteredSOPClass_SendSucceeds()
        {
            var uid = new DicomUID("1.1.1.1", "Private Fo-Dicom Storage", DicomUidType.SOPClass);

            DicomUID.Register(uid);
            var ds = new DicomDataset(
                new DicomUniqueIdentifier(DicomTag.SOPClassUID, uid),
                new DicomUniqueIdentifier(DicomTag.SOPInstanceUID, "1.2.3.4.5"));

            var port = Ports.GetNext();

            using (DicomServerFactory.Create <SimpleCStoreProvider>(port, logger: _logger.IncludePrefix("DicomServer")))
            {
                DicomStatus status  = null;
                var         request = new DicomCStoreRequest(new DicomFile(ds))
                {
                    OnResponseReceived = (req, res) => status = res.Status
                };

                var client = DicomClientFactory.Create("127.0.0.1", port, false, "SCU", "ANY-SCP");
                client.Logger = _logger.IncludePrefix("DicomClient");
                await client.AddRequestAsync(request);

                await client.SendAsync();

                Assert.Equal(DicomStatus.Success, status);
            }
        }
コード例 #25
0
ファイル: GH538.cs プロジェクト: zhaohh1985/fo-dicom
        public async Task CStoreRequestSend_16BitJpegFileToScpThatDoesNotSupportJpeg_TransferSuccessfulImplicitLENoPixelData()
        {
            const string file    = @"Test Data/GH538-jpeg14sv1.dcm";
            var          handle  = new ManualResetEventSlim();
            var          success = false;

            var port = Ports.GetNext();

            using (DicomServer.Create <VideoCStoreProvider>(port))
            {
                var request = new DicomCStoreRequest(file);
                request.OnResponseReceived = (req, rsp) =>
                {
                    if (req.Dataset.InternalTransferSyntax.Equals(DicomTransferSyntax.ImplicitVRLittleEndian) &&
                        !req.Dataset.Contains(DicomTag.PixelData) && rsp.Status == DicomStatus.Success)
                    {
                        success = true;
                    }
                    handle.Set();
                };

                var client = new Network.Client.DicomClient("localhost", port, false, "STORESCU", "STORESCP");
                await client.AddRequestAsync(request).ConfigureAwait(false);

                await client.SendAsync().ConfigureAwait(false);

                handle.Wait(10000);

                Assert.True(success);
            }
        }
コード例 #26
0
        /// <summary>
        /// Push a file to DICOM.
        /// </summary>
        /// <param name="routedItem"></param>
        /// <param name="taskID"></param>
        /// <param name="connection"></param>
        public void CStore(RoutedItem routedItem, long taskID, DICOMConnection connection)
        {
            Connection = connection;
            var taskInfo = $"task: {taskID} connection: {Connection.name}";

            try
            {
                try
                {
                    if (File.Exists(routedItem.sourceFileName))
                    {
                        var cStoreRequest = new DicomCStoreRequest(routedItem.sourceFileName);
                        routedItem.MessageId    = cStoreRequest.MessageID;
                        cStoreRequest.UserState = routedItem;
                        _logger.Log(LogLevel.Debug, $"{taskInfo} Request id: {routedItem.id} {cStoreRequest.MessageID}, {routedItem.sourceFileName} {routedItem.fileIndex}/{routedItem.fileCount} attempt: {routedItem.attempts}");

                        cStoreRequest.OnResponseReceived = (DicomCStoreRequest request, DicomCStoreResponse response) =>
                        {
                            var ri = (RoutedItem)request.UserState;
                            _logger.Log(LogLevel.Information, $"{taskInfo} Request id: {ri.id} {response.RequestMessageID} status: {response.Status.Code} description: {response.Status.Description} comment: {response.Status.ErrorComment} state: {response.Status.State}");

                            _routedItemManager.Init(ri);
                            //2018-08-01 shb BOUR-559 handle and log failure conditions
                            if (response.Status == DicomStatus.Success)
                            {
                                _routedItemManager.Dequeue(Connection, Connection.toDicom, nameof(Connection.toDicom), error: false);
                            }
                            else
                            {
                                _routedItemManager.Dequeue(Connection, Connection.toDicom, nameof(Connection.toDicom), error: true);
                            }

                            OnCStoreRequestComplete(request, response);
                        };

                        dicomClient.AddRequest(cStoreRequest);
                    }
                    else
                    {
                        _logger.Log(LogLevel.Information, $"{taskInfo} File does not exist: {routedItem.sourceFileName}");
                        _routedItemManager.Init(routedItem);
                        _routedItemManager.Dequeue(Connection, Connection.toDicom, nameof(Connection.toDicom), error: true);
                    }
                }
                catch (DicomDataException e)
                {
                    _logger.Log(LogLevel.Warning, $"{taskInfo} {routedItem.sourceFileName} {e.Message} {e.StackTrace} ");

                    // !e.GetType().IsAssignableFrom(typeof(DicomFileException)))

                    _routedItemManager.Init(routedItem);
                    _routedItemManager.Dequeue(Connection, Connection.toDicom, nameof(Connection.toDicom), error: true);
                }
            }
            catch (Exception e)
            {
                _logger.LogFullException(e, taskInfo);
            }
        }
コード例 #27
0
ファイル: Item.cs プロジェクト: 1059444127/RdmpDicom
 //TODO discuss construtor chaining with Thomas
 public Item(DicomCStoreRequest storeRequest) :  this(
         storeRequest.Dataset.GetSingleValue <string>(DicomTag.PatientID),
         storeRequest.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID),
         storeRequest.Dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID),
         storeRequest.Dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID)
         )
 {
 }
コード例 #28
0
        public DicomCStoreRequest CreateCStoreBySeriesUID(DicomFile dSet)
        {
            dSet.Dataset.AddOrUpdate(DicomTag.CommandField, (ushort)DicomCommandField.CMoveRequest);
            dSet.Dataset.AddOrUpdate(DicomTag.AffectedSOPClassUID, DicomUID.StudyRootQueryRetrieveInformationModelMOVE);
            var request = new DicomCStoreRequest(dSet);

            return(request);
        }
コード例 #29
0
        internal async Task <DicomResponse> OnCStoreRequestAsync(DicomCStoreRequest request)
        {
            if (OnCStoreRequest == null)
            {
                return(new DicomCStoreResponse(request, DicomStatus.StorageStorageOutOfResources));
            }

            return(await OnCStoreRequest(request).ConfigureAwait(false));
        }
コード例 #30
0
        public DicomCStoreResponse OnCStoreRequest(DicomCStoreRequest request)
        {
            var tempName = Path.GetTempFileName();

            Logger.Info(tempName);
            request.File.Save(tempName);

            return(new DicomCStoreResponse(request, DicomStatus.Success));
        }
コード例 #31
0
ファイル: DicomCStoreResponse.cs プロジェクト: GMZ/fo-dicom
 /// <summary>
 /// Initializes DICOM C-Store response to be returned to SCU.
 /// </summary>
 /// <param name="request">DICOM C-Store request being responded to</param>
 /// <param name="status">Status result of the C-Store operation</param>
 public DicomCStoreResponse(DicomCStoreRequest request, DicomStatus status)
     : base(request, status)
 {
 }