Exemple #1
0
        /// <summary>
        /// Generic routine to send the next C-STORE-RQ message in the _fileList.
        /// </summary>
        /// <param name="client">DICOM Client class</param>
        /// <param name="association">Association Parameters</param>
        public bool SendCStore(DicomClient client, ClientAssociationParameters association)
        {
            FileToSend fileToSend = _fileList[_fileListIndex];

            DicomFile dicomFile = new DicomFile(fileToSend.filename);

            try
            {
                dicomFile.Load(DicomReadOptions.Default);
            }
            catch (DicomException e)
            {
                Logger.LogErrorException(e, "Unexpected exception when loading DICOM file {0}", fileToSend.filename);

                return(false);
            }

            DicomMessage msg = new DicomMessage(dicomFile);

            byte pcid = association.FindAbstractSyntaxWithTransferSyntax(fileToSend.sopClass, dicomFile.TransferSyntax);

            if (pcid == 0)
            {
                Logger.LogError(
                    "Unable to find matching negotiated presentation context for sop {0} and syntax {1}",
                    dicomFile.SopClass.Name, dicomFile.TransferSyntax.Name);
                return(false);
            }
            client.SendCStoreRequest(pcid, client.NextMessageID(), DicomPriority.Medium, msg);
            return(true);
        }
Exemple #2
0
        /// <summary>
        /// Called when [network error].
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        /// <param name="e">The e.  Note, e can be null in some instances.</param>
        public void OnNetworkError(DicomClient client, ClientAssociationParameters association, Exception e)
        {
            //TODO: right now this method gets called in timeout and abort situations.  Should add
            // the appropriate methods to the IDicomClientHandler to address this.

            //We don't want to blow away other failure descriptions (e.g. the OnDimseTimeout one).
            if (Status == ScuOperationStatus.Running)
            {
                FailureDescription = String.Format("Unexpected network error: {0}", e == null ? "Unknown" : e.Message);
            }

            if (client.State == DicomAssociationState.Sta13_AwaitingTransportConnectionClose)
            {
                //When this state is set and an error occurs, an appropriate message has already been logged in the client.
            }
            else
            {
                LogAdapter.Logger.Warning(FailureDescription);
            }

            //We don't want to blow away the OnDimseTimeout 'TimeoutExpired' status.
            ScuOperationStatus stopStatus = Status;

            if (stopStatus == ScuOperationStatus.Running)
            {
                stopStatus = ScuOperationStatus.NetworkError;
            }

            ResultStatus = DicomState.Failure;

            StopRunningOperation(stopStatus);
        }
Exemple #3
0
        public void BeginTransferringDicomInstancesAuditTest()
        {
            AssociationParameters parms = new ClientAssociationParameters("CLIENT", "SERVER",
                                                                          new IPEndPoint(new IPAddress(new byte[] { 2, 2, 2, 2 }),
                                                                                         2));

            parms.LocalEndPoint = new IPEndPoint(new IPAddress(new byte[] { 1, 1, 1, 1 }),
                                                 1);


            BeginTransferringDicomInstancesAuditHelper helper =
                new BeginTransferringDicomInstancesAuditHelper(
                    new DicomAuditSource("testApp", "Site", AuditSourceTypeCodeEnum.ApplicationServerProcessTierInMultiTierSystem),
                    EventIdentificationContentsEventOutcomeIndicator.Success,
                    parms, new AuditPatientParticipantObject("id1234", "Test Patient"));

            DicomAttributeCollection collection = new DicomAttributeCollection();

            SetupMR(collection);
            helper.AddStorageInstance(new StorageInstance(new DicomMessage(new DicomAttributeCollection(), collection)));

            string output = helper.Serialize(true);

            Assert.IsNotEmpty(output);

            Assert.Ignore("Skipping schema validation due to schema bug #9455");
            Exception exception;

            if (!helper.Verify(out exception))
            {
                throw exception;
            }
        }
 private void SendSetImageBoxRequest(DicomClient client, ClientAssociationParameters association, DicomMessage responseMessage)
 {
     if (this._currentImageBoxIndex >= this._imageBoxPixelModuleIods.Count)
     {
         this._nextRequestType = RequestType.PrintAction;
         this.SendActionPrintRequest(client, association, responseMessage);
     }
     else
     {
         if (this._currentImageBoxIndex == 0)
         {
             this._firstFilmBoxResponseMessage = responseMessage.DataSet;
             this._imageBoxUid = responseMessage.AffectedSopInstanceUid;
         }
         BasicFilmBoxModuleIod iod = new BasicFilmBoxModuleIod(this._firstFilmBoxResponseMessage);
         if (this._currentImageBoxIndex > iod.ReferencedImageBoxSequenceList.Count)
         {
             throw new DicomException("Current Image Box Index is greater than number of Referenced ImageBox Sequences - set image box data");
         }
         ImageBoxPixelModuleIod iod2    = this._imageBoxPixelModuleIods[this._currentImageBoxIndex];
         DicomMessage           message = new DicomMessage(null, iod2.DicomAttributeCollection)
         {
             RequestedSopClassUid    = SopClass.BasicGrayscaleImageBoxSopClassUid,
             RequestedSopInstanceUid = iod.ReferencedImageBoxSequenceList[this._currentImageBoxIndex].ReferencedSopInstanceUid
         };
         byte presentationID = association.FindAbstractSyntax(SopClass.BasicGrayscalePrintManagementMetaSopClass);
         this._currentImageBoxIndex++;
         client.SendNSetRequest(presentationID, client.NextMessageID(), message);
     }
 }
        private void SendSetImageBoxRequest(DicomClient client, ClientAssociationParameters association)
        {
            if (_currentImageBoxIndex >= _imageBoxPixelModuleIods.Count)
            {
                // done sending images box - send print request
                _nextRequestType = RequestType.PrintAction;
                SendActionPrintRequest(client, association);
            }
            else
            {
                // want to get first film box response - although not sure if CC is using .net 3.5.. prolly not so do it old way
                IEnumerator <DicomAttributeCollection> filmBoxResponseEnumerator = _filmBoxResponseMessages.Values.GetEnumerator();
                filmBoxResponseEnumerator.Reset();
                filmBoxResponseEnumerator.MoveNext();

                BasicFilmBoxModuleIod basicFilmBoxModuleIod = new BasicFilmBoxModuleIod(filmBoxResponseEnumerator.Current);

                if (_currentImageBoxIndex > basicFilmBoxModuleIod.ReferencedImageBoxSequenceList.Count)
                {
                    throw new DicomException("Current Image Box Index is greater than number of Referenced ImageBox Sequences - set image box data");
                }

                ImageBoxPixelModuleIod imageBoxPixelModuleIod = _imageBoxPixelModuleIods[_currentImageBoxIndex];

                DicomMessage newRequestMessage = new DicomMessage(null, (DicomAttributeCollection)imageBoxPixelModuleIod.DicomAttributeProvider);
                newRequestMessage.RequestedSopClassUid    = SopClass.BasicGrayscaleImageBoxSopClassUid;
                newRequestMessage.RequestedSopInstanceUid = basicFilmBoxModuleIod.ReferencedImageBoxSequenceList[_currentImageBoxIndex].ReferencedSopInstanceUid;

                byte pcid = association.FindAbstractSyntax(SopClass.BasicGrayscalePrintManagementMetaSopClass);

                _currentImageBoxIndex++;
                client.SendNSetRequest(pcid, client.NextMessageID(), newRequestMessage);
            }
        }
