Esempio n. 1
0
 void IDicomServerHandler.OnReceiveReleaseRequest(DicomServer server, ServerAssociationParameters association)
 {
     LogAdapter.Logger.InfoWithFormat("Received association release request from {0} to {1}.", association.CallingAE, association.CalledAE);
     if (_complete != null)
     {
         _complete(_context, association, _instances);
     }
     OnAssociationRelease(server, association);
     Cleanup();
 }
Esempio n. 2
0
 void IDicomServerHandler.OnReceiveAbort(DicomServer server, ServerAssociationParameters association, DicomAbortSource source, DicomAbortReason reason)
 {
     LogAdapter.Logger.ErrorWithFormat("Received association abort from {0} to {1}", association.CallingAE, association.CalledAE);
     if (_complete != null)
     {
         _complete(_context, association, _instances);
     }
     OnAssociationAbort(server, association);
     Cleanup();
 }
Esempio n. 3
0
        private static void RemoveAllAssociationMppsFromCache(ServerAssociationParameters association)
        {
            ListDictionary mppsAssociationList;

            if (_mppsCache.TryGetValue(association.GetHashCode(), out mppsAssociationList))
            {
                mppsAssociationList.Clear();
                _mppsCache.Remove(association.GetHashCode());
            }
            Logger.LogInfo("Remove All Association cached mppsiod.");
        }
Esempio n. 4
0
        private static void AddPresentationContexts(ServerAssociationParameters assoc)
        {
            byte pcid = assoc.AddPresentationContext(SopClass.VerificationSopClass);

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

            pcid = assoc.AddPresentationContext(SopClass.ModalityWorklistInformationModelFind);
            assoc.AddTransferSyntax(pcid, TransferSyntax.ExplicitVrLittleEndian);
            assoc.AddTransferSyntax(pcid, TransferSyntax.ImplicitVrLittleEndian);
        }
Esempio n. 5
0
 /// <summary>
 /// Image transfer syntaxes
 /// </summary>
 /// <param name="pcid"></param>
 /// <param name="assoc"></param>
 public static void SetImageTransferSyntaxes(byte pcid, ServerAssociationParameters assoc)
 {
     assoc.AddTransferSyntax(pcid, TransferSyntax.JpegLosslessNonHierarchicalFirstOrderPredictionProcess14SelectionValue1);
     assoc.AddTransferSyntax(pcid, TransferSyntax.RleLossless);
     assoc.AddTransferSyntax(pcid, TransferSyntax.Jpeg2000ImageCompression);
     assoc.AddTransferSyntax(pcid, TransferSyntax.Jpeg2000ImageCompressionLosslessOnly);
     assoc.AddTransferSyntax(pcid, TransferSyntax.JpegBaselineProcess1);
     assoc.AddTransferSyntax(pcid, TransferSyntax.JpegExtendedProcess24);
     assoc.AddTransferSyntax(pcid, TransferSyntax.ExplicitVrLittleEndian);
     assoc.AddTransferSyntax(pcid, TransferSyntax.ImplicitVrLittleEndian);
 }
Esempio n. 6
0
        public void StorageScuMoveOriginatorTest()
        {
            int port = 2112;

            _serverHandlerList.Clear();

            /* Setup the Server */
            var  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.Receive;
            DicomServer.StartListening(serverParameters, ServerHandlerCreator);

            string     moveOriginatorAe = "ORIGINATOR";
            ushort     moveOriginatorId = 999;
            StorageScu scu = SetupScu(moveOriginatorAe, moveOriginatorId);

            IList <DicomAttributeCollection> list = SetupMRSeries(4, 2, DicomUid.GenerateUid().UID);

            foreach (DicomAttributeCollection collection in list)
            {
                var file = new DicomFile("test", new DicomAttributeCollection(), collection)
                {
                    TransferSyntax             = TransferSyntax.ExplicitVrLittleEndian,
                    MediaStorageSopClassUid    = SopClass.MrImageStorage.Uid,
                    MediaStorageSopInstanceUid = collection[DicomTags.SopInstanceUid].ToString()
                };

                scu.AddStorageInstance(new StorageInstance(file));
            }

            scu.Send();
            scu.Join();

            Assert.AreEqual(scu.Status, ScuOperationStatus.NotRunning);

            var handler       = CollectionUtils.FirstElement(_serverHandlerList);
            var serverHandler = handler as ServerHandler;

            Assert.NotNull(serverHandler);

            foreach (var message in serverHandler.MessagesReceived)
            {
                Assert.AreEqual(message.MoveOriginatorApplicationEntityTitle, moveOriginatorAe);
                Assert.AreEqual(message.MoveOriginatorMessageId, moveOriginatorId);
            }

            // StopListening
            DicomServer.StopListening(serverParameters);
        }
