Esempio n. 1
0
        public void DicomClientSend_ToAcceptedAssociation_ShouldSendRequest()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <DicomClientTest.MockCEchoProvider>(port))
            {
                var locker = new object();

                var         expected = DicomStatus.Success;
                DicomStatus actual   = null;

                var client = new DicomClient();
                client.AddRequest(
                    new DicomCEchoRequest
                {
                    OnResponseReceived = (rq, rsp) =>
                    {
                        lock (locker) actual = rsp.Status;
                    }
                });
                client.Send("localhost", port, false, "SCU", "ANY-SCP");

                Assert.Equal(expected, actual);
            }
        }
Esempio n. 2
0
        public virtual IEnumerable <DicomCFindResponse> OnCFindRequest(DicomCFindRequest request)
        {
            DicomStatus               status = DicomStatus.Success;
            IList <DicomDataset>      queries;
            List <DicomCFindResponse> responses = new List <DicomCFindResponse>();

            if (OnZSCFindRequest != null)
            {
                //此处通过代理来返回在服务端本机进行的操作结果,也就是DICOM协议中说的匹配查询结果
                queries = OnZSCFindRequest(request);
                if (queries != null)
                {
                    Logger.Info("查询到{0}个数据", queries.Count);

                    foreach (var item in queries)
                    {
                        //对于每一个查询匹配的结果,都需要有一个单独的C-FIND-RSP消息来返回到请求端
                        //【注】:每次发送的状态都必须是Pending,表明后续还会继续发送查询结果
                        DicomCFindResponse rsp = new DicomCFindResponse(request, DicomStatus.Pending);
                        rsp.Dataset = item;
                        responses.Add(rsp);
                    }
                }
                else
                {
                    status = DicomStatus.QueryRetrieveOutOfResources;
                }
            }
            //随后需要发送查询结束的状态,即Success到C-FIND SCU端
            responses.Add(new DicomCFindResponse(request, DicomStatus.Success));

            //这里貌似是一起将多个response发送出去的?需要后续在研究一下DicomService中的实现代码
            //搞清楚具体的发送机制
            return(responses);
        }
Esempio n. 3
0
        public void DicomClientSend_ToRejectedAssociation_ShouldNotSendRequest()
        {
            var port = Ports.GetNext();

            using (DicomServer.Create <DicomClientTest.MockCEchoProvider>(port))
            {
                var         locker = new object();
                DicomStatus status = null;

                var client = new DicomClient();
                client.AddRequest(
                    new DicomCEchoRequest
                {
                    OnResponseReceived = (rq, rsp) =>
                    {
                        lock (locker) status = rsp.Status;
                    }
                });

                try
                {
                    client.Send("localhost", port, false, "SCU", "WRONG-SCP");
                }
                catch
                {
                }

                Assert.Null(status);
            }
        }
Esempio n. 4
0
        public async Task DicomClientSend_ToRejectedAssociation_ShouldNotSendRequest()
        {
            var port = Ports.GetNext();

            using (DicomServerFactory.Create <DicomClientTest.MockCEchoProvider>(port))
            {
                var         locker = new object();
                DicomStatus status = null;

                var client = DicomClientFactory.Create("localhost", port, false, "SCU", "WRONG-SCP");
                await client.AddRequestAsync(
                    new DicomCEchoRequest
                {
                    OnResponseReceived = (rq, rsp) =>
                    {
                        lock (locker) status = rsp.Status;
                    }
                }).ConfigureAwait(false);

                try
                {
                    await client.SendAsync().ConfigureAwait(false);
                }
                catch
                {
                }

                Assert.Null(status);
            }
        }
Esempio n. 5
0
        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);
            }
        }
        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);
            }
        }