Exemple #6
0
        public void BeginTransferringDicomInstancesAuditTest()
        {
            AssociationParameters parms = new ClientAssociationParameters("CLIENT", "SERVER",
                                                                          new IPEndPoint(new IPAddress(new byte[] { 2, 2, 2, 2 }),
                                                                                         2));

            parms.LocalEndPoint = new IPEndPoint(new IPAddress(new byte[] { 1, 1, 1, 1 }),
                                                 1);


            BeginTransferringDicomInstancesAuditHelper helper =
                new BeginTransferringDicomInstancesAuditHelper(
                    new DicomAuditSource("testApp", "Site", AuditSourceTypeCodeEnum.ApplicationServerProcessTierInMultiTierSystem),
                    EventIdentificationTypeEventOutcomeIndicator.Success,
                    parms, new AuditPatientParticipantObject("id1234", "Test Patient"));

            DicomAttributeCollection collection = new DicomAttributeCollection();

            SetupMR(collection);
            helper.AddStorageInstance(new StorageInstance(new DicomMessage(new DicomAttributeCollection(), collection)));

            string output = helper.Serialize(true);

            Assert.IsNotEmpty(output);

            string failure;
            bool   result = helper.Verify(out failure);

            Assert.IsTrue(result, failure);
        }
Exemple #7
0
 /// <summary>
 ///     Called when [receive abort].
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="association">The association.</param>
 /// <param name="source">The source.</param>
 /// <param name="reason">The reason.</param>
 public void OnReceiveAbort(DicomClient client, ClientAssociationParameters association, DicomAbortSource source,
                            DicomAbortReason reason)
 {
     FailureDescription = string.Format("Unexpected association abort received from {0} to {1}",
                                        association.CallingAE, association.CalledAE);
     LogAdapter.Logger.Warn(FailureDescription);
     StopRunningOperation(ScuOperationStatus.UnexpectedMessage);
 }
Exemple #8
0
 /// <summary>
 /// Called when [receive release response].
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="association">The association.</param>
 public void OnReceiveReleaseResponse(DicomClient client, ClientAssociationParameters association)
 {
     if (LogInformation)
     {
         LogAdapter.Logger.InfoWithFormat("Association released from {0} to {1}", association.CallingAE, association.CalledAE);
     }
     StopRunningOperation();
 }
        private void SendCreateFilmSessionRequest(DicomClient client, ClientAssociationParameters association)
        {
            DicomMessage message        = new DicomMessage(null, this._basicFilmSessionModuleIod.DicomAttributeCollection);
            byte         presentationID = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);

            this._nextRequestType = RequestType.FilmBox;
            client.SendNCreateRequest(null, presentationID, client.NextMessageID(), message, DicomUids.BasicFilmSession);
        }
Exemple #10
0
 /// <summary>
 /// Called when [receive release response].
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="association">The association.</param>
 public void OnReceiveReleaseResponse(DicomClient client, ClientAssociationParameters association)
 {
     if (LogInformation)
     {
         Platform.Log(LogLevel.Info, "Association released from {0} to {1}", association.CallingAE, association.CalledAE);
     }
     StopRunningOperation();
 }
Exemple #11
0
 public void OnReceiveReleaseResponse(DicomClient client, ClientAssociationParameters association)
 {
     if (OnQueryCompleted != null)
     {
         OnQueryCompleted();
         _dicomClient.Dispose();
     }
 }
Exemple #12
0
 /// <summary>
 /// Called when [receive associate reject].
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="association">The association.</param>
 /// <param name="result">The result.</param>
 /// <param name="source">The source.</param>
 /// <param name="reason">The reason.</param>
 public void OnReceiveAssociateReject(DicomClient client, ClientAssociationParameters association, DicomRejectResult result, DicomRejectSource source, DicomRejectReason reason)
 {
     FailureDescription =
         String.Format("Association Rejection when {0} connected to remote AE {1}:{2}", association.CallingAE,
                       association.CalledAE, association.RemoteEndPoint);
     LogAdapter.Logger.Warning(FailureDescription);
     StopRunningOperation(ScuOperationStatus.AssociationRejected);
 }
 public void OnNetworkError(DicomClient client, ClientAssociationParameters association, Exception e)
 {
     if (_verificationResult != VerificationResult.Canceled)
     {
         Logger.LogErrorException(e, "Unexpected network error");
         _verificationResult = VerificationResult.Failed;
     }
     ProgressEvent.Set();
 }
Exemple #14
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)
 {
     base.ResultStatus = message.Status.Status;
     if (message.Status.Status == DicomState.Success)
     {
         this._results = message.DataSet;
     }
     base.ReleaseConnection(client);
 }
        private void SendCreateFilmSessionRequest(DicomClient client, ClientAssociationParameters association)
        {
            DicomMessage newRequestMessage = new DicomMessage(null, (DicomAttributeCollection)_basicFilmSessionModuleIod.DicomAttributeProvider);

            byte pcid = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);

            _nextRequestType = RequestType.FilmBox;
            client.SendNCreateRequest(DicomUid.GenerateUid(), pcid, client.NextMessageID(), newRequestMessage, DicomUids.BasicFilmSession);
        }
Exemple #16
0
        /// <summary>
        /// Sends the find request.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        private void SendFindRequest(DicomClient client, ClientAssociationParameters association)
        {
            byte pcid = association.FindAbstractSyntax(FindSopClass);

            if (pcid > 0)
            {
                DicomMessage dicomMessage = new DicomMessage(new DicomAttributeCollection(), _requestAttributeCollection.Copy());
                client.SendCFindRequest(pcid, client.NextMessageID(), dicomMessage);
            }
        }
Exemple #17
0
 /// <summary>
 /// Called when received response message.  If there are more files to send, will send them here.
 /// </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 (Status == ScuOperationStatus.Canceled)
     {
         LogAdapter.Logger.Info("Cancel request received, releasing association from {0} to {1}", association.CallingAE, association.CalledAE);
         client.SendReleaseRequest();
         StopRunningOperation();
         return;
     }
 }
Exemple #18
0
        /// <summary>
        /// Called when received associate accept.  For StorageScu, we then attempt to send the first file.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
        {
            base.OnReceiveAssociateAccept(client, association);

            Platform.Log(LogLevel.Info, "Association Accepted:\r\n{0}", association.ToString());

            _fileListIndex = 0;

            SendCStoreUntilSuccess(client, association);
        }
Exemple #19
0
        /// <summary>
        /// Called when received associate accept.  For StorageScu, we then attempt to send the first file.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
        {
            base.OnReceiveAssociateAccept(client, association);

            LogAdapter.Logger.InfoWithFormat("Association Accepted:\r\n{0}", association.ToString());

            _fileListIndex = 0;

            SendCStoreUntilSuccess(client, association);
        }