Esempio n. 7
0
        private static void AddPresentationContexts(ServerAssociationParameters assoc)
        {
            byte pcid = assoc.AddPresentationContext(SopClass.VerificationSopClass);

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

            pcid = assoc.AddPresentationContext(SopClass.ModalityPerformedProcedureStepSopClass);
            assoc.AddTransferSyntax(pcid, TransferSyntax.ExplicitVrLittleEndian);
            assoc.AddTransferSyntax(pcid, TransferSyntax.ImplicitVrLittleEndian);
        }
Esempio n. 8
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <remarks>
        /// The constructor creates a dictionary of each presentation context negotiated for the
        /// association, and the plugin that will handle it.  This is used later when incoming request
        /// messages are processed.
        /// </remarks>
        /// <param name="server">The server.</param>
        /// <param name="parameters">Association parameters for the negotiated association.</param>
        /// <param name="userParms">User parameters to be passed to the plugins called by the class.</param>
        /// <param name="verifier">Delegate to call to verify an association before its accepted.</param>
        /// <param name="complete">Delegate to call when the association is closed/complete.  Can be null.</param>
        public DicomScpHandler(DicomServer server, ServerAssociationParameters parameters, TContext userParms, DicomScp <TContext> .AssociationVerifyCallback verifier, DicomScp <TContext> .AssociationComplete complete)
        {
            _context  = userParms;
            _verifier = verifier;
            _complete = complete;

            DicomScpExtensionPoint <TContext> ep = new DicomScpExtensionPoint <TContext>();

            object[] scps = ep.CreateExtensions();

            // First set the user parms for each of the extensions before we do anything with them.
            foreach (object obj in scps)
            {
                IDicomScp <TContext> scp = obj as IDicomScp <TContext>;
                scp.SetContext(_context);
            }

            // Now, create a dictionary with the extension to be used for each presentation context.
            foreach (byte pcid in parameters.GetPresentationContextIDs())
            {
                if (parameters.GetPresentationContextResult(pcid) == DicomPresContextResult.Accept)
                {
                    SopClass       acceptedSop    = SopClass.GetSopClass(parameters.GetAbstractSyntax(pcid).UID);
                    TransferSyntax acceptedSyntax = parameters.GetAcceptedTransferSyntax(pcid);
                    foreach (object obj in scps)
                    {
                        IDicomScp <TContext> scp = obj as IDicomScp <TContext>;

                        IList <SupportedSop> sops = scp.GetSupportedSopClasses();
                        foreach (SupportedSop sop in sops)
                        {
                            if (sop.SopClass.Equals(acceptedSop))
                            {
                                if (sop.SyntaxList.Contains(acceptedSyntax))
                                {
                                    if (!_extensionList.ContainsKey(pcid))
                                    {
                                        _extensionList.Add(pcid, scp);
                                        break;
                                    }
                                    else
                                    {
                                        Platform.Log(LogLevel.Error, "SOP Class {0} supported by more than one extension", sop.SopClass.Name);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            _statsRecorder = new AssociationStatisticsRecorder(server);
        }
Esempio n. 9
0
        private static void RemoveMppsEntityFromCache(ServerAssociationParameters association, string key)
        {
            ListDictionary mppsAssociationList;

            if (_mppsCache.TryGetValue(association.GetHashCode(), out mppsAssociationList))
            {
                if (mppsAssociationList.Contains(key))
                {
                    mppsAssociationList.Remove(key);
                }
            }
        }
Esempio n. 10
0
        public bool CompleteStream(DicomServer server, ServerAssociationParameters assoc, byte presentationId, DicomMessage message)
        {
            DicomProcessingResult result;

            try
            {
                if (_fileStream != null)
                {
                    _fileStream.Flush(true);
                    _fileStream.Close();
                    _fileStream.Dispose();
                    _fileStream = null;
                }

                ISopInstanceImporter importer = IoC.Get <ISopInstanceImporter>();
                importer.Context = _importContext;

                result = importer.ImportFile(message, _sourceFilename);

                if (result.Successful)
                {
                    if (!String.IsNullOrEmpty(result.AccessionNumber))
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
                                     result.SopInstanceUid, assoc.CallingAE, assoc.CalledAE, result.AccessionNumber,
                                     result.StudyInstanceUid);
                    }
                    else
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
                                     result.SopInstanceUid, assoc.CallingAE, assoc.CalledAE,
                                     result.StudyInstanceUid);
                    }
                }
            }
            catch (Exception e)
            {
                result = new DicomProcessingResult {
                    DicomStatus = DicomStatuses.ProcessingFailure, ErrorMessage = e.Message
                };
            }

            if (!result.Successful)
            {
                Platform.Log(LogLevel.Warn, "Failure importing sop: {0}", result.ErrorMessage);
            }

            CleanupDirectory();

            server.SendCStoreResponse(presentationId, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
            return(true);
        }
Esempio n. 11
0
        public override bool OnReceiveRequest(DicomServer server, ServerAssociationParameters association,
                                              byte presentationId, DicomMessage message)
        {
            try
            {
                SopInstanceImporterContext context = new SopInstanceImporterContext(
                    String.Format("{0}_{1}", association.CallingAE, association.TimeStamp.ToString("yyyyMMddhhmmss")),
                    association.CallingAE, Partition.AeTitle);

                DicomProcessingResult result   = new DicomProcessingResult();
                ISopInstanceImporter  importer = IoC.Get <ISopInstanceImporter>();
                if (importer != null)
                {
                    importer.Context = context;
                    result           = importer.Import(message);
                }

                if (result.Successful)
                {
                    if (!String.IsNullOrEmpty(result.AccessionNumber))
                    {
                        Log.Logger.Info("Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
                                        result.SopInstanceUid, association.CallingAE, association.CalledAE, result.AccessionNumber,
                                        result.StudyInstanceUid);
                    }
                    else
                    {
                        Log.Logger.Info("Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
                                        result.SopInstanceUid, association.CallingAE, association.CalledAE,
                                        result.StudyInstanceUid);
                    }
                }
                else
                {
                    Log.Logger.Warn("Failure importing sop: {0}", result.ErrorMessage);
                }

                server.SendCStoreResponse(presentationId, message.MessageId,
                                          message.AffectedSopInstanceUid, result.DicomStatus);
                return(true);
            }
            catch (DicomDataException ex)
            {
                Log.Logger.Error(ex, "Error when import {0}", message.AffectedSopInstanceUid);
                return(false);  // caller will abort the association
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Error when import {0}", message.AffectedSopInstanceUid);
                return(false);  // caller will abort the association
            }
        }
Esempio n. 12
0
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            _sessionDebug.SetAssociationDumpString(association);
            _sessionDebug._request = message.Dump();

            #region Cancel request
            if (message.CommandField == DicomCommandField.CCancelRequest)
            {
                Logger.LogInfo("Received CANCEL-RQ message from {0}.", association.CallingAE);
                _cancelReceived = true;
                return;
            }
            #endregion

            #region CEcho request
            if (message.CommandField == DicomCommandField.CEchoRequest)
            {
                server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
                Logger.LogInfo("Received ECHO-RQ message from {0}.", association.CallingAE);
                return;
            }
            #endregion

            #region MWL C-FIND request
            if (message.CommandField == DicomCommandField.CFindRequest)
            {
                Logger.LogInfo("Message Dumped :\n" + message.Dump("", DicomDumpOptions.KeepGroupLengthElements));

                String level = message.DataSet[DicomTags.QueryRetrieveLevel].GetString(0, string.Empty);

                _cancelReceived = false;

                if (message.AffectedSopClassUid.Equals(SopClass.ModalityWorklistInformationModelFindUid))
                {
                    OnReceiveMWLQuery(server, presentationID, message);
                }
                else
                {
                    // Not supported message type, send a failure status.
                    server.SendCFindResponse(presentationID, message.MessageId, new DicomMessage(),
                                             DicomStatuses.QueryRetrieveIdentifierDoesNotMatchSOPClass);
                }
                return;
            }
            #endregion

            //ignore all unsupported request

            server.SendAssociateAbort(DicomAbortSource.ServiceProvider, DicomAbortReason.UnexpectedPDU);
            Logger.LogInfo("Unexpected Command. Send Associate Abort message from server to {0}.", association.CallingAE);
            return;
        }
Esempio n. 13
0
        public StorageFilestreamHandler(DicomScpContext context, ServerAssociationParameters assoc)
        {
            _context = context;
            //_remoteDevice = remoteDevice;
            _importContext = new SopInstanceImporterContext(
                String.Format("{0}_{1}", assoc.CallingAE, assoc.TimeStamp.ToString("yyyyMMddhhmmss")),
                assoc.CallingAE, assoc.CalledAE);

            //if (_remoteDevice != null && _remoteDevice.DeviceTypeEnum.Equals(DeviceTypeEnum.PrimaryPacs))
            //{
            //    _importContext.DuplicateProcessing = DuplicateProcessingEnum.OverwriteSopAndUpdateDatabase;
            //}
        }
Esempio n. 14
0
        private static bool IsMppsEntitycached(ServerAssociationParameters association, string key)
        {
            ListDictionary mppsAssociationList;

            if (_mppsCache.TryGetValue(association.GetHashCode(), out mppsAssociationList))
            {
                return(false);
            }
            else
            {
                return(mppsAssociationList.Contains(key));
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <remarks>
        /// The constructor creates a dictionary of each presentation context negotiated for the
        /// association, and the plugin that will handle it.  This is used later when incoming request
        /// messages are processed.
        /// </remarks>
        /// <param name="server">The server.</param>
        /// <param name="parameters">Association parameters for the negotiated association.</param>
        /// <param name="userParms">User parameters to be passed to the plugins called by the class.</param>
        /// <param name="verifier">Delegate to call to verify an association before its accepted.</param>
        /// <param name="complete">Delegate to call when the association is closed/complete.  Can be null.</param>
        public DicomScpHandler(DicomServer server, ServerAssociationParameters parameters, TContext userParms, DicomScp <TContext> .AssociationVerifyCallback verifier, DicomScp <TContext> .AssociationComplete complete)
        {
            _context  = userParms;
            _verifier = verifier;
            _complete = complete;

            List <IDicomScp <TContext> > scps =
                Platform.Instance.CompositionContainer.GetExportedValues <IDicomScp <TContext> >().Select(scp => scp).
                ToList();

            // First set the user parms for each of the extensions before we do anything with them.
            foreach (object obj in scps)
            {
                IDicomScp <TContext> scp = obj as IDicomScp <TContext>;
                scp.SetContext(_context);
            }

            // Now, create a dictionary with the extension to be used for each presentation context.
            foreach (byte pcid in parameters.GetPresentationContextIDs())
            {
                if (parameters.GetPresentationContextResult(pcid) == DicomPresContextResult.Accept)
                {
                    SopClass       acceptedSop    = SopClass.GetSopClass(parameters.GetAbstractSyntax(pcid).UID);
                    TransferSyntax acceptedSyntax = parameters.GetAcceptedTransferSyntax(pcid);
                    foreach (object obj in scps)
                    {
                        IDicomScp <TContext> scp = obj as IDicomScp <TContext>;

                        IList <SupportedSop> sops = scp.GetSupportedSopClasses();
                        foreach (SupportedSop sop in sops)
                        {
                            if (sop.SopClass.Equals(acceptedSop))
                            {
                                if (sop.SyntaxList.Contains(acceptedSyntax))
                                {
                                    if (!_extensionList.ContainsKey(pcid))
                                    {
                                        _extensionList.Add(pcid, scp);
                                        break;
                                    }
                                    else
                                    {
                                        LogAdapter.Logger.ErrorWithFormat("SOP Class {0} supported by more than one extension", sop.SopClass.Name);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 16
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);
        }
Esempio n. 17
0
        public override bool OnReceiveRequest(DicomServer server, ServerAssociationParameters association, byte presentationId, DicomMessage message)
        {
            try
            {
                var context = new SopInstanceImporterContext(
                    String.Format("{0}_{1}", association.CallingAE, association.TimeStamp.ToString("yyyyMMddhhmmss")),
                    association.CallingAE, association.CalledAE);

                if (Device != null && Device.DeviceTypeEnum.Equals(DeviceTypeEnum.PrimaryPacs))
                {
                    context.DuplicateProcessing = DuplicateProcessingEnum.OverwriteSopAndUpdateDatabase;
                }

                var importer = new SopInstanceImporter(context);
                DicomProcessingResult result = importer.Import(message);

                if (result.Successful)
                {
                    if (!String.IsNullOrEmpty(result.AccessionNumber))
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
                                     result.SopInstanceUid, association.CallingAE, association.CalledAE, result.AccessionNumber,
                                     result.StudyInstanceUid);
                    }
                    else
                    {
                        Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
                                     result.SopInstanceUid, association.CallingAE, association.CalledAE,
                                     result.StudyInstanceUid);
                    }
                }
                else
                {
                    Platform.Log(LogLevel.Warn, "Failure importing sop: {0}", result.ErrorMessage);
                }

                server.SendCStoreResponse(presentationId, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
                return(true);
            }
            catch (DicomDataException ex)
            {
                Platform.Log(LogLevel.Error, ex);
                return(false);  // caller will abort the association
            }
            catch (Exception ex)
            {
                Platform.Log(LogLevel.Error, ex);
                return(false);  // caller will abort the association
            }
        }
Esempio n. 18
0
        void IDicomServerHandler.OnReceiveAssociateRequest(DicomServer server, ServerAssociationParameters association)
        {
            if (_verifier != null)
            {
                DicomRejectResult result;
                DicomRejectReason reason;
                bool verified = _verifier(_context, association, out result, out reason);
                if (verified == false)
                {
                    server.SendAssociateReject(result, DicomRejectSource.ServiceUser, reason);
                    LogAdapter.Logger.Info("Association rejected from {0} to {1}",
                                           association.CallingAE, association.CalledAE);
                    return;
                }
            }

            // Let the extensions have its say on whether a presentation context is really acceptable.
            //
            bool atLeastOneAccepted = false;

            foreach (byte pcid in association.GetPresentationContextIDs())
            {
                if (association.GetPresentationContextResult(pcid) == DicomPresContextResult.Accept)
                {
                    IDicomScp <TContext>   scp = _extensionList[pcid];
                    DicomPresContextResult res = scp.VerifyAssociation(association, pcid);
                    if (res != DicomPresContextResult.Accept)
                    {
                        association.GetPresentationContext(pcid).ClearTransfers();
                        association.SetPresentationContextResult(pcid, res);
                    }
                    else
                    {
                        atLeastOneAccepted = true;
                    }
                }
            }

            if (!atLeastOneAccepted)
            {
                LogAdapter.Logger.Info("None of the proposed presentation context is accepted. Rejecting association from {0} to {1}", association.CallingAE, association.CalledAE);
                server.SendAssociateReject(DicomRejectResult.Permanent, DicomRejectSource.ServiceUser, DicomRejectReason.NoReasonGiven);
                return;
            }

            server.SendAssociateAccept(association);

            // Optimization to speed query performance
            Task.Factory.StartNew(() => LogAdapter.Logger.Info("Received association:\r\n{0}", association.ToString()));
        }
Esempio n. 19
0
        public static void AddPresentationContexts(ServerAssociationParameters assoc, Configuration.SOPClassSet sops)
        {
            byte pcid = assoc.AddPresentationContext(SopClass.VerificationSopClass);

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

            FindMatchingSOPS(sops).ForEach(
                s => {
                pcid = assoc.AddPresentationContext(s);
                SetImageTransferSyntaxes(pcid, assoc);
                log.Info(string.Format("Allow SOP class {0}", s.Name));
            }
                );
        }
Esempio n. 20
0
        public static void StartListening(string aeTitle, int port)
        {
            if (_started)
            {
                return;
            }

            _staticAssocParameters = new ServerAssociationParameters(aeTitle, new IPEndPoint(IPAddress.Any, port));

            AddPresentationContexts(_staticAssocParameters);

            DicomServer.StartListening(_staticAssocParameters,
                                       (server, assoc) => new StorageScp(server, assoc));

            _started = true;
        }
Esempio n. 21
0
        public static void StartListening(string aeTitle, IPAddress ip, int port)
        {
            if (_running)
            {
                return;
            }

            _param = new ServerAssociationParameters(aeTitle, new IPEndPoint(ip, port));

            AddPresentationContexts(_param);

            DicomServer.StartListening(_param,
                                       (server, assoc) => new dcmServer(server, assoc));

            _running = true;
        }
Esempio n. 22
0
        public void OnReceiveAssociateRequest(DicomServer server, ServerAssociationParameters association)
        {
            if (_delayAssociationAccept.Checked)
            {
                Thread.Sleep(TimeSpan.FromSeconds(35));
            }

            if (_rejectAssociation.Checked)
            {
                server.SendAssociateReject(DicomRejectResult.Permanent, DicomRejectSource.ServiceUser, DicomRejectReason.CallingAENotRecognized);
            }
            else
            {
                server.SendAssociateAccept(association);
            }
        }
Esempio n. 23
0
        private static ModalityPerformedProcedureStepIod GetCachedMppsIod(ServerAssociationParameters association, string cacheKeyId)
        {
            ListDictionary mppsAssociationList;

            if (_mppsCache.TryGetValue(association.GetHashCode(), out mppsAssociationList))
            {
                if (mppsAssociationList.Contains(cacheKeyId))
                {
                    return(mppsAssociationList[cacheKeyId] as ModalityPerformedProcedureStepIod);
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
Esempio n. 24
0
        public void OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            if (_type == TestTypes.SendMR)
            {
                var testSet = new DicomAttributeCollection();

                _test.SetupMR(testSet);

                bool same = testSet.Equals(message.DataSet);


                string studyId = message.DataSet[DicomTags.StudyId].GetString(0, "");
                Assert.AreEqual(studyId, "1933");


                DicomUid sopInstanceUid;
                bool     ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);
                if (!ok)
                {
                    server.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.NotSpecified);
                    return;
                }

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.Success);
            }
            else if (_type == TestTypes.Receive)
            {
                DicomUid sopInstanceUid;
                bool     ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);
                if (!ok)
                {
                    server.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.InvalidPDUParameter);
                    return;
                }

                MessagesReceived.Add(message);

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.Success);
            }
            else
            {
                Platform.Log(LogLevel.Error, "Unexpected test type mode");
                server.SendAssociateAbort(DicomAbortSource.ServiceUser, DicomAbortReason.InvalidPDUParameter);
            }
        }
Esempio n. 25
0
        public void ScuAbortTest()
        {
            int port = 2112;

            /* Setup the Server */
            var  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.Receive;
            DicomServer.StartListening(serverParameters, ServerHandlerCreator);

            StorageScu scu = SetupScu();

            IList <DicomAttributeCollection> list = SetupMRSeries(4, 2, DicomUid.GenerateUid().UID);

            foreach (DicomAttributeCollection collection in list)
            {
                var file = new DicomFile("test", new DicomAttributeCollection(), collection)
                {
                    TransferSyntax             = TransferSyntax.ExplicitVrLittleEndian,
                    MediaStorageSopClassUid    = SopClass.MrImageStorage.Uid,
                    MediaStorageSopInstanceUid = collection[DicomTags.SopInstanceUid].ToString()
                };

                scu.AddStorageInstance(new StorageInstance(file));
            }

            scu.ImageStoreCompleted += delegate(object o, StorageInstance instance)
            {
                // Test abort
                scu.Abort();
            };

            scu.Send();
            scu.Join();

            Assert.AreEqual(scu.Status, ScuOperationStatus.NetworkError);

            // StopListening
            DicomServer.StopListening(serverParameters);
        }
Esempio n. 26
0
        public static void StartListening(string aeTitle, int port)
        {
            if (_started)
            {
                return;
            }

            _staticAssocParameters = new ServerAssociationParameters(aeTitle, new IPEndPoint(IPAddress.Any, port));

            Platform.Log(LogLevel.Info, "MPPS Server Started");

            AddPresentationContexts(_staticAssocParameters);

            DicomServer.StartListening(_staticAssocParameters,
                                       delegate(DicomServer server, ServerAssociationParameters assoc)
            {
                return(new MPPSScp(assoc));
            });

            _started = true;
        }
Esempio n. 27
0
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            IDicomScp <TContext> scp = _extensionList[presentationID];

            bool ok = scp.OnReceiveRequest(server, association, presentationID, message);

            if (!ok)
            {
                Platform.Log(LogLevel.Error, "Unexpected error processing message of type {0}.  Aborting association.", message.SopClass.Name);

                server.SendAssociateAbort(DicomAbortSource.ServiceProvider, DicomAbortReason.NotSpecified);
            }
            else if (_complete != null)
            {
                // Only save C-STORE-RQ messages
                if (message.CommandField == DicomCommandField.CStoreRequest)
                {
                    _instances.Add(new StorageInstance(message));
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Store an image into the cache.
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="association"></param>
        /// <param name="message"></param>
        /// <param name="syntax"></param>
        /// <param name="studyInstanceUid"></param>
        /// <param name="seriesInstanceUid"></param>
        /// <param name="sopInstanceUid"></param>
        /// <param name="patientName"></param>
        public static void AddToCache(
            ListenerConfigurationInstance configuration,
            ServerAssociationParameters association,
            DicomMessage message,
            TransferSyntax syntax,
            string studyInstanceUid,
            string seriesInstanceUid,
            string sopInstanceUid,
            string patientName
            )
        {
            var path = CachePathFactory.CreatePath(configuration.Root, configuration.StorageStrategy, message);

            log.Info(string.Format("Cache destination path {0}", path));

            if (File.Exists(path) && !configuration.StorageStrategy.File.Overwrite)
            {
                log.Info("Cache destination exists and storage strategy says don't overwrite!");
                return;
            }

            Directory.CreateDirectory(Path.GetDirectoryName(path));

            var dicomFile = new DicomFile(message, path.ToString())
            {
                TransferSyntaxUid            = syntax.UidString,
                MediaStorageSopInstanceUid   = sopInstanceUid,
                ImplementationClassUid       = DicomImplementation.ClassUID.UID,
                ImplementationVersionName    = DicomImplementation.Version,
                SourceApplicationEntityTitle = association.CallingAE,
                MediaStorageSopClassUid      = message.SopClass.Uid
            };

            // Retrieve a modalityRule action and apply it.
            ModalityRuleFactory.Create(message, configuration).Process(dicomFile);

            log.Info("Saving file");
            dicomFile.Save(DicomWriteOptions.None);
        }
Esempio n. 29
0
        public override bool OnReceiveRequest(DicomServer server,
                                              ServerAssociationParameters association,
                                              byte presentationID, DicomMessage message)
        {
            try
            {
                server.SendCStoreResponse(presentationID, message.MessageId,
                                          message.AffectedSopInstanceUid, DicomStatuses.Success);
            }
            catch (DicomDataException ex)
            {
                LogAdapter.Logger.TraceException(ex);
                return(false); // caller will abort the association
            }
            catch (Exception ex)
            {
                LogAdapter.Logger.TraceException(ex);
                return(false); // caller will abort the association
            }

            return(true);
        }
Esempio n. 30
0
        protected void LoadImportContext(ServerAssociationParameters association)
        {
            _importContext = new DicomReceiveImportContext(association.CallingAE, GetRemoteHostName(association), StudyStore.GetConfiguration(), EventSource.CurrentProcess);

            // Publish new WorkItems as they're added to the context
            lock (_importContext.StudyWorkItemsSyncLock)
            {
                _importContext.StudyWorkItems.ItemAdded += delegate(object sender, DictionaryEventArgs <string, WorkItem> args)
                {
                    Platform.GetService(
                        (IWorkItemActivityMonitorService service) =>
                        service.Publish(new WorkItemPublishRequest
                    {
                        Item = WorkItemDataHelper.FromWorkItem(args.Item)
                    }));


                    var auditedInstances = new AuditedInstances();
                    var request          = args.Item.Request as DicomReceiveRequest;
                    if (request != null)
                    {
                        auditedInstances.AddInstance(request.Patient.PatientId, request.Patient.PatientsName,
                                                     request.Study.StudyInstanceUid);
                    }

                    AuditHelper.LogReceivedInstances(
                        association.CallingAE, GetRemoteHostName(association),
                        auditedInstances, EventSource.CurrentProcess,
                        EventResult.Success, EventReceiptAction.ActionUnknown);
                };

                _importContext.StudyWorkItems.ItemChanged += (sender, args) => Platform.GetService(
                    (IWorkItemActivityMonitorService service) =>
                    service.Publish(new WorkItemPublishRequest {
                    Item = WorkItemDataHelper.FromWorkItem(args.Item)
                }));
            }
        }