Esempio n. 7
0
        public void Lookup_MaskedEntryExists_LooksUpCorrectValue()
        {
            var testStatus = DicomStatus.PrintManagementFilmBoxEmptyPage;
            var status     = DicomStatus.Lookup(testStatus.Code);

            Assert.True(status.Code == testStatus.Code);
        }
 /// <summary>
 /// Converts a dicom status to a Dicom operation result.
 /// </summary>
 /// <param name="status">The Dicom status.</param>
 /// <returns>The Dicom operation result.</returns>
 private static DicomOperationResult GetStatus(DicomStatus status)
 {
     // On any warning we still return success. Please check here for a list of warnings: https://fo-dicom.github.io/html/f270d490-66d6-28d5-1fa3-f619b4792034.htm
     return(status == DicomStatus.Success ||
            status == DicomStatus.StorageCoercionOfDataElements ||
            status == DicomStatus.StorageElementsDiscarded
         ? DicomOperationResult.Success : DicomOperationResult.Error);
 }
Esempio n. 9
0
        public void ErrorCommentIsThereForFailure()
        {
            var rsp = new DicomResponse(new DicomDataset());

            var failure = new DicomStatus("FF01", DicomState.Failure, "Failed", "Comment on the failure mode");

            rsp.Status = failure;

            Assert.True(rsp.Command.Contains(DicomTag.ErrorComment));
        }
Esempio n. 10
0
        public override void OnReceiveResponseMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, Macro.Dicom.DicomMessage message)
        {
            base.OnReceiveResponseMessage(client, association, presentationID, message);

            if (message.Status.Status == DicomState.Warning)
            {
                DicomStatus status = DicomStatuses.LookupQueryRetrieve(message.Status.Code);
                _errorDescriptionDetails = String.Format("Remote server returned a warning status ({0}: {1}).",
                                                         RemoteAE, status.Description);
            }
        }
Esempio n. 11
0
        public void Lookup_WithWarning_ReturnsCorrectStatusClass()
        {
            var statusTest = DicomStatus.Lookup(_stateUPSIsAlreadyCompleted.Code);

            // Code B306 is not in the known list. So the DicomStatus.Lookup shall return
            // the original code, but a status and Description that matches best one of
            // the known states.
            Assert.Equal(_stateUPSIsAlreadyCompleted.State, statusTest.State);
            Assert.Equal(_stateUPSIsAlreadyCompleted.Code, statusTest.Code);
            Assert.NotEqual(_stateUPSIsAlreadyCompleted.Description, statusTest.Description);
        }
        /// <summary>
        /// Returns a user-friendly error message for a specified DICOM error
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public static string TranslateError(DicomStatus status)
        {
            if (status == DicomStatuses.Success) // don't translate this
            {
                return(null);
            }

            if (status == DicomStatuses.QueryRetrieveMoveDestinationUnknown)
            {
                return(SR.DicomError_QRMoveDestinationUnknown);
            }

            return(status.Description);
        }
Esempio n. 13
0
        private DicomNDeleteResponse DeleteFilmBox(DicomNDeleteRequest request)
        {
            if (_filmSession == null)
            {
                Logger.Error("Can't delete a basic film session doesnot exist for this association {0}", CallingAE);
                return(new DicomNDeleteResponse(request, DicomStatus.NoSuchObjectInstance));
            }

            DicomStatus status =
                _filmSession.DeleteFilmBox(request.SOPInstanceUID)
                ? DicomStatus.Success
                : DicomStatus.NoSuchObjectInstance;
            var response = new DicomNDeleteResponse(request, status);

            return(response);
        }
        public void StatusSetter_ChangesFromStatusWithCommentToWithout_UpdatesErrorComment()
        {
            var           comment = "This is a comment";
            DicomResponse x       = new DicomNActionResponse(new DicomDataset());
            var           status  = new DicomStatus(
                "C303",
                DicomState.Failure,
                "Refused: The UPS may only become SCHEDULED via N-CREATE, not N-SET or N-ACTION",
                comment);

            x.Status = status;
            Assert.Equal(x.Command.GetString(DicomTag.ErrorComment), comment);

            x.Status = DicomStatus.Success;
            Assert.False(x.Command.Contains(DicomTag.ErrorComment));
        }