Exemple #20
0
        /// <summary>
        /// Called when received response message.  If there are more files to send, will send them here.
        /// </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 (_storageInstanceList.Count > 0)
            {
                _storageInstanceList[_fileListIndex].SendStatus = message.Status;
                _storageInstanceList[_fileListIndex].ExtendedFailureDescription = message.ErrorComment;
            }

            if (message.Status.Status != DicomState.Success)
            {
                if (message.Status.Status == DicomState.Warning)
                {
                    _warningSubOperations++;
                    Platform.Log(LogLevel.Warn, "Warning status received in sending C-STORE to {0}: {1}",
                                 association.CalledAE, message.Status.Description);
                }
                else if (message.Status.Status == DicomState.Failure)
                {
                    _failureSubOperations++;
                    Platform.Log(LogLevel.Error, "Failure status received in sending C-STORE to {0}: {1}",
                                 association.CalledAE, message.Status.Description);
                }
            }
            else
            {
                _successSubOperations++;
            }

            _remainingSubOperations--;

            OnImageStoreCompleted(_storageInstanceList[_fileListIndex]);

            if (Status == ScuOperationStatus.Canceled || message.Status.Status == DicomState.Cancel)
            {
                FailRemaining(DicomStatuses.Cancel);
                Platform.Log(LogLevel.Info, "Cancel requested by {0}, releasing association from {1} to {2}",
                             (message.Status.Status == DicomState.Cancel) ? "remote host" : "client",
                             association.CallingAE, association.CalledAE);

                Status = ScuOperationStatus.Canceled;
                client.SendReleaseRequest();
                StopRunningOperation();
                return;
            }

            _fileListIndex++;
            if (_fileListIndex >= _storageInstanceList.Count)
            {
                Platform.Log(LogLevel.Info, "Completed sending {0} C-STORE-RQ messages, releasing association.", _storageInstanceList.Count);
                client.SendReleaseRequest();
                StopRunningOperation();
                return;
            }
            SendCStoreUntilSuccess(client, association);
        }
Exemple #21
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);
            }
        }
        private void SendDeleteFilmSessionRequest(DicomClient client, ClientAssociationParameters association)
        {
            DicomMessage newRequestMessage = new DicomMessage(null, null);

            newRequestMessage.RequestedSopInstanceUid = _filmSessionUid;
            newRequestMessage.RequestedSopClassUid    = SopClass.BasicFilmSessionSopClassUid;

            _nextRequestType = RequestType.Close;
            byte pcid = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);

            client.SendNDeleteRequest(pcid, client.NextMessageID(), newRequestMessage);
        }
Exemple #23
0
        /// <summary>
        /// Sends the find request.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        private static void SendRequest(DicomClient client, ClientAssociationParameters association)
        {
            DicomMessage newRequestMessage = new DicomMessage();

            PrinterModuleIod.SetCommonTags(newRequestMessage.DataSet);
            byte pcid = association.FindAbstractSyntax(SopClass.PrinterSopClass);

            if (pcid > 0)
            {
                client.SendNGetRequest(DicomUids.PrinterSOPInstance, pcid, client.NextMessageID(), newRequestMessage);
            }
        }
Exemple #24
0
 /// <summary>
 /// Called when received associate accept.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="association">The association.</param>
 public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
 {
     base.OnReceiveAssociateAccept(client, association);
     if (Canceled)
     {
         client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
     }
     else
     {
         SendRequest(client, association);
     }
 }
Exemple #25
0
        private byte SelectUncompressedPresentationContext(ClientAssociationParameters association, DicomMessage msg)
        {
            byte pcid = association.FindAbstractSyntaxWithTransferSyntax(msg.SopClass,
                                                                         TransferSyntax.ExplicitVrLittleEndian);

            if (pcid == 0)
            {
                pcid = association.FindAbstractSyntaxWithTransferSyntax(msg.SopClass,
                                                                        TransferSyntax.ImplicitVrLittleEndian);
            }
            return(pcid);
        }
        public override void OnReceiveResponseMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
        {
            try
            {
                base.ResultStatus = message.Status.Status;
                if (message.Status.Status == DicomState.Success)
                {
                    Platform.Log(LogLevel.Info, "Success status received in Printer Status Scu!");
                    this._results = message.DataSet;
                    switch (this._nextRequestType)
                    {
                    case RequestType.None:
                    case RequestType.FilmSession:
                        return;

                    case RequestType.FilmBox:
                        this.SendCreateFilmBoxRequest(client, association, message);
                        return;

                    case RequestType.ImageBox:
                        this.SendSetImageBoxRequest(client, association, message);
                        return;

                    case RequestType.PrintAction:
                        this.SendActionPrintRequest(client, association, message);
                        return;

                    case RequestType.DeleteFilmBox:
                        this.SendDeleteFilmBoxRequest(client, association, message);
                        return;

                    case RequestType.DeleteFilmSession:
                        this.SendDeleteFilmSessionRequest(client, association, message);
                        return;

                    case RequestType.Close:
                        base.ReleaseConnection(client);
                        return;
                    }
                }
                else
                {
                    Platform.Log(LogLevel.Info, string.Format("warning status: code:{0}, description: {1}", message.Status.Code, message.Status.Description));
                    base.ReleaseConnection(client);
                }
            }
            catch (Exception exception)
            {
                Platform.Log(LogLevel.Error, exception.ToString());
                base.ReleaseConnection(client);
                throw;
            }
        }
Exemple #27
0
        public void Query(string remoteAE, string remoteHost, int remotePort)
        {
            IPAddress addr = Dns.GetHostAddresses(remoteHost)[0];
            ClientAssociationParameters _assocParams = new ClientAssociationParameters(AETitle, remoteAE, new IPEndPoint(addr, remotePort));

            byte pcid = _assocParams.AddPresentationContext(SopClass.StudyRootQueryRetrieveInformationModelFind);

            _assocParams.AddTransferSyntax(pcid, TransferSyntax.ExplicitVrLittleEndian);
            _assocParams.AddTransferSyntax(pcid, TransferSyntax.ImplicitVrLittleEndian);

            _dicomClient = DicomClient.Connect(_assocParams, this);
        }
        private void SendDeleteFilmSessionRequest(DicomClient client, ClientAssociationParameters association, DicomMessage responseMessage)
        {
            DicomMessage message = new DicomMessage(null, null)
            {
                RequestedSopInstanceUid = this._filmSessionUid,
                RequestedSopClassUid    = SopClass.BasicFilmSessionSopClassUid
            };

            this._nextRequestType = RequestType.Close;
            byte presentationID = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);

            client.SendNDeleteRequest(presentationID, client.NextMessageID(), message);
        }
Exemple #29
0
        public void RejectTests()
        {
            int port = 2112;

            /* Setup the Server */
            ServerAssociationParameters serverParameters = new ServerAssociationParameters("AssocTestServer", new IPEndPoint(IPAddress.Any, port));
            byte pcid = serverParameters.AddPresentationContext(SopClass.MrImageStorage);

            serverParameters.AddTransferSyntax(pcid, TransferSyntax.ExplicitVrLittleEndian);
            serverParameters.AddTransferSyntax(pcid, TransferSyntax.ExplicitVrBigEndian);
            serverParameters.AddTransferSyntax(pcid, TransferSyntax.ImplicitVrLittleEndian);

            _serverType = TestTypes.AssociationReject;
            DicomServer.StartListening(serverParameters, ServerHandlerCreator);

            /* Setup the client */
            ClientAssociationParameters clientParameters = new ClientAssociationParameters("AssocTestClient", "AssocTestServer",
                                                                                           new System.Net.IPEndPoint(IPAddress.Loopback, port));

            pcid = clientParameters.AddPresentationContext(SopClass.CtImageStorage);
            clientParameters.AddTransferSyntax(pcid, TransferSyntax.ExplicitVrLittleEndian);
            clientParameters.AddTransferSyntax(pcid, TransferSyntax.ImplicitVrLittleEndian);

            /* Open the association */
            ClientHandler handler = new ClientHandler(this, TestTypes.AssociationReject);
            DicomClient   client  = DicomClient.Connect(clientParameters, handler);


            handler._threadStop.WaitOne();
            client.Dispose();

            _serverType = TestTypes.AssociationReject;

            /* Setup the client */
            clientParameters = new ClientAssociationParameters("AssocTestClient", "AssocTestServer",
                                                               new System.Net.IPEndPoint(IPAddress.Loopback, port));
            pcid = clientParameters.AddPresentationContext(SopClass.MrImageStorage);
            clientParameters.AddTransferSyntax(pcid, TransferSyntax.Jpeg2000ImageCompressionLosslessOnly);


            /* Open the association */
            ClientHandler clientHandler = new ClientHandler(this, TestTypes.AssociationReject);

            client = DicomClient.Connect(clientParameters, clientHandler);

            handler._threadStop.WaitOne();
            client.Dispose();


            DicomServer.StopListening(serverParameters);
        }