Esempio n. 15
0
        public IEnumerable <DicomCFindResponse> OnCFindRequest(DicomCFindRequest request)
        {
            DicomStatus status  = DicomStatus.Success;
            var         queries = GetPatients();

            foreach (var item in queries)
            {
                DicomCFindResponse rs = new DicomCFindResponse(request, DicomStatus.Pending);
                rs.Dataset = item;
                yield return(rs);
            }
            DicomCFindResponse rs2 = new DicomCFindResponse(request, DicomStatus.Success);

            rs2.Dataset = queries.LastOrDefault();
            yield return(rs2);
        }
Esempio n. 16
0
 public void AddKnownDicomStatuses_WithFailure_IsLookedupCorrectly()
 {
     try
     {
         DicomStatus.AddKnownDicomStatuses(new[] { _stateUPSIsAlreadyCompleted, _stateSOPInstanceDoesNotExist });
         var upsCompleteTest = DicomStatus.Lookup(_stateUPSIsAlreadyCompleted.Code);
         Assert.Equal(_stateUPSIsAlreadyCompleted, upsCompleteTest);
         Assert.Equal(_stateUPSIsAlreadyCompleted.Code, upsCompleteTest.Code);
         Assert.Equal(_stateUPSIsAlreadyCompleted.Description, upsCompleteTest.Description);
         var sopDoesNotExistTest = DicomStatus.Lookup(_stateUPSIsAlreadyCompleted.Code);
         Assert.Equal(_stateUPSIsAlreadyCompleted, sopDoesNotExistTest);
         Assert.Equal(_stateUPSIsAlreadyCompleted.Code, sopDoesNotExistTest.Code);
         Assert.Equal(_stateUPSIsAlreadyCompleted.Description, sopDoesNotExistTest.Description);
     }
     finally
     {
         DicomStatus.ResetEntries();
     }
 }
Esempio n. 17
0
        /// <summary>
        /// Fail the remaining SOP Instances for sending.
        /// </summary>
        private void FailRemaining(DicomStatus status)
        {
            while (_fileListIndex < _storageInstanceList.Count)
            {
                StorageInstance fileToSend = _storageInstanceList[_fileListIndex];

                OnImageStoreStarted(fileToSend);

                fileToSend.SendStatus = status;

                _failureSubOperations++;
                _remainingSubOperations--;

                fileToSend.ExtendedFailureDescription = "The association was aborted.";

                OnImageStoreCompleted(fileToSend);

                _fileListIndex++;
            }
        }
Esempio n. 18
0
        public async Task Send_LoopbackListenerKnownSOPClass_SendSucceeds()
        {
            var port = Ports.GetNext();

            using (DicomServerFactory.Create <SimpleCStoreProvider>(NetworkManager.IPv4Loopback, port, logger: _logger.IncludePrefix("DicomServer")))
            {
                DicomStatus status  = null;
                var         request = new DicomCStoreRequest(TestData.Resolve("CT-MONO2-16-ankle"))
                {
                    OnResponseReceived = (req, res) => status = res.Status
                };

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

                await client.SendAsync();

                Assert.Equal(DicomStatus.Success, status);
            }
        }
Esempio n. 19
0
        private void LogError(StorageInstance instance, DicomMessage msg, DicomStatus dicomStatus)
        {
            if (dicomStatus == DicomStatuses.SOPClassNotSupported)
            {
                var log = new StringBuilder();

                log.AppendLine(string.Format("Unable to transfer SOP {0} in study {1}. Remote device does not accept {2} in {3} transfer syntax",
                                             instance.SopInstanceUid, instance.StudyInstanceUid, msg.SopClass, msg.TransferSyntax));

                if (instance.TransferSyntax.Encapsulated)
                {
                    var codecExists = DicomCodecRegistry.GetCodec(instance.TransferSyntax) != null;

                    log.AppendLine(codecExists
                                       ? string.Format("Note: codec is available for {0} but remote device does not support it?", instance.TransferSyntax)
                                       : string.Format("Note: codec is NOT available for {0}", instance.TransferSyntax));
                }

                Platform.Log(LogLevel.Error, log.ToString());
            }
        }