Exemple #30
0
 /// <summary>
 /// Called when [receive request 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 virtual void OnReceiveRequestMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
 {
     LogAdapter.Logger.Error("Unexpected OnReceiveRequestMessage callback on client.");
     try
     {
         client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
     }
     catch (Exception ex)
     {
         LogAdapter.Logger.TraceException(ex);
     }
     StopRunningOperation(ScuOperationStatus.UnexpectedMessage);
     throw new Exception("The method or operation is not implemented.");
 }
Exemple #31
0
		/// <summary>
		/// Generic routine to continue attempting to send C-STORE-RQ messages in the <see cref="StorageInstanceList"/> until one is successful.
		/// </summary>
		/// <remarks>
		/// <para>
		/// This routine will continue attempting to send a C-STORE until one has successfully been sent or all
		/// SOP instances in the <see cref="StorageInstanceList"/> have been sent.  Possible failures are that 
		/// a SOP Class was not negotiated, or a failure happened reading the SOP Instance from disk.
		/// </para>
		/// </remarks>
		/// <param name="client">DICOM Client class</param>
		/// <param name="association">Association Parameters</param>
		private void SendCStoreUntilSuccess(DicomClient client, ClientAssociationParameters association)
		{
			bool ok = SendCStore(client, association);
			while (ok == false)
			{
				_fileListIndex++;
				if (_fileListIndex >= _storageInstanceList.Count)
				{
					Platform.Log(LogLevel.Info, "Completed sending C-STORE-RQ messages, releasing association.");
					client.SendReleaseRequest();
					StopRunningOperation();
					return;
				}
				ok = SendCStore(client, association);
			}
		}
Exemple #32
0
 private byte SelectUncompressedPresentationContext(ClientAssociationParameters association, DicomMessage msg)
 {
     byte pcid = association.FindAbstractSyntaxWithTransferSyntax(msg.SopClass,
                                                                  TransferSyntax.ExplicitVrLittleEndian);
     if (pcid == 0)
         pcid = association.FindAbstractSyntaxWithTransferSyntax(msg.SopClass,
                                                                 TransferSyntax.ImplicitVrLittleEndian);
     return pcid;
 }
Exemple #33
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)
		{
			try
			{
				this.ResultStatus = message.Status.Status;
				switch (this.ResultStatus)
				{
					case DicomState.Cancel:
					case DicomState.Pending:
					case DicomState.Failure:
						Platform.Log(LogLevel.Error, string.Format("{0} status received in Print Scu response message", message.Status.Status));

						this.FailureDescription = SR.MessagePrinterError;
						this.ReleaseConnection(client);
						return;

					case DicomState.Warning:
						Platform.Log(LogLevel.Warn, string.Format("{0} status received in Print Scu response message", message.Status.Status));
						break;

					case DicomState.Success:
						break;
				}

				EventsHelper.Fire(this.ProgressUpdated, this, new ProgressUpdateEventArgs(_numberOfImageBoxesSent));

				if (Canceled)
				{
					Platform.Log(LogLevel.Info, "Cancel requested by user.  Closing association.");
					client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
					return;
				}

				Platform.Log(LogLevel.Info, "Success status received in Print Scu");

				var affectedUid = new DicomUid(message.AffectedSopInstanceUid, "Instance UID", UidType.SOPInstance);

				switch (message.CommandField)
				{
					case DicomCommandField.NCreateResponse:
						switch (_eventObject)
						{
							case EventObject.FilmSession:
								_filmSession.OnCreated(affectedUid);
								break;
							case EventObject.FilmBox:
								{
									var responseFilmBoxModule = new BasicFilmBoxModuleIod(message.DataSet);
									_filmSession.OnFilmBoxCreated(affectedUid,
										CollectionUtils.Map<ReferencedInstanceSequenceIod, DicomUid>(
											responseFilmBoxModule.ReferencedImageBoxSequenceList,
											imageBoxModule => new DicomUid(imageBoxModule.ReferencedSopInstanceUid, "Instance UID", UidType.SOPInstance)
										));
								}
								break;
						}

						break;

					case DicomCommandField.NDeleteResponse:
						switch (_eventObject)
						{
							case EventObject.FilmSession:
								_filmSession.OnDeleted();
								this.ReleaseConnection(client);
								break;
							case EventObject.FilmBox:
								_filmSession.OnFilmBoxDeleted();
								break;
						}

						break;

					case DicomCommandField.NSetResponse:
						_numberOfImageBoxesSent++;
						_filmSession.OnImageBoxSet(affectedUid);
						break;

					case DicomCommandField.NActionResponse:
						_filmSession.OnFilmBoxPrinted(affectedUid);

						break;
					default:
						break;
				}
			}
			catch (Exception ex)
			{
				this.FailureDescription = ex.Message;
				Platform.Log(LogLevel.Error, ex.ToString());
				ReleaseConnection(client);
				throw;
			}
		}
Exemple #34
0
        private void SendOnPresentationContext(DicomClient client, ClientAssociationParameters association, byte pcid, StorageInstance fileToSend, DicomMessage msg)
        {
            var presContext = association.GetPresentationContext(pcid);
            if (msg.TransferSyntax.Encapsulated
                && presContext.AcceptedTransferSyntax.Encapsulated
                && !msg.TransferSyntax.Equals(presContext.AcceptedTransferSyntax))
            {
                // Compressed in different syntaxes, decompress here first, ChangeTransferSyntax does not convert syntaxes properly in this case.
                msg.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);
            }

            fileToSend.SentMessageId = client.NextMessageID();

            if (_moveOriginatorAe == null)
                client.SendCStoreRequest(pcid, fileToSend.SentMessageId, DicomPriority.Medium, msg);
            else
                client.SendCStoreRequest(pcid, fileToSend.SentMessageId, DicomPriority.Medium, _moveOriginatorAe,
                                         _moveOriginatorMessageId, msg);
        }
Exemple #35
0
		/// <summary>
		/// Called when received response message.  Sets the <see cref="Result"/> 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.Success)
			{
				Platform.Log(LogLevel.Error, "Failure status received in sending verification: {0}", message.Status.Description);
				_verificationResult = VerificationResult.Failed;
			}
			else if (_verificationResult == VerificationResult.Canceled)
			{
				Platform.Log(LogLevel.Info, "Verification was canceled");
			}
			else
			{
				Platform.Log(LogLevel.Info, "Success status received in sending verification!");
				_verificationResult = VerificationResult.Success;
			}
			client.SendReleaseRequest();
			StopRunningOperation();
		}
Exemple #36
0
		/// <summary>
		/// Called when received associate accept.  For StorageScu, we then attempt to send the first file.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="association">The association.</param>
		public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
		{
			base.OnReceiveAssociateAccept(client, association);

			Platform.Log(LogLevel.Info, "Association Accepted:\r\n{0}", association.ToString());

			_fileListIndex = 0;

			SendCStoreUntilSuccess(client,association);
		}
Exemple #37
0
		/// <summary>
		/// Called when a timeout occurs waiting for the next message, as specified by <see cref="AssociationParameters.ReadTimeout"/>.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="association">The association.</param>
		public override void OnDimseTimeout(DicomClient client, ClientAssociationParameters association)
		{
			Status = ScuOperationStatus.TimeoutExpired;
			FailureDescription =
				String.Format("Timeout Expired ({0} seconds) for remote host {1} when processing C-MOVE-RQ, aborting connection", association.ReadTimeout/1000,
				              RemoteAE);
			Platform.Log(LogLevel.Error, FailureDescription);

			try
			{
				client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
			}
			catch (Exception ex)
			{
				Platform.Log(LogLevel.Error, ex, "Error aborting association");
			}

			Platform.Log(LogLevel.Warn, "Completed aborting connection (after DIMSE timeout) from {0} to {1}",
			             association.CallingAE, association.CalledAE);
			ProgressEvent.Set();
		}
Exemple #38
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 (message.Status.Status == DicomState.Pending)
        	{
        		OnImageMoveCompleted();
        	}
        	else
        	{
				DicomState status = message.Status.Status;
				if (message.Status.Status != DicomState.Success)
				{
					if (status == DicomState.Cancel)
					{
						if (LogInformation) Platform.Log(LogLevel.Info, "Cancel status received in Move Scu: {0}", message.Status);
						Status = ScuOperationStatus.Canceled;
					}
					else if (status == DicomState.Failure)
					{
						string msg = String.Format("Failure status received in Move Scu: {0}", message.Status);
						Platform.Log(LogLevel.Error, msg);
						Status = ScuOperationStatus.Failed;
						FailureDescription = msg;
					}
					else if (status == DicomState.Warning)
					{
						Platform.Log(LogLevel.Warn, "Warning status received in Move Scu: {0}", message.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();
			}
        }
Exemple #39
0
        /// <summary>
        /// Called when received associate accept.  
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
        {
            base.OnReceiveAssociateAccept(client, association);

            SendMoveRequest(client, association);
        }
        /// <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)
        {
            try
            {
                base.ResultStatus = message.Status.Status;
                if (message.Status.Status == DicomState.Success)
                {
                    if (message.CommandField == DicomCommandField.NCreateResponse && message.AffectedSopClassUid == SopClass.BasicFilmSessionSopClassUid)
                    {
                        _filmSessionUid = message.AffectedSopInstanceUid;
                    }

                    else if (message.CommandField == DicomCommandField.NCreateResponse && message.AffectedSopClassUid == SopClass.BasicFilmBoxSopClassUid)
                    {
                        _filmBoxUids.Add(message.AffectedSopInstanceUid);
                        _filmBoxResponseMessages.Add(message.AffectedSopInstanceUid, message.DataSet);
                    }

                    Platform.Log(LogLevel.Info, "Success status received in Printer Status Scu!");
                    _results = message.DataSet;
                    switch (_nextRequestType)
                    {
                        case RequestType.FilmBox:
                            SendCreateFilmBoxRequest(client, association, message);
                            break;

                        case RequestType.ImageBox:
                            SendSetImageBoxRequest(client, association);
                            break;

                        case RequestType.PrintAction:
                            SendActionPrintRequest(client, association);
                            break;

                        case RequestType.DeleteFilmBox:
                            SendDeleteFilmBoxRequest(client, association, message);
                            break;

                        case RequestType.DeleteFilmSession:
                            SendDeleteFilmSessionRequest(client, association);
                            break;

                        case RequestType.Close:
                            base.ReleaseConnection(client);
                            break;

                        case RequestType.None:
                        default:
                            // TODO: throw error....
                            break;
                    }
                }
                else
                {
                    // TODO: Handle this... check for warnings - they are OK?  throw exception on errors... ?
                }

            }
            catch (Exception ex)
            {
                Platform.Log(LogLevel.Error, ex.ToString());
                base.ReleaseConnection(client);
                throw;
            }
        }
Exemple #41
0
		/// <summary>
		/// Called when received response message.  If there are more files to send, will send them here.
		/// </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 (_storageInstanceList.Count > 0)
            {
                _storageInstanceList[_fileListIndex].SendStatus = message.Status;
                _storageInstanceList[_fileListIndex].ExtendedFailureDescription = message.ErrorComment;
            }

		    if (message.Status.Status != DicomState.Success)
			{
				if (message.Status.Status == DicomState.Warning)
				{
					_warningSubOperations++;
					Platform.Log(LogLevel.Warn, "Warning status received in sending C-STORE to {0}: {1}",
								 association.CalledAE, message.Status.Description);
				}
				else if (message.Status.Status == DicomState.Failure)
				{
					_failureSubOperations++;
					Platform.Log(LogLevel.Error, "Failure status received in sending C-STORE to {0}: {1}",
						association.CalledAE, message.Status.Description);
				}
			}
			else
				_successSubOperations++;

			_remainingSubOperations--;

			OnImageStoreCompleted(_storageInstanceList[_fileListIndex]);

			if (Status == ScuOperationStatus.Canceled || message.Status.Status == DicomState.Cancel)
			{
				FailRemaining(DicomStatuses.Cancel);
				Platform.Log(LogLevel.Info, "Cancel requested by {0}, releasing association from {1} to {2}",
					(message.Status.Status == DicomState.Cancel) ? "remote host" : "client", 
					association.CallingAE, association.CalledAE);

				Status = ScuOperationStatus.Canceled;
				client.SendReleaseRequest();
				StopRunningOperation();
				return;
			}

			_fileListIndex++;
			if (_fileListIndex >= _storageInstanceList.Count)
			{
				Platform.Log(LogLevel.Info, "Completed sending {0} C-STORE-RQ messages, releasing association.", _storageInstanceList.Count);
				client.SendReleaseRequest();
				StopRunningOperation();
				return;
			}
		    SendCStoreUntilSuccess(client, association);
		}
Exemple #42
0
		/// <summary>
		/// Generic routine to send the next C-ECHO-RQ message.
		/// </summary>
		/// <param name="client">DICOM Client class</param>
		/// <param name="association">Association Parameters</param>
		private void SendVerificationRequest(DicomClient client, ClientAssociationParameters association)
		{
			byte pcid = association.FindAbstractSyntax(SopClass.VerificationSopClass);

			client.SendCEchoRequest(pcid, client.NextMessageID());
		}
Exemple #43
0
 /// <summary>
 /// Sends the find request.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="association">The association.</param>
 private static void SendRequest(DicomClient client, ClientAssociationParameters association)
 {
     DicomMessage newRequestMessage = new DicomMessage();
     PrinterModuleIod.SetCommonTags(newRequestMessage.DataSet);
     byte pcid = association.FindAbstractSyntax(SopClass.PrinterSopClass);
     if (pcid > 0)
     {
         client.SendNGetRequest(DicomUids.PrinterSOPInstance, pcid, client.NextMessageID(), newRequestMessage);
     }
 }
Exemple #44
0
		/// <summary>
		/// Generic routine to send the next C-STORE-RQ message in the <see cref="StorageInstanceList"/>.
		/// </summary>
		/// <param name="client">DICOM Client class</param>
		/// <param name="association">Association Parameters</param>
		private bool SendCStore(DicomClient client, ClientAssociationParameters association)
		{
			StorageInstance fileToSend = _storageInstanceList[_fileListIndex];

			OnImageStoreStarted(fileToSend);

			DicomFile dicomFile;

			try
			{
				// Check to see if image does not exist or is corrupted
				if (fileToSend.SendStatus == DicomStatuses.ProcessingFailure)
				{
					_failureSubOperations++;
					_remainingSubOperations--;
					OnImageStoreCompleted(fileToSend);
					return false;
				}

				dicomFile = fileToSend.LoadFile();
			}
			catch (DicomException e)
			{
				Platform.Log(LogLevel.Error, e, "Unexpected exception when loading DICOM file {0}", fileToSend.Filename);

				fileToSend.ExtendedFailureDescription = e.GetType().Name + " " + e.Message;
				_failureSubOperations++;
				_remainingSubOperations--;
				OnImageStoreCompleted(fileToSend);
				return false;
			}

		    try
            {
                DicomMessage msg;

                byte pcid = SelectPresentationContext(association, fileToSend, dicomFile, out msg);

                if (pcid == 0)
                {
                    fileToSend.SendStatus = DicomStatuses.SOPClassNotSupported;
                    fileToSend.ExtendedFailureDescription = string.Format(SR.ErrorSendSopClassNotSupported, msg.SopClass);

                    LogError(fileToSend, msg, DicomStatuses.SOPClassNotSupported);

                    _failureSubOperations++;
                    _remainingSubOperations--;
                    OnImageStoreCompleted(fileToSend);
                    return false;
                }

                try
                {
                    SendOnPresentationContext(client, association, pcid, fileToSend, msg);
                }
                catch (DicomCodecUnsupportedSopException e)
                {
                    if (!msg.TransferSyntax.Encapsulated)
                    {
                        pcid = SelectUncompressedPresentationContext(association, msg);
                        if (pcid != 0)
                        {
                            SendOnPresentationContext(client, association, pcid, fileToSend, msg);
                            Platform.Log(LogLevel.Warn, "Could not send SOP as compressed, sent as uncompressed: {0}, file: {1}", e.Message, fileToSend.SopInstanceUid);
                            return true;
                        }
                    }

                    throw;
                }
            }
            catch (DicomNetworkException)
            {
                throw; //This is a DicomException-derived class that we want to throw.
            } 
            catch (DicomCodecException e)
            {
                Platform.Log(LogLevel.Error, e, "Unexpected exception when compressing or decompressing file before send {0}", fileToSend.Filename);

                fileToSend.SendStatus = DicomStatuses.ProcessingFailure;
                fileToSend.ExtendedFailureDescription = string.Format("Error decompressing or compressing file before send: {0}", e.Message);
                _failureSubOperations++;
                _remainingSubOperations--;
                OnImageStoreCompleted(fileToSend);
                return false;

            }
            catch (DicomException e)
            {
                Platform.Log(LogLevel.Error, e, "Unexpected exception while sending file {0}", fileToSend.Filename);

                fileToSend.SendStatus = DicomStatuses.ProcessingFailure;
                fileToSend.ExtendedFailureDescription = string.Format("Unexpected exception while sending file: {0}", e.Message);
                _failureSubOperations++;
                _remainingSubOperations--;
                OnImageStoreCompleted(fileToSend);
                return false;
            }

			return true;
		}
        private void SendSetImageBoxRequest(DicomClient client, ClientAssociationParameters association)
        {
            if (_currentImageBoxIndex >= _imageBoxPixelModuleIods.Count)
            {
                // done sending images box - send print request
                _nextRequestType = RequestType.PrintAction;
                SendActionPrintRequest(client, association);
            }
            else
            {
                // want to get first film box response - although not sure if CC is using .net 3.5.. prolly not so do it old way
                IEnumerator<DicomAttributeCollection> filmBoxResponseEnumerator = _filmBoxResponseMessages.Values.GetEnumerator();
                filmBoxResponseEnumerator.Reset();
                filmBoxResponseEnumerator.MoveNext();

                BasicFilmBoxModuleIod basicFilmBoxModuleIod = new BasicFilmBoxModuleIod(filmBoxResponseEnumerator.Current);

                if (_currentImageBoxIndex > basicFilmBoxModuleIod.ReferencedImageBoxSequenceList.Count)
                {
                    throw new DicomException("Current Image Box Index is greater than number of Referenced ImageBox Sequences - set image box data");
                }

                ImageBoxPixelModuleIod imageBoxPixelModuleIod = _imageBoxPixelModuleIods[_currentImageBoxIndex];

                DicomMessage newRequestMessage = new DicomMessage(null, (DicomAttributeCollection)imageBoxPixelModuleIod.DicomAttributeProvider);
                newRequestMessage.RequestedSopClassUid = SopClass.BasicGrayscaleImageBoxSopClassUid;
                newRequestMessage.RequestedSopInstanceUid = basicFilmBoxModuleIod.ReferencedImageBoxSequenceList[_currentImageBoxIndex].ReferencedSopInstanceUid;

                byte pcid = association.FindAbstractSyntax(SopClass.BasicGrayscalePrintManagementMetaSopClass);

                _currentImageBoxIndex++;
                client.SendNSetRequest(pcid, client.NextMessageID(), newRequestMessage);
            }

        }
        private void SendCreateFilmBoxRequest(DicomClient client, ClientAssociationParameters association, DicomMessage responseMessage)
        {

            ReferencedInstanceSequenceIod referencedFilmSessionSequence = new ReferencedInstanceSequenceIod();
            referencedFilmSessionSequence.ReferencedSopClassUid = SopClass.BasicFilmSessionSopClassUid;
            referencedFilmSessionSequence.ReferencedSopInstanceUid = responseMessage.AffectedSopInstanceUid;
            _basicFilmBoxModuleIod.ReferencedFilmSessionSequenceList.Add(referencedFilmSessionSequence);

            DicomMessage newRequestMessage = new DicomMessage(null, (DicomAttributeCollection)_basicFilmBoxModuleIod.DicomAttributeProvider);

            byte pcid = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);

            _nextRequestType = RequestType.ImageBox;
            client.SendNCreateRequest(DicomUid.GenerateUid(), pcid, client.NextMessageID(), newRequestMessage, DicomUids.BasicFilmBoxSOP);
        }