Esempio n. 20
0
        public static ProgressEventType ToProgressEventType(this DicomStatus status)
        {
            switch (status.State)
            {
            case DicomState.Success:
                return(ProgressEventType.Information);

            case DicomState.Cancel:
                return(ProgressEventType.Warning);

            case DicomState.Pending:
                return(ProgressEventType.Information);

            case DicomState.Warning:
                return(ProgressEventType.Warning);

            case DicomState.Failure:
                return(ProgressEventType.Error);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 21
0
 private void SendBufferedResponses(DicomServer server, byte presentationId, DicomMessage requestMessage, DicomStatus pendingStatus)
 {
     while (_responseQueue.Count > 0)
     {
         DicomMessage response = _responseQueue.Dequeue();
         _sessionDebug._responses.Add(response.Dump());
         server.SendCFindResponse(presentationId, requestMessage.MessageId, response,
                                  pendingStatus);
         Platform.Log(LogLevel.Info, "Sending a Worklist Response ");
         if (_cancelReceived)
         {
             throw new DicomException("DICOM C-Cancel Received");
         }
     }
 }
Esempio n. 22
0
        public virtual IEnumerable <DicomCMoveResponse> OnCMoveRequest(DicomCMoveRequest request)
        {
            DicomStatus status             = DicomStatus.Success;
            IList <DicomCMoveResponse> rsp = new List <DicomCMoveResponse>();
            /*----to do------*/
            //添加查询数据库的代码,即根据request的条件提取指定的图像
            //然后将图像信息添加到rsp响应中

            //创建C-STORE-SCU,发起C-STORE-RQ
            IList <DicomDataset> queries;
            DicomClient          clt = new DicomClient();

            if (OnZSCMoveRequest != null)
            {
                queries = OnZSCMoveRequest(request);
                if (queries != null)
                {
                    Logger.Info("需要发送{0}个数据", queries.Count);
                    int len = queries.Count;
                    int cnt = 0;
                    foreach (var item in queries)
                    {
                        //zssure:
                        //取巧的方法直接利用request来构造response中相同的部分
                        //这部分与mDCM方式很不同
                        var studyUid = item.Get <string>(DicomTag.StudyInstanceUID);
                        var instUid  = item.Get <string>(DicomTag.SOPInstanceUID);
                        //需要在c:\cmovetest目录下手动添加C-MOVE SCU请求的图像
                        //本地构造的目录结构为,
                        //      c:\cmovetest\12\0.dcm
                        //      c:\cmovetest\12\1.dcm
                        //      c:\cmovetest\12\2.dcm
                        var path = Path.GetFullPath(@"c:\cmovetest");

                        try
                        {
                            path = Path.Combine(path, studyUid);
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            path = Path.Combine(path, instUid) + ".dcm";
                            DicomCStoreRequest cstorerq = new DicomCStoreRequest(path);
                            cstorerq.OnResponseReceived = (rq, rs) =>
                            {
                                if (rs.Status != DicomStatus.Pending)
                                {
                                }
                                if (rs.Status == DicomStatus.Success)
                                {
                                    DicomCMoveResponse rsponse = new DicomCMoveResponse(request, DicomStatus.Pending);
                                    rsponse.Remaining = --len;
                                    rsponse.Completed = ++cnt;
                                    rsponse.Warnings  = 0;
                                    rsponse.Failures  = 0;
                                    //zssure:2014-12-24
                                    //修复发送C-MOVE-RSP的逻辑错误
                                    SendResponse(rsponse);
                                    //rsp.Add(rsponse);
                                    //zssure:end
                                }
                            };
                            clt.AddRequest(cstorerq);
                            //注意:这里给出的IP地址与C-MOVE请求的IP地址相同,意思就是说C-MOVE SCP需要向C-MOVE SCU发送C-STORE-RQ请求
                            //将查询到的图像返回给C-MOVE SCU
                            //所以四尺C-STORE-RQ中的IP地址与C-MOVE SCU相同,但是端口不同,因为同一个端口不能被绑定多次。
                            clt.Send("127.0.0.1", 22345, false, this.Association.CalledAE, request.DestinationAE);
                        }
                        catch (System.Exception ex)
                        {
                            DicomCMoveResponse rs = new DicomCMoveResponse(request, DicomStatus.StorageStorageOutOfResources);
                            rsp.Add(rs);
                            return(rsp);
                        }
                    }
                    //zssure:
                    //发送完成后统一返回C-MOVE RESPONSE
                    //貌似响应流程有问题,有待进一步核实
                    //注意,如果最后为发送DicomStatus.Success消息,TCP连接不会释放,浪费资源
                    rsp.Add(new DicomCMoveResponse(request, DicomStatus.Success));
                    return(rsp);
                }
                else
                {
                    rsp.Add(new DicomCMoveResponse(request, DicomStatus.NoSuchObjectInstance));
                    return(rsp);
                }
            }
            rsp.Add(new DicomCMoveResponse(request, DicomStatus.NoSuchObjectInstance));
            return(rsp);
        }
Esempio n. 23
0
 /// <summary>
 /// Called when received response message.  Sets the <see cref="Results"/> property as appropriate.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="association">The association.</param>
 /// <param name="presentationID">The presentation ID.</param>
 /// <param name="message">The message.</param>
 public override void OnReceiveResponseMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
 {
     if (message.Status.Status == DicomState.Pending)
     {
         // one result sent back, add to result list
         _results.Add(message.DataSet);
         if (_maxResults != -1 && !_cancelSent && _results.Count > _maxResults)
         {
             client.SendCFindCancelRequest(presentationID, message.MessageIdBeingRespondedTo);
             _cancelSent = true;
         }
     }
     else
     {
         _cancelSent = false;
         DicomStatus status = DicomStatuses.LookupQueryRetrieve(message.Status.Code);
         if (status.Status != DicomState.Success)
         {
             if (status.Status == DicomState.Cancel)
             {
                 if (LogInformation)
                 {
                     Platform.Log(LogLevel.Info, "Cancel status received in Find Scu: {0}", status);
                 }
                 Status = ScuOperationStatus.Canceled;
             }
             else if (status.Status == DicomState.Failure)
             {
                 Platform.Log(LogLevel.Error, "Failure status received in Find Scu: {0}", status);
                 Status             = ScuOperationStatus.Failed;
                 FailureDescription = status.ToString();
             }
             else if (status.Status == DicomState.Warning)
             {
                 Platform.Log(LogLevel.Warn, "Warning status received in Find Scu: {0}", status);
             }
             else if (Status == ScuOperationStatus.Canceled)
             {
                 if (LogInformation)
                 {
                     Platform.Log(LogLevel.Info, "Client cancelled Find Scu operation.");
                 }
             }
         }
         else
         {
             if (LogInformation)
             {
                 Platform.Log(LogLevel.Info, "Success status received in Find Scu!");
             }
         }
         if (!ReuseAssociation)
         {
             client.SendReleaseRequest();
             StopRunningOperation();
         }
         else
         {
             ProgressEvent.Set();
         }
     }
 }
Esempio n. 24
0
 public DicomCEchoResponse(DicomCEchoRequest request, DicomStatus status)
     : base(request, status)
 {
 }
Esempio n. 25
0

        
Esempio n. 26
0
		/// <summary>
		/// Fail the remaining SOP Instances for sending.
		/// </summary>
		private void FailRemaining(DicomStatus status)
		{

			while (_fileListIndex < _storageInstanceList.Count)
			{
				StorageInstance fileToSend = _storageInstanceList[_fileListIndex];

				OnImageStoreStarted(fileToSend);

				fileToSend.SendStatus = status;

				_failureSubOperations++;
				_remainingSubOperations--;

				fileToSend.ExtendedFailureDescription = "The association was aborted.";

				OnImageStoreCompleted(fileToSend);

				_fileListIndex++;
			}
		}
Esempio n. 27
0
        /// <summary>
        /// Called when received response message.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        /// <param name="presentationID">The presentation ID.</param>
        /// <param name="message">The message.</param>
        public override void OnReceiveResponseMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
        {
            // Discovered issue with an SCP that was not setting these values on the final Success return, so blocking an update of the values if all of them are 0.
            if (message.NumberOfFailedSubOperations != 0 ||
                message.NumberOfCompletedSubOperations != 0 ||
                message.NumberOfRemainingSubOperations != 0 ||
                message.NumberOfWarningSubOperations != 0)
            {
                _failureSubOperations   = message.NumberOfFailedSubOperations;
                _successSubOperations   = message.NumberOfCompletedSubOperations;
                _remainingSubOperations = message.NumberOfRemainingSubOperations;
                _warningSubOperations   = message.NumberOfWarningSubOperations;
                _totalSubOperations     = _failureSubOperations + _successSubOperations + _remainingSubOperations +
                                          _warningSubOperations;
            }

            if (!string.IsNullOrEmpty(message.ErrorComment))
            {
                FailureDescription = message.ErrorComment;
            }

            if (message.Status.Status == DicomState.Pending)
            {
                OnImageMoveCompleted();
            }
            else
            {
                DicomStatus status = DicomStatuses.LookupQueryRetrieve(message.Status.Code);
                if (message.Status.Status != DicomState.Success)
                {
                    if (status.Status == DicomState.Cancel)
                    {
                        if (LogInformation)
                        {
                            Platform.Log(LogLevel.Info, "Cancel status received in Move Scu: {0}", status);
                        }
                        Status = ScuOperationStatus.Canceled;
                    }
                    else if (status.Status == DicomState.Failure)
                    {
                        Platform.Log(LogLevel.Error, "Failure status received in Move Scu: {0}", status);
                        Status             = ScuOperationStatus.Failed;
                        FailureDescription = status.ToString();
                    }
                    else if (status.Status == DicomState.Warning)
                    {
                        Platform.Log(LogLevel.Warn, "Warning status received in Move Scu: {0}", status);
                    }
                    else if (Status == ScuOperationStatus.Canceled)
                    {
                        if (LogInformation)
                        {
                            Platform.Log(LogLevel.Info, "Client cancelled Move Scu operation.");
                        }
                    }
                }
                else
                {
                    if (LogInformation)
                    {
                        Platform.Log(LogLevel.Info, "Success status received in Move Scu!");
                    }
                }

                client.SendReleaseRequest();
                StopRunningOperation();
            }
        }
Esempio n. 28
0
 /// <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)
 {
 }
Esempio n. 29
0
        private void LogError(StorageInstance instance, DicomMessage msg, DicomStatus dicomStatus)
        {
            if (dicomStatus == DicomStatuses.SOPClassNotSupported)
            {
                var log = new StringBuilder();

                log.AppendLine(string.Format("Unable to transfer SOP {0} in study {1}. Remote device does not accept {2} in {3} transfer syntax", 
                                instance.SopInstanceUid, instance.StudyInstanceUid, msg.SopClass, msg.TransferSyntax));

                if (instance.TransferSyntax.Encapsulated)
                {
                    var codecExists = DicomCodecRegistry.GetCodec(instance.TransferSyntax) != null;

                    log.AppendLine(codecExists
                                       ? string.Format("Note: codec is available for {0} but remote device does not support it?", instance.TransferSyntax)
                                       : string.Format("Note: codec is NOT available for {0}", instance.TransferSyntax));
                }

                Platform.Log(LogLevel.Error, log.ToString());        
            }
        }
Esempio n. 30
0
 public DicomNGetResponse(DicomNGetRequest request, DicomStatus status)
     : base(request, status)
 {
     SOPInstanceUID = request.SOPInstanceUID;
 }
Esempio n. 31
0
 public DicomNCreateResponse(DicomNCreateRequest request, DicomStatus status)
     : base(request, status)
 {
 }
Esempio n. 32
0
 public void SetError(DicomStatus status, String message)
 {
     Successful   = false;
     DicomStatus  = status;
     ErrorMessage = message;
 }
Esempio n. 33
0
 public DicomNCreateResponse(DicomNCreateRequest request, DicomStatus status)
     : base(request, status)
 {
 }
Esempio n. 34
0
 /// <summary>
 /// Initializes an instance of the <see cref="DicomNSetResponse"/> class.
 /// </summary>
 /// <param name="request">Associated N-SET request.</param>
 /// <param name="status">Response status.</param>
 public DicomNSetResponse(DicomNSetRequest request, DicomStatus status)
     : base(request, status)
 {
     SOPInstanceUID = request.SOPInstanceUID;
 }
Esempio n. 35
0
        private void OnReceiveMWLQuery(DicomServer server, byte presentationID, DicomMessage message)
        {
            #region Non conformance checking    - Unsopported Optional matching key checking

            if (CheckForMissingRequiredMatchingKey(server, presentationID, message))
            {
                return; //this mean sending failure message response.
            }
            DicomStatus pendingStatus = DicomStatuses.Pending;

            bool optionalMatchingKeyPresentButNotSupported =
                CheckForUnSupportedOptionalMatchingKey(server, presentationID, message, false);

            if (optionalMatchingKeyPresentButNotSupported)
            {
                pendingStatus = DicomStatuses.QueryRetrieveOptionalKeysNotSupported;
            }
            #endregion

            List <uint> tagList = new List <uint>();

            string sqlWhereClause = " where 1=1 ";

            DicomAttributeCollection data = message.DataSet;

            string specificCharacterSet = "";

            foreach (DicomAttribute attrib in message.DataSet)
            {
                tagList.Add(attrib.Tag.TagValue);

                if (!attrib.IsNull)
                {
                    switch (attrib.Tag.TagValue)
                    {
                    case DicomTags.SpecificCharacterSet:
                        specificCharacterSet = data[DicomTags.SpecificCharacterSet].GetString(0, string.Empty);
                        break;

                        #region Case Scheduled procedure Step Seq
                    case DicomTags.ScheduledProcedureStepSequence:
                        DicomAttributeSQ  sequence         = attrib as DicomAttributeSQ;
                        DicomSequenceItem sequenceSubItems = sequence[0];
                        foreach (DicomAttribute seqAttrib in sequenceSubItems)
                        {
                            if (seqAttrib.IsNull)
                            {
                                continue;
                            }

                            tagList.Add(seqAttrib.Tag.TagValue);
                            switch (seqAttrib.Tag.TagValue)
                            {
                            // Required matching keys in ScheduledProcedureStepSequence
                            case DicomTags.ScheduledStationName:
                                SetStringCondition(ref sqlWhereClause, "ScheduledAET",
                                                   sequenceSubItems[DicomTags.ScheduledStationName].GetString(0, string.Empty));
                                break;

                            case DicomTags.Modality:
                                SetStringCondition(ref sqlWhereClause, "Modality",
                                                   sequenceSubItems[DicomTags.Modality].GetString(0, string.Empty));
                                break;

                            case DicomTags.ScheduledPerformingPhysiciansName:
                                SetStringCondition(ref sqlWhereClause, "PerformingPhysician",
                                                   sequenceSubItems[DicomTags.ScheduledPerformingPhysiciansName].GetString(0, string.Empty));
                                break;

                            case DicomTags.ScheduledProcedureStepStartDate:
                                SetDateRangeCondition(ref sqlWhereClause, "ExamScheduledDateAndTime",
                                                      sequenceSubItems[DicomTags.ScheduledProcedureStepStartDate].GetString(0, string.Empty));
                                break;

                            case DicomTags.ScheduledProcedureStepStartTime:
                                SetTimeRangeCondition(ref sqlWhereClause, "ExamScheduledDateAndTime",
                                                      sequenceSubItems[DicomTags.ScheduledProcedureStepStartTime].GetString(0, string.Empty));
                                break;

                            // Optional matching keys
                            case DicomTags.ScheduledProcedureStepLocation:
                                SetStringCondition(ref sqlWhereClause, "ExamRoom",
                                                   sequenceSubItems[DicomTags.ScheduledProcedureStepLocation].GetString(0, string.Empty));
                                break;

                            case DicomTags.ScheduledProcedureStepDescription:
                                SetStringCondition(ref sqlWhereClause, "ExamDescription",
                                                   sequenceSubItems[DicomTags.ScheduledProcedureStepDescription].GetString(0, string.Empty));
                                break;

                            case DicomTags.RequestedProcedureId:
                                SetInt32Condition(ref sqlWhereClause, "ProcedureID",
                                                  sequenceSubItems[DicomTags.RequestedProcedureId].GetString(0, string.Empty));
                                break;

                            case DicomTags.ScheduledProcedureStepId:
                                SetInt32Condition(ref sqlWhereClause, "ProcedureStepID",
                                                  sequenceSubItems[DicomTags.ScheduledProcedureStepId].GetString(0, string.Empty));
                                break;

                            default:
                                break;
                            }
                        }
                        break;
                        #endregion

                    case DicomTags.PatientId:
                        SetInt32Condition(ref sqlWhereClause, "PatientID",
                                          data[DicomTags.PatientId].GetString(0, string.Empty));
                        break;

                    case DicomTags.PatientsName:
                        SetStringCondition(ref sqlWhereClause, "FullName",
                                           data[DicomTags.PatientsName].GetString(0, string.Empty));
                        break;

                    // Optional matching keys
                    case DicomTags.AccessionNumber:
                        SetInt32Condition(ref sqlWhereClause, "AccessionNumber",
                                          data[DicomTags.AccessionNumber].GetString(0, string.Empty));
                        break;

                    case DicomTags.ReferringPhysiciansName:
                        SetStringCondition(ref sqlWhereClause, "ReferringPhysician",
                                           data[DicomTags.ReferringPhysiciansName].GetString(0, string.Empty));
                        break;

                    default:
                        break;
                    }
                }
            }

            int resultCount = 0;
            try
            {
                _sessionDebug._searchCriteriaDumpString = sqlWhereClause;
                List <ExamsScheduled> list = DBBroker.ExamsScheduled.GetWorkList(sqlWhereClause);
                foreach (ExamsScheduled row in list)
                {
                    if (_cancelReceived)
                    {
                        throw new DicomException("DICOM C-Cancel Received");
                    }

                    resultCount++;
                    if (_maxQueryResponses != -1 &&
                        _maxQueryResponses < resultCount)
                    {
                        SendBufferedResponses(server, presentationID, message, pendingStatus);
                        throw new DicomException("Maximum Configured Query Responses Exceeded: " + resultCount);
                    }

                    DicomMessage response = new DicomMessage();
                    PopulateResponse(response, tagList, row, specificCharacterSet);
                    _responseQueue.Enqueue(response);

                    if (_responseQueue.Count >= _bufferedQueryResponses)
                    {
                        SendBufferedResponses(server, presentationID, message, pendingStatus);
                    }
                }

                SendBufferedResponses(server, presentationID, message, pendingStatus);
                Platform.Log(LogLevel.Info, "All Worklist have been sent successfully.");
            }
            catch (Exception e)
            {
                if (_cancelReceived)
                {
                    DicomMessage errorResponse = new DicomMessage();
                    server.SendCFindResponse(presentationID, message.MessageId, errorResponse,
                                             DicomStatuses.Cancel);
                }
                else if (_maxQueryResponses != -1 &&
                         _maxQueryResponses < resultCount)
                {
                    Platform.Log(LogLevel.Warn, "Maximum Configured Query Responses Exceeded: {0} on query from {1}", resultCount, server.AssociationParams.CallingAE);
                    DicomMessage errorResponse = new DicomMessage();
                    server.SendCFindResponse(presentationID, message.MessageId, errorResponse,
                                             DicomStatuses.QueryRetrieveOutOfResources);
                }
                else
                {
                    Platform.Log(LogLevel.Error, e, "Unexpected exception when processing FIND request.");
                    DicomMessage errorResponse = new DicomMessage();
                    server.SendCFindResponse(presentationID, message.MessageId, errorResponse,
                                             DicomStatuses.QueryRetrieveUnableToProcess);
                }
                return;
            }


            DicomMessage finalResponse = new DicomMessage();
            server.SendCFindResponse(presentationID, message.MessageId, finalResponse, DicomStatuses.Success);
            return;
        }