Exemple #47
0
		/// <summary>
		/// Called when received associate accept.  We send the verificationrequest.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="association">The association.</param>
		public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
		{
			base.OnReceiveAssociateAccept(client, association);
			if (Canceled)
				client.SendAssociateAbort(DicomAbortSource.ServiceUser,DicomAbortReason.NotSpecified);
			else
				SendVerificationRequest(client, association);
		}
Exemple #48
0
		/// <summary>
		/// Called when received associate accept.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="association">The association.</param>
		public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
		{
			base.OnReceiveAssociateAccept(client, association);
			if (Canceled)
			{
				client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
			}
			else
			{
				CreateFilmSession(_filmSession);
			}
		}
        private void SendDeleteFilmSessionRequest(DicomClient client, ClientAssociationParameters association)
        {
            DicomMessage newRequestMessage = new DicomMessage(null, null);
            newRequestMessage.RequestedSopInstanceUid = _filmSessionUid;
            newRequestMessage.RequestedSopClassUid = SopClass.BasicFilmSessionSopClassUid;

            _nextRequestType = RequestType.Close;
            byte pcid = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);
            client.SendNDeleteRequest(pcid, client.NextMessageID(), newRequestMessage);
        }
Exemple #50
0
	    private byte SelectPresentationContext(ClientAssociationParameters association, StorageInstance fileToSend, DicomFile dicomFile, out DicomMessage msg)
        {
            byte pcid = 0;
            if (PresentationContextSelectionDelegate != null)
            {
                // Note, this may do a conversion of the file according to codecs, need to catch a codec exception if it occurs
                pcid = PresentationContextSelectionDelegate(association, dicomFile, out msg);
            }
            else
            {
                msg = new DicomMessage(dicomFile);

                if (fileToSend.TransferSyntax.Encapsulated)
                {
                    pcid = association.FindAbstractSyntaxWithTransferSyntax(msg.SopClass,
                                                                            msg.TransferSyntax);

                    if (DicomCodecRegistry.GetCodec(fileToSend.TransferSyntax) != null)
                    {
                        // We can compress/decompress the file. Check if remote device accepts it
                        if (pcid == 0)
                            pcid = SelectUncompressedPresentationContext(association, msg);
                    }
                }
                else
                {
                    if (pcid == 0)
                        pcid = SelectUncompressedPresentationContext(association, msg);
                }
            }
            return pcid;
        }
        private void SendCreateFilmSessionRequest(DicomClient client, ClientAssociationParameters association)
        {
            DicomMessage newRequestMessage = new DicomMessage(null, (DicomAttributeCollection)_basicFilmSessionModuleIod.DicomAttributeProvider);

            byte pcid = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);
            _nextRequestType = RequestType.FilmBox;
            client.SendNCreateRequest(DicomUid.GenerateUid(), pcid, client.NextMessageID(), newRequestMessage, DicomUids.BasicFilmSession);
        }
Exemple #52
0
		/// <summary>
		/// Called when [receive request 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 OnReceiveRequestMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
		{
			if (message.CommandField == DicomCommandField.NEventReportRequest)
			{
				Platform.Log(LogLevel.Info, "N-EVENT-REPORT-RQ messages currently not supported by StorageCommitScu.  Aborting connection.");
				client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
				StopRunningOperation(ScuOperationStatus.UnexpectedMessage);
				throw new Exception("The method or operation is not implemented.");
			}
			else
			{
				Platform.Log(LogLevel.Info, "Unexpected OnReceiveRequestMessage callback on client.");
				try
				{
					client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
				}
				catch (Exception ex)
				{
					Platform.Log(LogLevel.Error, ex, "Error aborting association");
				}
				StopRunningOperation(ScuOperationStatus.UnexpectedMessage);
				throw new Exception("The method or operation is not implemented.");
			}
		}
Exemple #53
0
		public override void OnReceiveRequestMessage(DicomClient client, ClientAssociationParameters association, byte presentationID, DicomMessage message)
		{
			try
			{
				// We only handle NEventReport request messages
				if (message.CommandField != DicomCommandField.NEventReportRequest ||
					message.AffectedSopClassUid != SopClass.PrinterSopClassUid)
				{
					base.OnReceiveRequestMessage(client, association, presentationID, message);
					return;
				}
				
				var printerStatus = IodBase.ParseEnum(message.EventTypeId.ToString(), PrinterStatus.None);
				var printerModule = new PrinterModuleIod(message.DataSet);
				var logMessage = string.Format("Received NEventReportRequest, Printer Status: {0}, Status Info = {1}", printerStatus,
											   printerModule.PrinterStatusInfo);

				//Always respond.
				Client.SendNEventReportResponse(GetPresentationContextId(this.AssociationParameters),
												 message, new DicomMessage(), DicomStatuses.Success);

				switch (printerStatus)
				{
					case PrinterStatus.Failure:
						Platform.Log(LogLevel.Error, logMessage);
						this.FailureDescription = SR.MessagePrinterError;
						this.ReleaseConnection(client);
						return;
					case PrinterStatus.Warning:
						Platform.Log(LogLevel.Warn, logMessage);
						break;
					case PrinterStatus.None:
					case PrinterStatus.Normal:
					default:
						Platform.Log(LogLevel.Debug, logMessage);
						break;
				}

			}
			catch (Exception ex)
			{
				this.FailureDescription = ex.Message;
				Platform.Log(LogLevel.Error, ex.ToString());
				ReleaseConnection(client);
				throw;
			}
		}
        private void SendDeleteFilmBoxRequest(DicomClient client, ClientAssociationParameters association, DicomMessage responseMessage)
        {
            if (_filmBoxUids.Count == 0)
            {
                // no more film boxes left to delete - so send delete film session
                SendDeleteFilmSessionRequest(client, association);
            }
            else
            {
                string currentFilmBoxUid = _filmBoxUids[0];
                _filmBoxUids.Remove(currentFilmBoxUid);

                DicomMessage newRequestMessage = new DicomMessage(null, null);
                newRequestMessage.RequestedSopInstanceUid = currentFilmBoxUid;
                newRequestMessage.RequestedSopClassUid = SopClass.BasicFilmBoxSopClassUid;
                newRequestMessage.Priority = DicomPriority.Medium;

                _nextRequestType = RequestType.DeleteFilmBox;

                byte pcid = association.FindAbstractSyntaxOrThrowException(SopClass.BasicGrayscalePrintManagementMetaSopClass);
                client.SendNDeleteRequest(pcid, client.NextMessageID(), newRequestMessage);
            }
        }
Exemple #55
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)
 {
     base.ResultStatus = message.Status.Status;
     if (message.Status.Status == DicomState.Success)
     {
         this._results = message.DataSet;
     }
     base.ReleaseConnection(client);
 }
Exemple #56
0
		/// <summary>
		/// Generic routine to continue attempting to send C-STORE-RQ messages in the <see cref="StorageInstanceList"/> until one is successful.
		/// </summary>
		/// <remarks>
		/// <para>
		/// This routine will continue attempting to send a C-STORE until one has successfully been sent or all
		/// SOP instances in the <see cref="StorageInstanceList"/> have been sent.  Possible failures are that 
		/// a SOP Class was not negotiated, or a failure happened reading the SOP Instance from disk.
		/// </para>
		/// </remarks>
		/// <param name="client">DICOM Client class</param>
		/// <param name="association">Association Parameters</param>
		private void SendCStoreUntilSuccess(DicomClient client, ClientAssociationParameters association)
		{
		    /// TODO (CR Jun 2012): Probably shouldn't use thread pool threads for potentially long-running operations.
		    /// Although unlikely, this could exhaust the .NET thread pool.
		    
            // Added the background thread as part of ticket #9568.  Note that we probably should have some threading 
            // built into NetworkBase as opposed to here.
		    ThreadPool.QueueUserWorkItem(delegate
		                                     {
                                                 try
                                                 {
                                                     bool ok = SendCStore(client, association);
                                                     while (ok == false)
                                                     {
                                                         Platform.Log(LogLevel.Info, "Attempted to send {0} of {1} instances to {2}.", _fileListIndex + 1, _storageInstanceList.Count, client.AssociationParams.CalledAE);
                                                         _fileListIndex++;
                                                         if (_fileListIndex >= _storageInstanceList.Count)
                                                         {
                                                             Platform.Log(LogLevel.Info,
                                                                          "Completed sending C-STORE-RQ messages, releasing association.");
                                                             client.SendReleaseRequest();
                                                             StopRunningOperation();
                                                             return;
                                                         }

                                                         /// TODO (CR Jun 2012): Do we need to check for a stop signal?
                                                         // TODO (Marmot): Check stop?
                                                         // TODO (CR Jun 2012): Stop is checked for in OnReceiveResponseMessage after each c-store-rsp received.
                                                         // There's a small chance that every image we're attempting to send wasn't negotiated over the association and it
                                                         // takes awhile to go through the list, but the chances of that are small, plus it should be quick.
                                                         ok = SendCStore(client, association);                                                             
                                                     }                                                     
                                                 }
                                                 catch
                                                 {
                                                     Platform.Log(LogLevel.Error, "Error when sending C-STORE-RQ messages, aborted on-going send operations");
                                                     try
                                                     {
                                                         client.SendAssociateAbort(DicomAbortSource.ServiceProvider, DicomAbortReason.NotSpecified);
                                                         StopRunningOperation();    
                                                     }
                                                     catch
                                                     {
                                                         Platform.Log(LogLevel.Error, "Error attempting to abort association");
                                                     }                                                     
                                                 }
		                                     }, null);
		}
Exemple #57
0
		/// <summary>
		/// Called when received associate accept.  For StorageScu, we then attempt to send the first file.
		/// </summary>
		/// <param name="client">The client.</param>
		/// <param name="association">The association.</param>
		public override void OnReceiveAssociateAccept(DicomClient client, ClientAssociationParameters association)
		{
			base.OnReceiveAssociateAccept(client, association);

			Platform.Log(LogLevel.Info, "Association Accepted:\r\n{0}", association.ToString());

			byte pcid = association.FindAbstractSyntaxWithTransferSyntax(SopClass.StorageCommitmentPushModelSopClass,
			                                                             TransferSyntax.ExplicitVrLittleEndian);
			if (pcid == 0)
				pcid = association.FindAbstractSyntaxWithTransferSyntax(SopClass.StorageCommitmentPushModelSopClass,
				                                                        TransferSyntax.ImplicitVrLittleEndian);
			if (pcid == 0)
			{
				client.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
				return;
			}

			DicomMessage msg = new DicomMessage();

			msg.RequestedSopInstanceUid = "1.2.840.10008.1.20.1.1";
			msg.ActionTypeId = 1;
			msg.DataSet[DicomTags.TransactionUid].SetStringValue(DicomUid.GenerateUid().UID);

			foreach (StorageInstance instance in StorageInstanceList)
			{
				DicomSequenceItem item = new DicomSequenceItem();

				msg.DataSet[DicomTags.ReferencedSopSequence].AddSequenceItem(item);

				item[DicomTags.ReferencedSopClassUid].SetStringValue(instance.SopClass.Uid);
				item[DicomTags.ReferencedSopInstanceUid].SetStringValue(instance.SopInstanceUid);
			}


		}
Exemple #58
0
		/// <summary>
		/// Called when received response message.  If there are more files to send, will send them here.
		/// </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 (Status == ScuOperationStatus.Canceled)
			{
				Platform.Log(LogLevel.Info, "Cancel request received, releasing association from {0} to {1}", association.CallingAE, association.CalledAE);
				client.SendReleaseRequest();
				StopRunningOperation();
				return;
			}
		}
Exemple #59
0
        /// <summary>
        /// Sends the move request (called after the association is accepted).
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="association">The association.</param>
        private void SendMoveRequest(DicomClient client, ClientAssociationParameters association)
        {
            byte pcid = association.FindAbstractSyntaxOrThrowException(MoveSopClass);

            DicomMessage dicomMessage = new DicomMessage();
            foreach (DicomAttribute dicomAttribute in _dicomAttributeCollection)
            {
                // Need to do it this way in case the attribute is blank
                DicomAttribute dicomAttribute2 = dicomMessage.DataSet[dicomAttribute.Tag];
                if (dicomAttribute.Values != null)
                    dicomAttribute2.Values = dicomAttribute.Values;
            }

            client.SendCMoveRequest(pcid, client.NextMessageID(), _destinationAe, dicomMessage);
        }
Exemple #60
0
		/// <summary>
		/// Generic routine to send the next C-STORE-RQ message in the <see cref="StorageInstanceList"/>.
		/// </summary>
		/// <param name="client">DICOM Client class</param>
		/// <param name="association">Association Parameters</param>
		private bool SendCStore(DicomClient client, ClientAssociationParameters association)
		{
			StorageInstance fileToSend = _storageInstanceList[_fileListIndex];

			OnImageStoreStarted(fileToSend);

			DicomFile dicomFile;

			try
			{
				// Check to see if image does not exist or is corrupted
				if (fileToSend.SendStatus == DicomStatuses.ProcessingFailure)
				{
					_failureSubOperations++;
					_remainingSubOperations--;
					OnImageStoreCompleted(fileToSend);
					return false;
				}

				dicomFile = fileToSend.LoadFile();
			}
			catch (DicomException e)
			{
				Platform.Log(LogLevel.Error, e, "Unexpected exception when loading DICOM file {0}", fileToSend.Filename);

				fileToSend.ExtendedFailureDescription = e.GetType().Name + " " + e.Message;
				_failureSubOperations++;
				_remainingSubOperations--;
				OnImageStoreCompleted(fileToSend);
				return false;
			}

			DicomMessage msg = new DicomMessage(dicomFile);

			byte pcid = 0;

			if (fileToSend.TransferSyntax.Encapsulated)
			{
				pcid = association.FindAbstractSyntaxWithTransferSyntax(fileToSend.SopClass, fileToSend.TransferSyntax);

				if (DicomCodecRegistry.GetCodec(fileToSend.TransferSyntax) != null)
				{
					if (pcid == 0)
						pcid = association.FindAbstractSyntaxWithTransferSyntax(fileToSend.SopClass,
						                                                        TransferSyntax.ExplicitVrLittleEndian);
					if (pcid == 0)
						pcid = association.FindAbstractSyntaxWithTransferSyntax(fileToSend.SopClass,
						                                                        TransferSyntax.ImplicitVrLittleEndian);
				}
			}
			else
			{
				if (pcid == 0)
					pcid = association.FindAbstractSyntaxWithTransferSyntax(fileToSend.SopClass,
					                                                        TransferSyntax.ExplicitVrLittleEndian);
				if (pcid == 0)
					pcid = association.FindAbstractSyntaxWithTransferSyntax(fileToSend.SopClass,
					                                                        TransferSyntax.ImplicitVrLittleEndian);
			}

			if (pcid == 0)
			{
				fileToSend.SendStatus = DicomStatuses.SOPClassNotSupported;
				fileToSend.ExtendedFailureDescription = "No valid presentation contexts for file.";
				OnImageStoreCompleted(fileToSend);
				_failureSubOperations++;
				_remainingSubOperations--;
				return false;
			}

			try
			{
				if (_moveOriginatorAe == null)
					client.SendCStoreRequest(pcid, client.NextMessageID(), DicomPriority.Medium, msg);
				else
					client.SendCStoreRequest(pcid, client.NextMessageID(), DicomPriority.Medium, _moveOriginatorAe,
					                         _moveOriginatorMessageId, msg);
			}
			catch(DicomNetworkException)
			{
				throw; //This is a DicomException-derived class that we want to throw.
			}
			catch(DicomCodecException e)
			{
				Platform.Log(LogLevel.Error, e, "Unexpected exception when compressing or decompressing file before send {0}", fileToSend.Filename);

				fileToSend.SendStatus = DicomStatuses.ProcessingFailure;
				fileToSend.ExtendedFailureDescription = "Error decompressing or compressing file before send.";
				OnImageStoreCompleted(fileToSend);
				_failureSubOperations++;
				_remainingSubOperations--;
				return false;

			}
			catch(DicomException e)
			{
				Platform.Log(LogLevel.Error, e, "Unexpected exception while sending file {0}", fileToSend.Filename);

				fileToSend.SendStatus = DicomStatuses.ProcessingFailure;
				fileToSend.ExtendedFailureDescription = "Unexpected exception while sending file.";
				OnImageStoreCompleted(fileToSend);
				_failureSubOperations++;
				_remainingSubOperations--;
				return false;
			}

			return true;
		}