Example #1
0
        public override PresentationContextCollection GetPresentationContext( )
        {
            PresentationContextCollection pc = new PresentationContextCollection();
            PresentationContext           p;

            try
            {
                string VerificationClass;

                VerificationClass = DicomUidType.VerificationClass;

                // Check to make sure the Presentation Context isn't already in the collection
                p = FindPresentationContext(VerificationClass, pc);
                if (p == null)
                {
                    p = new PresentationContext();

                    p.AbstractSyntax = VerificationClass;
                    pc.Add(p);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
            return(pc);
        }
Example #2
0
 public static void Send(AbstractDIMSEBase dimse, Association asc, PresentationContext pContext = null)
 {
     if (asc.State != NetworkState.TRANSPORT_CONNECTION_OPEN)
     {
         asc.OutboundMessages.Enqueue(dimse);
         AssociationMessenger.SendRequest(asc, dimse.AffectedSOPClassUID);
     }
     else
     {
         asc.Logger.Log("--> DIMSE" + dimse.GetLogString());
         dimse.LogData(asc);
         var stream = asc.Stream;
         pContext =
             pContext ?? asc.PresentationContexts.First(a => a.AbstractSyntax == dimse.AffectedSOPClassUID);
         var pds = GetPDataTFs(dimse, pContext, asc.UserInfo.MaxPDULength);
         if (pds.Count > 0 && stream.CanWrite)
         {
             foreach (var pd in pds)
             {
                 var message = pd.Write();
                 stream.Write(message, 0, message.Length);
             }
         }
     }
 }
Example #3
0
        /// <summary>
        /// Creates presentation contexts to be used in an A-ASSOCIATE-AC that are based on the
        /// presentation contexts of this instance.
        /// </summary>
        /// <remarks>
        /// The following holds for the returned presentation contexts:
        /// - All requested presentation contexts with an abstract syntax contained in the supplied
        ///   SOP classes will be accepted (have result field 0). The rest will be rejected
        ///   (have result field 3).
        /// - For each accepted requested presentation context, the first proposed transfer syntax
        ///   will be used.
        /// </remarks>
        /// <param name="sopClasses">The SOP Classes to accept.</param>
        /// <returns>The created presentation contexts.</returns>
        public PresentationContextCollection CreatePresentationContextsForAssociateAc(SopClasses sopClasses)
        {
            PresentationContextCollection presentationContextsForAssociateAc = new PresentationContextCollection();

            PresentationContextCollection presentationContexts = PresentationContexts;

            foreach (PresentationContext presentationContextInAssociateRq in presentationContexts)
            {
                String abstractSyntaxInAssociateRq = presentationContextInAssociateRq.AbstractSyntax;

                PresentationContext presentationContextForAssociateAc = null;

                if (sopClasses.List.Contains(abstractSyntaxInAssociateRq))
                {
                    presentationContextForAssociateAc = new PresentationContext
                                                            (presentationContextInAssociateRq.AbstractSyntax,
                                                            0,
                                                            presentationContextInAssociateRq.TransferSyntaxes[0]);
                }
                else
                {
                    presentationContextForAssociateAc = new PresentationContext
                                                            (presentationContextInAssociateRq.AbstractSyntax,
                                                            3,
                                                            "");
                }

                presentationContextForAssociateAc.SetId(presentationContextInAssociateRq.ID);

                presentationContextsForAssociateAc.Add(presentationContextForAssociateAc);
            }

            return(presentationContextsForAssociateAc);
        }
            protected override void Execute()
            {
                PresentationContext pc = new PresentationContext("1.2.840.10008.5.1.4.31", "1.2.840.10008.1.2");

                SendAssociateRq(pc);

                ReceiveAssociateAc();

                Send(cFindMessage);

                while (true)
                {
                    DicomMessage response = ReceiveDicomMessage();

                    Int32 statusVal = Int32.Parse(response.CommandSet.GetValues("0x00000900")[0]);
                    if ((statusVal == 0xff00) || (statusVal == 0xff01))
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }

                SendReleaseRq();

                ReceiveReleaseRp();
            }
Example #5
0
        public PDataTF(DICOMObject dicom, bool isLastItem, bool isCommandObject, PresentationContext context)
            : this()
        {
            byte[] data;
            using (var stream = new MemoryStream())
            {
                using (var dw = new DICOMBinaryWriter(stream))
                {
                    var settings = new DICOMWriteSettings();
                    settings.TransferSyntax = isCommandObject
                        ? TransferSyntax.IMPLICIT_VR_LITTLE_ENDIAN
                        : TransferSyntaxHelper.GetSyntax(context.TransferSyntaxes[0]);
                    DICOMObjectWriter.Write(dw, settings, dicom);
                    data = stream.ToArray();
                }
            }
            var frag = new PDVItemFragment();

            frag.Data            = data;
            frag.IsLastItem      = isLastItem;
            frag.IsCommandObject = isCommandObject;
            var item = new PDVItem();

            item.Fragment = frag;
            item.PresentationContextID = context.Id;
            Items.Add(item);
        }
Example #6
0
        ///// <summary>
        ///// Sends a request for DIMSE association to a DICOM service
        ///// </summary>
        ///// <param name="asc">the underlying association</param>
        ///// <param name="abstractSyntax">the proposed abstract syntaxes (what should the service be able to do)</param>
        public static void SendRequest(Association asc, params string[] abstractSyntaxes)
        {
            var request = new Request
            {
                CalledEntityTitle  = asc.AeTitle,
                CallingEntityTitle = asc.ServiceClass.ApplicationEntity.AeTitle
            };

            abstractSyntaxes.Select((a, i) => new { a, i })
            .ToList()
            .ForEach(a =>
            {
                var pres = new PresentationContext
                {
                    AbstractSyntax   = a.a,
                    Id               = a.i * 2 + 1, //Convention of odd numbers
                    Reason           = PresentationContextReason.ACCEPTANCE,
                    TransferSyntaxes = asc.ServiceClass.SupportedTransferSyntaxes
                };
                request.PresentationContexts.Add(pres);
            });
            asc.PresentationContexts.AddRange(request.PresentationContexts);
            request.UserInfo = new UserInfo();
            asc.Logger.Log("--> " + request);
            asc.SendMessage(request);
            asc.State = NetworkState.ASSOCIATION_ESTABLISHED_WAITING_ON_DATA;
        }
Example #7
0
        public static Message <Accept> ReadAssociationAccept(NetworkBinaryReader dr)
        {
            var acc = new Accept();

            acc.PresentationContexts = new List <PresentationContext>();

            dr.Skip(1); //PDU ID and Reserved Null Byte
            int length = LengthReader.ReadBigEndian(dr.Take(4));

            using (DICOMBinaryReader sub = dr.GetSubStream(length))
            {
                acc.ProtocolVersion = LengthReader.ReadBigEndian(sub, 2);
                sub.Skip(2); //Reserved Null Bytes
                acc.CalledEntityTitle  = sub.ReadString(16).Trim();
                acc.CallingEntityTitle = sub.ReadString(16).Trim();
                sub.Skip(32); //Reserved Null Bytes
                acc.ApplicationContext = ItemReader.ReadApplicationContext(sub);
                while (sub.Peek(1).First() == (byte)ItemType.PRESENTATION_CONTEXT_ACCEPT)
                {
                    PresentationContext context = ItemReader.ReadPresentationCtxAccept(sub);
                    if (context != null)
                    {
                        acc.PresentationContexts.Add(context);
                    }
                }
                acc.UserInfo = ItemReader.ReadUserInfo(sub);
            }
            return(new Message <Accept> {
                Payload = acc, Type = MessageType.PDU
            });
        }
Example #8
0
        public override PresentationContextCollection GetPresentationContext()
        {
            PresentationContextCollection pc = new PresentationContextCollection();
            PresentationContext           p;

            p = new PresentationContext();
            p.AbstractSyntax = DicomUidType.PatientRootQueryFind;
            p.TransferSyntaxList.Add(DicomUidType.ImplicitVRLittleEndian);
            pc.Add(p);

            p = new PresentationContext();
            p.AbstractSyntax = DicomUidType.StudyRootQueryFind;
            p.TransferSyntaxList.Add(DicomUidType.ImplicitVRLittleEndian);
            pc.Add(p);

            p = new PresentationContext();
            p.AbstractSyntax = DicomUidType.StudyRootQueryMove;
            p.TransferSyntaxList.Add(DicomUidType.ImplicitVRLittleEndian);
            pc.Add(p);

            p = new PresentationContext();
            p.AbstractSyntax = DicomUidType.VerificationClass;
            p.TransferSyntaxList.Add(DicomUidType.ImplicitVRLittleEndian);
            pc.Add(p);

            p = new PresentationContext();
            p.AbstractSyntax = DicomUidType.PatientRootQueryMove;
            p.TransferSyntaxList.Add(DicomUidType.ImplicitVRLittleEndian);
            pc.Add(p);

            return(pc);
        }
Example #9
0
        public static Message <Request> ReadAssociationRequest(NetworkBinaryReader dr)
        {
            var rq = new Request();

            rq.PresentationContexts = new List <PresentationContext>();
            dr.Skip(1); //PDU ID and Reserved Null Byte
            int length = LengthReader.ReadBigEndian(dr.Take(4));

            using (DICOMBinaryReader sub = dr.GetSubStream(length))
            {
                rq.ProtocolVersion = LengthReader.ReadBigEndian(sub, 2);
                sub.Skip(2); //Reserved Null Bytes
                rq.CalledEntityTitle  = sub.ReadString(16).Trim();
                rq.CallingEntityTitle = sub.ReadString(16).Trim();
                sub.Skip(32); //Reserved Null Bytes
                rq.ApplicationContext = ItemReader.ReadApplicationContext(sub);
                while (sub.Peek(1)[0] == (byte)ItemType.PRESENTATION_CONTEXT_REQUEST)
                {
                    PresentationContext context = ItemReader.ReadPresentationCtxRequest(sub);
                    rq.PresentationContexts.Add(context);
                }
                rq.UserInfo = ItemReader.ReadUserInfo(sub);
            }
            return(new Message <Request> {
                Payload = rq, Type = MessageType.PDU
            });
        }
Example #10
0
        /// <summary>
        /// Trigger the Client to send a Verification (DICOM C-ECHO-RQ).
        /// </summary>
        /// <param name="actorName">Destination Actor Name.</param>
        /// <returns>Boolean indicating success or failure.</returns>
        public bool TriggerClientVerification(ActorName actorName)
        {
            // Set up a Verification SOP Class - C-ECHO-RQ trigger
            DicomTrigger dicomTrigger = new DicomTrigger(Dvtk.IheActors.Bases.TransactionNameEnum.RAD_UNKNOWN);

            dicomTrigger.AddItem(new DicomMessage(DvtkData.Dimse.DimseCommand.CECHORQ),
                                 HliScp.VERIFICATION_SOP_CLASS_UID,
                                 HliScp.IMPLICIT_VR_LITTLE_ENDIAN);
            DicomTriggerItem dicomTriggerItem = dicomTrigger.TriggerItems[0];

            // thread must wait for association completion
            _scu.SignalCompletion = true;

            // set up the presentation context from the trigger
            PresentationContext[] presentationContexts = new PresentationContext[1];
            presentationContexts[0] = new PresentationContext(dicomTriggerItem.SopClassUid,
                                                              dicomTriggerItem.TransferSyntaxes);
            _scu.TriggerSendAssociation(dicomTriggerItem.Message, presentationContexts);

            // wait for association completion
            // - timeout of 0 means "no timeout".
            _semaphore.Wait(0);

            // return a boolean indicating if the trigger was processed successfully or not
            return(_scu.ProcessTriggerResult);
        }
Example #11
0
 public static void Send(AbstractDIMSEBase dimse, Association asc, PresentationContext pContext = null)
 {
     if (asc.State != NetworkState.TRANSPORT_CONNECTION_OPEN)
     {
         asc.OutboundMessages.Enqueue(dimse);
         AssociationMessenger.SendRequest(asc, dimse.AffectedSOPClassUID);
     }
     else if (!asc.IsClientConnected)
     {
         //Connection lost
         asc.Logger.Log("TCP connection has been lost. Ending association");
     }
     else
     {
         asc.Logger.Log("--> DIMSE" + dimse.GetLogString());
         dimse.LogData(asc);
         pContext = pContext ?? asc.PresentationContexts.First(a => a.AbstractSyntax == dimse.AffectedSOPClassUID);
         var maxPDU = asc.UserInfo.MaxPDULength;
         WriteDimseToStream(dimse, asc.Stream, pContext, maxPDU);
         if (dimse is AbstractDIMSEResponse && !(dimse is NEventReportResponse))
         {
             asc.State = NetworkState.AWAITING_RELEASE;
         }
         else if (dimse is NEventReportResponse)
         {
             AssociationMessenger.SendReleaseRequest(asc);
         }
         else
         {
             asc.State = NetworkState.ASSOCIATION_ESTABLISHED_WAITING_ON_DATA;
         }
     }
 }
Example #12
0
        private PresentationContext[] SetPresentationContexts(DicomTrigger dicomTrigger)
        {
            DicomTriggerItemCollection localTriggerItems = new DicomTriggerItemCollection();

            // use the local trigger items to establish a list of presentation contexts that
            // only appear once
            foreach (DicomTriggerItem triggerItem in dicomTrigger.TriggerItems)
            {
                if (localTriggerItems.FindMatchingPresentationContext(triggerItem) == false)
                {
                    localTriggerItems.Add(triggerItem);
                }
            }

            // now set up the returned presentation contexts from the local trigger collection
            PresentationContext[] presentationContexts = new PresentationContext[localTriggerItems.Count];
            int index = 0;

            foreach (DicomTriggerItem triggerItem in localTriggerItems)
            {
                // save the presentation context
                presentationContexts[index++] = new PresentationContext(triggerItem.SopClassUid,
                                                                        MergeTransferSyntaxes(triggerItem.TransferSyntaxes));
            }

            return(presentationContexts);
        }
 /// <summary>
 /// Constructor that initialized this instance with a DvtkData AcceptedPresentationContextList.
 /// </summary>
 /// <param name="dvtkDataAcceptedPresentationContextList">The DvtkData AcceptedPresentationContextList.</param>
 internal PresentationContextCollection(DvtkData.Dul.AcceptedPresentationContextList dvtkDataAcceptedPresentationContextList)
 {
     foreach (DvtkData.Dul.AcceptedPresentationContext dvtkDataAcceptedPresentationContext in dvtkDataAcceptedPresentationContextList)
     {
         PresentationContext presentationContext = new PresentationContext(dvtkDataAcceptedPresentationContext);
         Add(presentationContext);
     }
 }
Example #14
0
        /// <summary>
        /// Class constructor.
        /// </summary>
        /// <param name="parentActor">Parent Actor Name - containing actor.</param>
        /// <param name="actorName">Destination Actor Name.</param>
        public DicomStorageCommitClient(BaseActor parentActor, ActorName actorName)
            : base(parentActor, actorName, true)
        {
            _presentationContexts = new PresentationContext[1];

            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.1.20.1", // Abstract Syntax Name
                "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
            _presentationContexts[0] = presentationContext;
        }
Example #15
0
        protected override List <PresentationContext> GetPresentationContexts()
        {
            List <PresentationContext> contexts = base.GetPresentationContexts();
            PresentationContext        pc       = new PresentationContext(NActionScu.PatientUpdateClass);

            pc.TransferSyntaxes.Add(DicomUidType.ImplicitVRLittleEndian);
            contexts.Add(pc);
            return(contexts);
        }
Example #16
0
        public DicomQueryRetrieveClient(BaseActor parentActor, ActorNameEnum actorName)
            : base(parentActor, actorName)
        {
            _presentationContexts = new PresentationContext[1];

            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.3.1.2.3.3", // Abstract Syntax Name
                "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
            _presentationContexts[0] = presentationContext;
        }
Example #17
0
        public DicomStorageClient(BaseActor parentActor, ActorNameEnum actorName) : base(parentActor, actorName)
        {
            _presentationContexts = new PresentationContext[1];

            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.3.1.2.3.3", // Abstract Syntax Name
                                                                              "1.2.840.10008.1.2");      // Transfer Syntax Name(s)

            _presentationContexts[0] = presentationContext;
        }
Example #18
0
        /// <summary>
        /// Class constructor.
        /// </summary>
        /// <param name="parentActor">Parent Actor Name - containing actor.</param>
        /// <param name="actorName">Destination Actor Name.</param>
        public DicomWorklistClient(BaseActor parentActor, ActorName actorName)
            : base(parentActor, actorName, false)
        {
            _presentationContexts = new PresentationContext[1];

            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.5.1.4.31", // Abstract Syntax Name
                                                                              "1.2.840.10008.1.2");     // Transfer Syntax Name(s)

            _presentationContexts[0] = presentationContext;
        }
Example #19
0
        /// <summary>
        /// Class constructor.
        /// </summary>
        /// <param name="parentActor">Parent Actor Name - containing actor.</param>
        /// <param name="actorName">Destination Actor Name.</param>
        public DicomStorageClient(BaseActor parentActor, ActorName actorName)
            : base(parentActor, actorName, false)
        {
            _presentationContexts = new PresentationContext[1];

            String[] transferSyntaxes = new String[1];
            transferSyntaxes[0] = "1.2.840.10008.1.2"; // Transfer Syntax Name(s)
            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.5.1.4.1.1.7", // Abstract Syntax Name
                transferSyntaxes);
            _presentationContexts[0] = presentationContext;
        }
Example #20
0
        /// <summary>
        /// Class constructor.
        /// </summary>
        /// <param name="parentActor">Parent Actor Name - containing actor.</param>
        /// <param name="actorName">Destination Actor Name.</param>
        public DicomStorageClient(BaseActor parentActor, ActorName actorName)
            : base(parentActor, actorName, false)
        {
            _presentationContexts = new PresentationContext[1];

            String[] transferSyntaxes = new String[1];
            transferSyntaxes[0] = "1.2.840.10008.1.2";                                                     // Transfer Syntax Name(s)
            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.5.1.4.1.1.7", // Abstract Syntax Name
                                                                              transferSyntaxes);

            _presentationContexts[0] = presentationContext;
        }
        /// <summary>
        /// Constructor with initialization. Shallow copy.
        /// </summary>
        /// <param name="arrayOfValues">Values to copy.</param>
        /// <exception cref="System.ArgumentNullException"><paramref name="arrayOfValues"/> is null.</exception>
        public PresentationContextCollection(PresentationContext[] arrayOfValues)
        {
            if (arrayOfValues == null)
            {
                throw new ArgumentNullException();
            }

            foreach (PresentationContext value in arrayOfValues)
            {
                this.Add(value);
            }
        }
Example #22
0
        public void MyDelegate(MyParameters p)
        {
            Leadtools.AddIn.StorageCommit.StorageCommit commit = new Leadtools.AddIn.StorageCommit.StorageCommit();
            DicomRequest request = new DicomRequest(p._client);

            this.AddCommitItem(p._ds, DicomTag.ReferencedPerformedProcedureStepSequence, commit);
            this.AddCommitItem(p._ds, DicomTag.ReferencedSOPSequence, commit);
            foreach (StorageCommitItem item in commit.Items)
            {
                string          sql = string.Format("SELECT * FROM Images WHERE SOPInstanceUID = '{0}'", item.SOPInstanceUID);
                SqlCeDataReader r   = SqlCeHelper.ExecuteReader(p._connectionString, sql);
                if (r.Read())
                {
                    if (r["SOPClassUID"].ToString() == item.SOPClassUID)
                    {
                        string referencedFile = r["referencedFile"].ToString();
                        if (File.Exists(referencedFile))
                        {
                            item.Status = DicomCommandStatusType.Success;
                        }
                        else
                        {
                            item.Status = DicomCommandStatusType.NoSuchObjectInstance;
                        }
                    }
                    else
                    {
                        item.Status = DicomCommandStatusType.ClaseInstanceConflict;
                    }
                    item.StudyInstanceUID = r["StudyInstanceUID"].ToString();
                }
                else
                {
                    item.Status = DicomCommandStatusType.NoSuchObjectInstance;
                }
                r.Close();
            }
            DicomDataSet        commitDS = BuildDataset(p._client, commit, p.ServerAE);
            PresentationContext pc       = new PresentationContext();

            pc.AbstractSyntax = DicomUidType.StorageCommitmentPushModelClass;
            pc.TransferSyntaxes.Add(DicomUidType.ImplicitVRLittleEndian);
            request.PresentationContexts.Add(pc);
            request.RequireMessagePump = true;

            request.ReceiveNReportResponse += new ReceiveNReportResponseDelegate(request_ReceiveNReportResponse);
            request.ConnectType             = ConnectType.Conditional;

            _DicomRequest.SendNReportRequest(request, p._presentationId, p._messageId, DicomUidType.StorageCommitmentPushModelClass,
                                             DicomUidType.StorageCommitmentPushModelInstance,
                                             commit.FailedCount > 0 ? 2 : 1, commitDS);
        }
Example #23
0
        public PDataTF(byte[] data, bool isLastItem, bool isCommandObject, PresentationContext context)
            : this()
        {
            var frag = new PDVItemFragment();

            frag.Data            = data;
            frag.IsLastItem      = isLastItem;
            frag.IsCommandObject = isCommandObject;
            var item = new PDVItem();

            item.Fragment = frag;
            item.PresentationContextID = context.Id;
            Items.Add(item);
        }
Example #24
0
        public void ReadWriteDIMSETest()
        {
            using (var stream = new MemoryStream())
            {
                //Generate a DIMSE
                var dimse    = CFind.CreateStudyQuery("123456");
                var pContext = new PresentationContext()
                {
                    AbstractSyntax   = AbstractSyntax.STUDY_FIND,
                    TransferSyntaxes = new List <string>()
                    {
                        TransferSyntaxHelper.IMPLICIT_VR_LITTLE_ENDIAN
                    }
                };

                PDataMessenger.WriteDimseToStream(dimse, stream, pContext);

                //Wrap stream in buffer to get to network stream
                using (var bs = new BufferedStream(stream))
                {
                    bs.Position = 0;
                    var net = new NetworkBinaryReader(bs);

                    var           pdata = PDataProcessor.ReadPDataTFs(net);
                    var           dcm   = PDataProcessor.GetCommandObject(pdata);
                    AbstractDIMSE dimseRead;
                    var           success = DIMSEReader.TryReadDIMSE(dcm, out dimseRead);

                    Assert.AreEqual(dimse.Elements.Count, dimseRead.Elements.Count);

                    for (int i = 0; i < dimse.Elements.Count; i++)
                    {
                        var el1 = dimse.Elements[i];
                        var el2 = dimseRead.Elements[i];
                        Assert.AreEqual(el1.Tag, el2.Tag);
                        Assert.AreEqual(el1.DData, el2.DData);
                    }

                    //Make sure this DIMSE was written with data
                    Assert.IsTrue(dimse.HasData);

                    //REad the data
                    var dataPds = PDataProcessor.ReadPDataTFs(net);
                    var data    = PDataProcessor.GetDataObject(dataPds, TransferSyntax.IMPLICIT_VR_LITTLE_ENDIAN);

                    DICOMAssert.AreEqual(data, dimse.Data);
                }
            }
        }
Example #25
0
        //override this function to include your abstract class (the custom message we created) in the association
        protected override List <PresentationContext> GetPresentationContexts()
        {
            List <PresentationContext> presentations;
            PresentationContext        customPresentation;

            presentations      = base.GetPresentationContexts();
            customPresentation = new PresentationContext(CustomUID.DownloadImagesClass);

            customPresentation.TransferSyntaxes.Add(DicomUidType.ExplicitVRBigEndian);
            customPresentation.TransferSyntaxes.Add(DicomUidType.ImplicitVRLittleEndian);

            presentations.Add(customPresentation);

            return(presentations);
        }
Example #26
0
        /// <summary>
        /// Creates presentation contexts to be used in an A-ASSOCIATE-AC that are based on the
        /// presentation contexts of this instance.
        /// </summary>
        /// <remarks>
        /// The following holds for the returned presentation contexts:<br></br>
        /// - All requested presentation contexts with an abstract syntax not contained in the supplied
        ///   SOP classes will be rejected (have result field 3).<br></br>
        /// - For each other requested presentation contex that has an abstract syntax contained in
        ///   the supplied SOP classes, do the following:<br></br>
        ///   1)<br></br>
        ///   Check if one or more of the requested transfer syntaxes is present in the first supplied
        ///   TransferSyntaxes instance. If this is the case, use the requested transfer syntax that is
        ///   requested before the other ones in the accepted presentation context counterpart (has
        ///   result field 0).<br></br>
        ///   2)<br></br>
        ///   If no requested transfer syntaxes was present, try this with the second supplied
        ///   TransferSyntaxes instance.<br></br>
        ///   3) If no requested transfer syntaxes was present is in any supplied TransferSyntaxes
        ///   instance, reject the presentation context with result 4.<br></br>
        ///
        ///   Note that a difference exists between supplying one TransferSyntaxes instance with all
        ///   transfer syntaxes to accept and supplying multiple TransferSyntaxes instances each containing
        ///   only one transfer syntax. In the first case, the preference (order of proposed transfer
        ///   syntaxes) of the SCU will be used, in the second case the preference of the caller of this
        ///   method will be used.
        /// </remarks>
        /// <param name="sopClasses">The SOP Classes to accept.</param>
        /// <param name="transferSyntaxesList">The transfer syntaxes to accept.</param>
        /// <returns>The created presentation contexts.</returns>
        public PresentationContextCollection CreatePresentationContextsForAssociateAc(SopClasses sopClasses, params TransferSyntaxes[] transferSyntaxesList)
        {
            PresentationContextCollection presentationContextsForAssociateAc = new PresentationContextCollection();

            PresentationContextCollection presentationContexts = PresentationContexts;

            foreach (PresentationContext presentationContextInAssociateRq in presentationContexts)
            {
                String abstractSyntaxInAssociateRq = presentationContextInAssociateRq.AbstractSyntax;

                PresentationContext presentationContextForAssociateAc = null;

                if (sopClasses.List.Contains(abstractSyntaxInAssociateRq))
                {
                    String transferSyntaxForAssociateAc = DetermineTransferSyntaxToAccept
                                                              (presentationContextInAssociateRq.TransferSyntaxes,
                                                              transferSyntaxesList);

                    if (transferSyntaxForAssociateAc.Length == 0)
                    {
                        presentationContextForAssociateAc = new PresentationContext
                                                                (presentationContextInAssociateRq.AbstractSyntax,
                                                                4,
                                                                "");
                    }
                    else
                    {
                        presentationContextForAssociateAc = new PresentationContext
                                                                (presentationContextInAssociateRq.AbstractSyntax,
                                                                0,
                                                                transferSyntaxForAssociateAc);
                    }
                }
                else
                {
                    presentationContextForAssociateAc = new PresentationContext
                                                            (presentationContextInAssociateRq.AbstractSyntax,
                                                            3,
                                                            "");
                }

                presentationContextForAssociateAc.SetId(presentationContextInAssociateRq.ID);

                presentationContextsForAssociateAc.Add(presentationContextForAssociateAc);
            }

            return(presentationContextsForAssociateAc);
        }
Example #27
0
 public static void Send(AbstractDIMSEBase dimse, Association asc, PresentationContext pContext = null)
 {
     if (asc.State != NetworkState.TRANSPORT_CONNECTION_OPEN)
     {
         asc.OutboundMessages.Enqueue(dimse);
         AssociationMessenger.SendRequest(asc, dimse.AffectedSOPClassUID);
     }
     else
     {
         asc.Logger.Log("--> DIMSE" + dimse.GetLogString());
         dimse.LogData(asc);
         pContext = pContext ?? asc.PresentationContexts.First(a => a.AbstractSyntax == dimse.AffectedSOPClassUID);
         var maxPDU = asc.UserInfo.MaxPDULength;
         WriteDimseToStream(dimse, asc.Stream, pContext, maxPDU);
     }
 }
Example #28
0
        public void GetChunksTest()
        {
            //Generate a DIMSE
            var dimse    = CFind.CreateStudyQuery("123456");
            var pContext = new PresentationContext()
            {
                AbstractSyntax   = AbstractSyntax.STUDY_FIND,
                TransferSyntaxes = new List <string>()
                {
                    TransferSyntaxHelper.IMPLICIT_VR_LITTLE_ENDIAN
                }
            };

            var bytes  = PDataMessenger.GetChunks(dimse.Data, 16534, pContext);
            var bytes1 = bytes[0];
            var dcm    = DICOMObject.Read(bytes1);

            DICOMAssert.AreEqual(dcm, dimse.Data);
        }
Example #29
0
        public static List <PDataTF> GetPDataTFs(AbstractDIMSEBase dimse, PresentationContext pContext, int maxPDULength = 16384)
        {
            var list       = new List <PDataTF>();
            var commandEls = dimse.Elements;

            list.Add(new PDataTF(new DICOMObject(dimse.Elements), true, true, pContext));

            var dataDIMSE = dimse as AbstractDIMSE;

            if (dataDIMSE != null && dataDIMSE.Data != null)
            {
                List <byte[]> chunks = GetChunks(dataDIMSE.Data, maxPDULength, pContext);
                chunks
                .Select((c, i) => new PDataTF(c, i == chunks.Count - 1, false, pContext))
                .ToList()
                .ForEach(list.Add);
            }
            return(list);
        }
Example #30
0
        //
        // - Methods -
        //

        /// <summary>
        /// Creates presentation contexts to be used in an A-ASSOCIATE-AC that are based on the
        /// presentation contexts of this instance.
        /// </summary>
        /// <remarks>
        /// The following holds for the returned presentation contexts:
        /// - All requested presentation contexts will be accepted (have result field 0).
        /// - For each requested presentation context, the first proposed transfer syntax will be used.
        /// </remarks>
        /// <returns>The created presentation contexts.</returns>
        public PresentationContextCollection CreatePresentationContextsForAssociateAc()
        {
            PresentationContextCollection presentationContextsForAssociateAc = new PresentationContextCollection();

            PresentationContextCollection presentationContexts = PresentationContexts;

            foreach (PresentationContext presentationContextInAssociateRq in presentationContexts)
            {
                PresentationContext presentationContextForAssociateAc = new PresentationContext
                                                                            (presentationContextInAssociateRq.AbstractSyntax,
                                                                            0,
                                                                            presentationContextInAssociateRq.TransferSyntaxes[0]);

                presentationContextForAssociateAc.SetId(presentationContextInAssociateRq.ID);

                presentationContextsForAssociateAc.Add(presentationContextForAssociateAc);
            }

            return(presentationContextsForAssociateAc);
        }
Example #31
0
File: SCU.cs Project: ewcasas/DVTK
 public SendAssociationTrigger(DicomMessageCollection dicomMessageCollection, PresentationContext[] presentationContexts)
 {
     this.dicomMessageCollection = dicomMessageCollection;
     this.presentationContexts = presentationContexts;
     this.returnValue = true;
 }
 /// <summary>
 /// Inserts an item to the IList at the specified position.
 /// </summary>
 /// <param name="index">The zero-based index at which <c>value</c> should be inserted. </param>
 /// <param name="value">The item to insert into the <see cref="System.Collections.IList"/>.</param>
 public void Insert(int index, PresentationContext value)
 {
     base.Insert(index, value);
 }
 /// <summary>
 /// Removes the first occurrence of a specific item from the IList.
 /// </summary>
 /// <param name="value">The item to remove from the <see cref="System.Collections.IList"/>.</param>
 public void Remove(PresentationContext value)
 {
     base.Remove(value);
 }
Example #34
0
        private void buttonEcho_Click(object sender, System.EventArgs e)
        {
            //isStorageEcho = true;
            labelStorageEcho.Text = "";
            toolBarButtonResult.Enabled = false;

            if ((textBoxStorageSCPIPAdd.Text == null) || (textBoxStorageSCPIPAdd.Text.Length == 0))
            {
                MessageBox.Show("Pl Specify SCP IP Address.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Update DVT & SUT settings
            this.storageOptions.RemoteAeTitle = textBoxStorageSCPAETitle.Text;
            this.storageOptions.RemoteHostName = textBoxStorageSCPIPAdd.Text;
            this.storageOptions.RemotePort = UInt16.Parse(textBoxStorageSCPPort.Text);
            this.storageOptions.LocalAeTitle = textBoxSCUAETitle.Text;
            this.storageOptions.ResultsDirectory = validationResultsFileGroup.Directory;

            SCU echoScu = new SCU();

            if (isStopped)
            {
                this.overviewThread = new OverviewThread();
                this.overviewThread.Initialize(threadManager);
                this.overviewThread.Options.ResultsDirectory = validationResultsFileGroup.Directory;
                this.overviewThread.Options.Identifier = "Storage_SCU_Emulator";
                this.overviewThread.Options.AttachChildsToUserInterfaces = true;
                this.overviewThread.Options.LogThreadStartingAndStoppingInParent = false;
                this.overviewThread.Options.LogWaitingForCompletionChildThreads = false;

                this.userControlActivityLogging.Attach(overviewThread);

                String resultsFileName = "StoreSCUEmulator_" + System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
                this.overviewThread.Options.ResultsFileNameOnlyWithoutExtension = resultsFileName;

                //
                // Start the Dicom Overview Thread
                //
                this.overviewThread.Start();
                isStopped = false;
            }

            echoScu.Initialize(this.overviewThread);
            echoScu.Options.DeepCopyFrom(this.storageOptions);

            String resultsFileBaseName = "StoreSCUEcho_" + System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
            echoScu.Options.ResultsFileNameOnlyWithoutExtension = resultsFileBaseName;
            echoScu.Options.Identifier = resultsFileBaseName;

            echoScu.Options.LogThreadStartingAndStoppingInParent = false;
            echoScu.Options.LogWaitingForCompletionChildThreads = false;
            echoScu.Options.AutoValidate = false;

            echoScu.Options.ResultsDirectory = this.storageOptions.ResultsDirectory;

            echoScu.Options.LocalAeTitle = textBoxSCUAETitle.Text;

            echoScu.Options.RemoteAeTitle = textBoxStorageSCPAETitle.Text;
            echoScu.Options.RemotePort = UInt16.Parse(textBoxStorageSCPPort.Text);
            echoScu.Options.RemoteHostName = textBoxStorageSCPIPAdd.Text;

            //this.userControlActivityLogging.Attach(echoScu);

            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.1.1", // Abstract Syntax Name
                                                                            "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
            PresentationContext[] presentationContexts = new PresentationContext[1];
            presentationContexts[0] = presentationContext;

            DicomMessage echoMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CECHORQ);

            echoScu.Start();

            bool sendResult = echoScu.TriggerSendAssociationAndWait(echoMessage, presentationContexts);

            if (!sendResult)
            {
                labelStorageEcho.Text = "DICOM Echo failed (See logging for details)";
            }
            else
                labelStorageEcho.Text = "DICOM Echo successful";

            echoScu.Stop();

            toolBarButtonResult.Enabled = true;
        }
 /// <summary>
 /// Determines the index of a specific item in the <see cref="System.Collections.IList"/>.
 /// </summary>
 /// <param name="value">The item to locate in the <see cref="System.Collections.IList"/>.</param>
 /// <returns>The index of <c>value</c> if found in the list; otherwise, -1.</returns>
 public int IndexOf(PresentationContext value)
 {
     return base.IndexOf(value);
 }
 public PresentationService(PresentationContext presentationContext)
 {
     _presentationContext = presentationContext;
 }
Example #37
0
 public QuestionService(PresentationContext context)
 {
     _context = context;
 }
Example #38
0
        //
        // - Methods -
        //
        /// <summary>
        /// Creates presentation contexts to be used in an A-ASSOCIATE-AC that are based on the
        /// presentation contexts of this instance.
        /// </summary>
        /// <remarks>
        /// The following holds for the returned presentation contexts:
        /// - All requested presentation contexts will be accepted (have result field 0).
        /// - For each requested presentation context, the first proposed transfer syntax will be used.
        /// </remarks>
        /// <returns>The created presentation contexts.</returns>
        public PresentationContextCollection CreatePresentationContextsForAssociateAc()
        {
            PresentationContextCollection presentationContextsForAssociateAc = new PresentationContextCollection();

            PresentationContextCollection presentationContexts = PresentationContexts;

            foreach(PresentationContext presentationContextInAssociateRq in presentationContexts)
            {
                PresentationContext presentationContextForAssociateAc = new PresentationContext
                    (presentationContextInAssociateRq.AbstractSyntax,
                     0,
                     presentationContextInAssociateRq.TransferSyntaxes[0]);

                presentationContextForAssociateAc.SetId(presentationContextInAssociateRq.ID);

                presentationContextsForAssociateAc.Add(presentationContextForAssociateAc);
            }

            return(presentationContextsForAssociateAc);
        }
Example #39
0
        private bool HandleSubOperation(System.String moveDestinationAE, System.String dcmFilename, int subOperationIndex)
        {
            SCU storageScu = new SCU(true);

            storageScu.Initialize(DicomThread.ThreadManager);

            storageScu.Options.Identifier = "StorageSubOperationAsScu";

            if (DicomThread.Options.StartAndEndResultsGathering == true)
            {
                storageScu.Options.StartAndEndResultsGathering = true;
                storageScu.Options.ResultsFilePerAssociation = false;

                System.String filenameFormat = DicomThread.Options.ResultsFileName.Replace("_res", "_StorageSubOperationAsScu{0}_res");
                System.String resultsFilename = String.Format(filenameFormat, subOperationIndex);
                storageScu.Options.ResultsFileName = resultsFilename;
                storageScu.Options.ResultsDirectory = DicomThread.Options.ResultsDirectory;

                System.String message = String.Format("StorageSubOperation filename: {0}", storageScu.Options.ResultsDirectory + "Detail_" + storageScu.Options.ResultsFileName);
                DicomThread.WriteInformation(message);
            }
            else
            {
                storageScu.Options.StartAndEndResultsGathering = false;
            }

            storageScu.Options.DvtAeTitle = DicomThread.Options.DvtAeTitle;
            storageScu.Options.DvtPort = DicomThread.Options.DvtPort;

            storageScu.Options.SutAeTitle = moveDestinationAE;
            storageScu.Options.SutPort = DicomThread.Options.SutPort;
            storageScu.Options.SutIpAddress = DicomThread.Options.SutIpAddress;

            storageScu.Options.DataDirectory = DicomThread.Options.DataDirectory;
            storageScu.Options.StorageMode = Dvtk.Sessions.StorageMode.AsDataSet;

            //			foreach (System.String filename in config.DefinitionFiles)
            //			{
            //				storageScu.Options.LoadDefinitionFile(filename);
            //			}

            System.String sopClassUid = "1.2.840.10008.5.1.4.1.1.7";
            PresentationContext presentationContext
                = new PresentationContext(sopClassUid, // Abstract Syntax Name
                                        "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
            PresentationContext[] presentationContexts = new PresentationContext[1];
            presentationContexts[0] = presentationContext;

            DicomMessage storageMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CSTORERQ);
            storageMessage.DataSet.Read(dcmFilename, storageScu);

            storageScu.NonThreadedStart();

            bool sendResult = false;
            try
            {
                sendResult = storageScu.SendAssociation(storageMessage, presentationContexts);
            }
            catch (System.Exception)
            {
                DicomThread.WriteError("Storage Sub-Operation As SCU Failed");
            }
            finally
            {
                storageScu.NonThreadedStop();
            }

            return sendResult;
        }
            protected override void Execute()
            {
                PresentationContext pc = new PresentationContext("1.2.840.10008.5.1.4.31", "1.2.840.10008.1.2");

                SendAssociateRq(pc);

                ReceiveAssociateAc();

                Send(cFindMessage);

                while (true)
                {
                    DicomMessage response = ReceiveDicomMessage();

                    Int32 statusVal = Int32.Parse(response.CommandSet.GetValues("0x00000900")[0]);
                    if ((statusVal == 0xff00) || (statusVal == 0xff01))
                    {
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }

                SendReleaseRq();

                ReceiveReleaseRp();
            }
Example #41
0
        private void buttonCommitEcho_Click(object sender, System.EventArgs e)
        {
            labelEcho.Text = "";

            if ((textBoxStorageCommitIPAdd.Text == null) || (textBoxStorageCommitIPAdd.Text.Length == 0))
            {
                MessageBox.Show("Pl Specify SCP IP Address.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            SCU storageScu = new SCU();

            storageScu.Initialize(this.threadManager);

            storageScu.Options.Identifier = "CommitSCPEchoMessage";

            storageScu.Options.ResultsFileNameOnlyWithoutExtension = "CommitSCPCEcho_" + System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
            storageScu.Options.ResultsDirectory = this.storageOptions.ResultsDirectory;

            storageScu.Options.LocalAeTitle = textBoxCommitSCPAETitle.Text;

            storageScu.Options.RemoteAeTitle = textBoxStorageCommitAETitle.Text;
            storageScu.Options.RemotePort = UInt16.Parse(textBoxStorageCommitPort.Text);
            storageScu.Options.RemoteHostName = textBoxStorageCommitIPAdd.Text;
            storageScu.Options.AutoValidate = false;
            this.userControlActivityLogging.Attach(storageScu);

            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.1.1", // Abstract Syntax Name
                                                                            "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
            PresentationContext[] presentationContexts = new PresentationContext[1];
            presentationContexts[0] = presentationContext;

            DicomMessage echoMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CECHORQ);

            storageScu.Start();

            bool sendResult = storageScu.TriggerSendAssociationAndWait(echoMessage, presentationContexts);

            if (!sendResult)
            {
                labelEcho.Text = "DICOM Echo failed (See logging for details)";
            }
            else
                labelEcho.Text = "DICOM Echo successful";

            storageScu.Stop();
        }
Example #42
0
        /// <summary>
        /// Creates presentation contexts to be used in an A-ASSOCIATE-AC that are based on the
        /// presentation contexts of this instance.
        /// </summary>
        /// <remarks>
        /// The following holds for the returned presentation contexts:
        /// - All requested presentation contexts with an abstract syntax contained in the supplied
        ///   SOP classes will be accepted (have result field 0). The rest will be rejected
        ///   (have result field 3).
        /// - For each accepted requested presentation context, the first proposed transfer syntax 
        ///   will be used.
        /// </remarks>
        /// <param name="sopClasses">The SOP Classes to accept.</param>
        /// <returns>The created presentation contexts.</returns>
        public PresentationContextCollection CreatePresentationContextsForAssociateAc(SopClasses sopClasses)
        {
            PresentationContextCollection presentationContextsForAssociateAc = new PresentationContextCollection();

            PresentationContextCollection presentationContexts = PresentationContexts;

            foreach(PresentationContext presentationContextInAssociateRq in presentationContexts)
            {
                String abstractSyntaxInAssociateRq = presentationContextInAssociateRq.AbstractSyntax;

                PresentationContext presentationContextForAssociateAc = null;

                if (sopClasses.List.Contains(abstractSyntaxInAssociateRq))
                {
                    presentationContextForAssociateAc = new PresentationContext
                        (presentationContextInAssociateRq.AbstractSyntax,
                         0,
                         presentationContextInAssociateRq.TransferSyntaxes[0]);
                }
                else
                {
                    presentationContextForAssociateAc = new PresentationContext
                        (presentationContextInAssociateRq.AbstractSyntax,
                         3,
                         "");
                }

                presentationContextForAssociateAc.SetId(presentationContextInAssociateRq.ID);

                presentationContextsForAssociateAc.Add(presentationContextForAssociateAc);
            }

            return(presentationContextsForAssociateAc);
        }
Example #43
0
        /// <summary>
        /// Creates presentation contexts to be used in an A-ASSOCIATE-AC that are based on the
        /// presentation contexts of this instance.
        /// </summary>
        /// <remarks>
        /// The following holds for the returned presentation contexts:<br></br>
        /// - For each requested presentation contex, do the following:<br></br>
        ///   1)<br></br>
        ///   Check if one or more of the requested transfer syntaxes is present in the first supplied
        ///   TransferSyntaxes instance. If this is the case, use the requested transfer syntax that is
        ///   requested before the other ones in the accepted presentation context counterpart (has
        ///   result field 0).<br></br>
        ///   2)<br></br>
        ///   If no requested transfer syntaxes was present, try this with the second supplied
        ///   TransferSyntaxes instance.<br></br>
        ///   3) If no requested transfer syntaxes was present is in any supplied TransferSyntaxes
        ///   instance, reject the presentation context with result 4.<br></br><br></br>
        ///   
        ///   Note that a difference exists between supplying one TransferSyntaxes instance with all
        ///   transfer syntaxes to accept and supplying multiple TransferSyntaxes instances each containing
        ///   only one transfer syntax. In the first case, the preference (order of proposed transfer
        ///   syntaxes) of the SCU will be used, in the second case the preference of the caller of this
        ///   method will be used.
        /// </remarks>
        /// <param name="transferSyntaxesList">The transfer syntaxes to accept.</param>
        /// <returns>The created presentation contexts.</returns>
        public PresentationContextCollection CreatePresentationContextsForAssociateAc(params TransferSyntaxes[] transferSyntaxesList)
        {
            PresentationContextCollection presentationContextsForAssociateAc = new PresentationContextCollection();

            PresentationContextCollection presentationContexts = PresentationContexts;

            foreach(PresentationContext presentationContextInAssociateRq in presentationContexts)
            {
                String abstractSyntaxInAssociateRq = presentationContextInAssociateRq.AbstractSyntax;

                PresentationContext presentationContextForAssociateAc = null;

                String transferSyntaxForAssociateAc = DetermineTransferSyntaxToAccept
                    (presentationContextInAssociateRq.TransferSyntaxes,
                    transferSyntaxesList);

                if (transferSyntaxForAssociateAc.Length == 0)
                {
                    presentationContextForAssociateAc = new PresentationContext
                        (presentationContextInAssociateRq.AbstractSyntax,
                        4,
                        "");
                }
                else
                {
                    presentationContextForAssociateAc = new PresentationContext
                        (presentationContextInAssociateRq.AbstractSyntax,
                        0,
                        transferSyntaxForAssociateAc);
                }

                presentationContextForAssociateAc.SetId(presentationContextInAssociateRq.ID);

                presentationContextsForAssociateAc.Add(presentationContextForAssociateAc);
            }

            return(presentationContextsForAssociateAc);
        }
Example #44
0
        private bool FindMatchingPresentationContext(PresentationContextCollection pcs,PresentationContext value)
        {
            bool found = false;
            foreach (PresentationContext pc in pcs)
            {
                if (IsPCEquals(pc,value))
                {
                    found = true;
                    break;
                }
            }

            return found;
        }
Example #45
0
        private void SendDICOMDataInMultipleAssociation(string[] mediaFiles)
        {
            int index = 0;
            // Set the dicom messages to send
            DicomMessageCollection dicomMessageCollection = new DicomMessageCollection();
            PresentationContextCollection pcCollection = new PresentationContextCollection();

            //The Current Directory is being set to the Results Directory because
            // when DICOMDIRs(or DICOM Files)Media are exported, the Environment.CurrentDirectory
            //is set to the Directory in which the DCM objects are present and the export will fail
            // if the DICOMDIR is present on a Physical Media.
            Environment.CurrentDirectory = this.storageOptions.ResultsDirectory;

            foreach (string dcmFilename in mediaFiles)
            {
                HliScu storageScuSubThread = new HliScu();

                storageScuSubThread.Initialize(this.overviewThread);
                storageScuSubThread.Options.CopyFrom(this.storageOptions);

                storageScuSubThread.Options.Identifier = string.Format("StorageOperation_{0}",index);

                String resultsFileBaseName = string.Format("StorageOperation_{0}_", index) + System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
                storageScuSubThread.Options.ResultsFileNameOnlyWithoutExtension = resultsFileBaseName;

                storageScuSubThread.Options.LogThreadStartingAndStoppingInParent = false;
                storageScuSubThread.Options.LogWaitingForCompletionChildThreads = false;
                storageScuSubThread.Options.AutoValidate = false;

                string msg = string.Format("Reading and exporting the DICOM object - {0}", dcmFilename);
                storageScuSubThread.WriteInformation(msg);

                try
                {
                    // Read the DCM File
                    DicomFile dcmFile = new DicomFile();
                    dcmFile.Read(dcmFilename, storageScuSubThread);

                    FileMetaInformation fMI = dcmFile.FileMetaInformation;

                    // Get the transfer syntax and SOP class UID
                    System.String transferSyntax = "1.2.840.10008.1.2.1";
                    if ((fMI != null) && fMI.Exists("0x00020010"))
                    {
                        // Get the Transfer syntax
                        HLI.Attribute tranferSyntaxAttr = fMI["0x00020010"];
                        transferSyntax = tranferSyntaxAttr.Values[0];
                    }

                    Values values = fMI["0x00020002"].Values;
                    System.String sopClassUid = values[0];

                    //Check for DICOMDIR
                    if (sopClassUid == "1.2.840.10008.1.3.10")
                    {
                        // Read the DICOMDIR dataset
                        dcmFile.DataSet.DvtkDataDataSet = Dvtk.DvtkDataHelper.ReadDataSetFromFile(dcmFilename);
                        ArrayList refFiles = ImportRefFilesFromDicomdir(dcmFilename, dcmFile.DataSet);

                        foreach (string refFilename in refFiles)
                        {
                            // Read the Reference File
                            DicomFile refFile = new DicomFile();
                            refFile.Read(refFilename, storageScuSubThread);

                            FileMetaInformation refFMI = refFile.FileMetaInformation;

                            // Get the transfer syntax and SOP class UID
                            System.String refTransferSyntax = "1.2.840.10008.1.2.1";
                            if ((refFMI != null) && refFMI.Exists("0x00020010"))
                            {
                                // Get the Transfer syntax
                                HLI.Attribute refTranferSyntaxAttr = refFMI["0x00020010"];
                                refTransferSyntax = refTranferSyntaxAttr.Values[0];
                            }

                            Values sopValues = refFile.DataSet["0x00080016"].Values;
                            System.String refSopClassUid = sopValues[0];

                            PresentationContext refPresentationContext = new PresentationContext(refSopClassUid, // Abstract Syntax Name
                                                                                        refTransferSyntax); // Transfer Syntax Name(s)
                            pcCollection.Add(refPresentationContext);

                            DicomMessage refStorageMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CSTORERQ);
                            refStorageMessage.DataSet.CloneFrom(refFile.DataSet);
                            dicomMessageCollection.Add(refStorageMessage);

                            // set the presentation contexts for the association
                            PresentationContext[] presentationContexts = SetPresentationContexts(pcCollection);

                            storageScuSubThread.Start();

                            storageScuSubThread.TriggerSendAssociationAndWait(dicomMessageCollection, presentationContexts);
                        }
                    }
                    else
                    {
                        PresentationContext presentationContext = new PresentationContext(sopClassUid, // Abstract Syntax Name
                                                                                        transferSyntax); // Transfer Syntax Name(s)
                        PresentationContext[] presentationContexts = new PresentationContext[1];
                        presentationContexts[0] = presentationContext;

                        DicomMessage storageMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CSTORERQ);
                        storageMessage.DataSet.CloneFrom(dcmFile.DataSet);

                        storageScuSubThread.Start();

                        storageScuSubThread.TriggerSendAssociationAndWait(storageMessage, presentationContexts);
                    }

                    if (storageScuSubThread.HasExceptionOccured)
                    {
                        storageScuSubThread.WriteError(string.Format("Store operation of {0} failed", dcmFilename));
                    }
                }
                catch (Exception e)
                {
                    storageScuSubThread.WriteError(e.Message + "\nSkipping the DCM File.");
                }

                index++;

                storageScuSubThread.Stop();
            }

            DicomMessageCollection cStoreResponses = threadManager.Messages.DicomProtocolMessages.DicomMessages.CStoreResponses;

            foreach (DicomMessage cStoreRsp in cStoreResponses)
            {
                Int32 statusVal = Int32.Parse(cStoreRsp.CommandSet.GetValues("0x00000900")[0]);
                String sopInstUid = cStoreRsp.CommandSet.GetValues("0x00001000")[0];
                if (statusVal == 0)
                {
                    string infoMsg = string.Format("Image with SOP Instance UID{0} stored successfully.", sopInstUid);
                    overviewThread.WriteInformation(infoMsg);
                }
                else
                {
                    string warnMsg = string.Format("Non-zero status returned. Image with SOP Instance UID{0} storage failed.", sopInstUid);
                    overviewThread.WriteWarning(warnMsg);
                }
            }

            HandleCStoreResponses(storageCommitItems, cStoreResponses);

            threadManager.Messages.DicomProtocolMessages.DicomMessages.CStoreResponses.Clear();
        }
Example #46
0
        public void HandleNReport(StorageCommitArgs p)
        {
            StorageCommitment       commitRequest = p.RequestDS.Get <StorageCommitment>();
            StorageCommitmentResult commitResult  = new StorageCommitmentResult();

            commitResult.TransactionUID  = commitRequest.TransactionUID;
            commitResult.RetrieveAETitle = p.Client.AETitle; //p.Client.Server.AETitle;

            int failedCount = 0;

            foreach (SopInstanceReference referencedSop in commitRequest.ReferencedSOPSequence)
            {
                string referencedFile = GetInstanceFileName.FindReferencedFile(referencedSop.ReferencedSopInstanceUid);
                bool   success        = !string.IsNullOrEmpty(referencedFile) && File.Exists(referencedFile);

                if (success)
                {
                    // Success
                    if (commitResult.ReferencedSOPSequence == null)
                    {
                        commitResult.ReferencedSOPSequence = new List <SCSOPInstanceReference>();
                    }

                    SCSOPInstanceReference scSopInstanceReference = new SCSOPInstanceReference();
                    scSopInstanceReference.RetrieveAETitle          = commitResult.RetrieveAETitle;
                    scSopInstanceReference.ReferencedSopClassUid    = referencedSop.ReferencedSopClassUid;
                    scSopInstanceReference.ReferencedSopInstanceUid = referencedSop.ReferencedSopInstanceUid;
                    commitResult.ReferencedSOPSequence.Add(scSopInstanceReference);
                }
                else
                {
                    // Fail

                    if (commitResult.FailedSOPSequence == null)
                    {
                        commitResult.FailedSOPSequence = new List <SCFailedSOPInstanceReference>();
                    }

                    SCFailedSOPInstanceReference scFailedSopInstanceReference = new SCFailedSOPInstanceReference();
                    scFailedSopInstanceReference.ReferencedSopClassUid    = referencedSop.ReferencedSopClassUid;
                    scFailedSopInstanceReference.ReferencedSopInstanceUid = referencedSop.ReferencedSopInstanceUid;

                    // The following values and semantics shall be used for the Failure Reason Attribute:
                    // 0110H - DicomCommandStatusType.ProcessingFailure       - Processing failure A general failure in processing the operation was encountered.
                    // 0112H - DicomCommandStatusType.NoSuchObjectInstance    - No such object instance One or more of the elements in the Referenced SOP Instance Sequence was not available.
                    // 0213H - DicomCommandStatusType.ResourceLimitation      - Resource limitation The SCP does not currently have enough resources to store the requested SOP Instance(s).
                    // 0122H - DicomCommandStatusType.ClassNotSupported       - Referenced SOP Class not supported Storage Commitment has been requested for a SOP Instance with a SOP Class thatis not supported by the SCP.
                    // 0119H - DicomCommandStatusType.ClaseInstanceConflict   - Class / Instance conflict The SOP Class of an element in the Referenced SOP Instance Sequence did not correspond to theSOP class registered for this SOP Instance at the SCP.
                    // 0131H - DicomCommandStatusType.DuplicateTransactionUid - Duplicate transaction UID The Transaction UID of the Storage Commitment Request is already in use.
                    scFailedSopInstanceReference.FailureReason = (int)DicomCommandStatusType.NoSuchObjectInstance;

                    commitResult.FailedSOPSequence.Add(scFailedSopInstanceReference);
                    failedCount++;
                }
            }

            DicomDataSet resultDS = new DicomDataSet();

            resultDS.Set(commitResult);

            PresentationContext pc = new PresentationContext();

            pc.AbstractSyntax = DicomUidType.StorageCommitmentPushModelClass;
            pc.TransferSyntaxes.Add(DicomUidType.ImplicitVRLittleEndian);

            DicomRequest request = new DicomRequest(p.Client);

            request.PresentationContexts.Add(pc);
            request.RequireMessagePump = true;

            request.ReceiveNReportResponse += new ReceiveNReportResponseDelegate(request_ReceiveNReportResponse);

            request.ConnectType = ConnectType.Conditional;
            // request.ConnectType = ConnectType.New;

            // eventTypeId   - 1 -- All success
            //               - 2 -- One or more failures
            int eventTypeId = failedCount > 0 ? 2 : 1;

            _dicomRequest.SendNReportRequest(request,
                                             p.PresentationId,
                                             p.MessageId,
                                             DicomUidType.StorageCommitmentPushModelClass,
                                             DicomUidType.StorageCommitmentPushModelInstance,
                                             eventTypeId,
                                             resultDS);
        }
 public AuthorRepository(PresentationContext context)
 {
     this.context = context;
 }
Example #48
0
        private bool IsPCEquals(PresentationContext pc1,PresentationContext pc2)
        {
            // Only interested in comparing the SOP Class UID and Transfer Syntaxes
            if (pc1.AbstractSyntax != pc2.AbstractSyntax) return false;
            if (pc1.TransferSyntaxes.Count != pc2.TransferSyntaxes.Count) return false;

            // The transfer syntaxes may be defined in a different order
            bool equal = true;
            for (int i = 0; i < pc1.TransferSyntaxes.Count; i++)
            {
                bool matchFound = false;
                for (int j = 0; j < pc2.TransferSyntaxes.Count; j++)
                {
                    if (pc1.TransferSyntaxes[i] == pc2.TransferSyntaxes[j])
                    {
                        matchFound = true;
                        break;
                    }
                }
                if (matchFound == false)
                {
                    equal = false;
                    break;
                }
            }

            return equal;
        }
Example #49
0
        private void SendDICOMDataInSingleAssociation(string[] mediaFiles)
        {
            // Set the dicom messages to send
            List<DicomFile> dicomMessageCollection = new List<DicomFile>();
            PresentationContextCollection pcCollection = new PresentationContextCollection();

            StoreScu storageScuThread = new StoreScu();

            storageScuThread.Initialize(this.overviewThread);
            storageScuThread.Options.CopyFrom(this.storageOptions);

            String resultsFileBaseName = "StorageOperation_" + System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
            storageScuThread.Options.ResultsFileNameOnlyWithoutExtension = resultsFileBaseName;
            storageScuThread.Options.Identifier = resultsFileBaseName;

            storageScuThread.Options.LogThreadStartingAndStoppingInParent = false;
            storageScuThread.Options.LogWaitingForCompletionChildThreads = false;
            storageScuThread.Options.AutoValidate = false;

            //The Current Directory is being set to the Results Directory because
            // when DICOMDIRs(or DICOM Files)Media are exported, the Environment.CurrentDirectory
            //is set to the Directory in which the DCM objects are present and the export will fail
            // if the DICOMDIR is present on a Physical Media.
            Environment.CurrentDirectory = this.storageOptions.ResultsDirectory;

            foreach (string dcmFilename in mediaFiles)
            {
                string msg = string.Format("Reading the DICOM object - {0}", dcmFilename);
                storageScuThread.WriteInformation(msg);

                try
                {
                    // Read the DCM File
                    DicomFile dcmFile = new DicomFile();

                    dcmFile.Read(dcmFilename, storageScuThread);

                    FileMetaInformation fMI =  dcmFile.FileMetaInformation;

                    // Get the transfer syntax and SOP class UID
                    System.String transferSyntax = "1.2.840.10008.1.2.1";
                    System.String sopClassUid = "";
                    if ((fMI != null))
                    {
                        // Get the Transfer syntax
                        HLI.Attribute tranferSyntaxAttr = fMI["0x00020010"];
                        transferSyntax = tranferSyntaxAttr.Values[0];

                        // Get the SOP Class UID
                        Values values = fMI["0x00020002"].Values;
                        sopClassUid = values[0];
                    }
                    else
                    {
                        // Get the SOP Class UID
                        Values values =  dcmFile.DataSet["0x00080016"].Values;
                        sopClassUid = values[0];
                    }

                    //Check for DICOMDIR
                    if(sopClassUid == "")
                    {
                        storageScuThread.WriteError("Can't determine SOP Class UID for DCM file. \nSkipping the DCM File.");
                        continue;
                    }
                    else if (sopClassUid == "1.2.840.10008.1.3.10")
                    {

                            HLI.DataSet tempDataSet = new HLI.DataSet();

                            // Read the DICOMDIR dataset
                            dcmFile.DataSet.DvtkDataDataSet = Dvtk.DvtkDataHelper.ReadDataSetFromFile(dcmFilename);
                            Dvtk.Sessions.ScriptSession session = this.storageOptions.DvtkScriptSession;
                            ArrayList refFiles = ImportRefFilesFromDicomdir(dcmFilename, dcmFile.DataSet);

                            foreach (string refFilename in refFiles)
                            {
                                // Read the Reference File
                                DicomFile refFile = new DicomFile();
                                refFile.Read(refFilename, storageScuThread);

                                FileMetaInformation refFMI = refFile.FileMetaInformation;

                                // Get the transfer syntax and SOP class UID
                                System.String refTransferSyntax = "1.2.840.10008.1.2.1";
                                if ((refFMI != null) && refFMI.Exists("0x00020010"))
                                {
                                    // Get the Transfer syntax
                                    HLI.Attribute refTranferSyntaxAttr = refFMI["0x00020010"];
                                    refTransferSyntax = refTranferSyntaxAttr.Values[0];
                                }

                                Values sopValues = refFile.DataSet["0x00080016"].Values;
                                System.String refSopClassUid = sopValues[0];

                                PresentationContext refPresentationContext = new PresentationContext(refSopClassUid, // Abstract Syntax Name
                                                                                                     refTransferSyntax); // Transfer Syntax Name(s)
                                pcCollection.Add(refPresentationContext);

                                //DicomMessage refStorageMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CSTORERQ);
                                //refStorageMessage.DataSet.CloneFrom(refFile.DataSet);
                                dicomMessageCollection.Add(refFile);
                            }
                    }
                    else
                    {
                        PresentationContext presentationContext = new PresentationContext(sopClassUid, // Abstract Syntax Name
                                                                                          transferSyntax); // Transfer Syntax Name(s)
                        pcCollection.Add(presentationContext);

                        //DicomMessage storageMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CSTORERQ);
                        //storageMessage.DataSet.CloneFrom(dcmFile.DataSet);
                        dicomMessageCollection.Add(dcmFile);
                    }
                }
                catch (Exception e)
                {
                    storageScuThread.WriteError(e.Message + "\nSkipping the DCM File.");
                }
            }

            // set the presentation contexts for the association
            PresentationContext[] presentationContexts = SetPresentationContexts(pcCollection);

            storageScuThread.DICOMFileCollection = dicomMessageCollection;
            storageScuThread.PresentationContexts = presentationContexts;

            storageScuThread.Start();

            storageScuThread.WaitForCompletion();

            DicomMessageCollection cStoreResponses = storageScuThread.Messages.DicomMessages.CStoreResponses;

            //storageScuThread.Stop();

            HandleCStoreResponses(storageCommitItems, cStoreResponses);

            storageScuThread.Messages.DicomMessages.CStoreResponses.Clear();
        }
Example #50
0
        private PresentationContext[] SetPresentationContexts(PresentationContextCollection pcs)
        {
            PresentationContextCollection localPCs = new PresentationContextCollection();

            // use the local trigger items to establish a list of presentation contexts that
            // only appear once
            foreach (PresentationContext pc in pcs)
            {
                if (FindMatchingPresentationContext(localPCs,pc) == false)
                {
                    localPCs.Add(pc);
                }
            }

            // now set up the returned presentation contexts from the local trigger collection
            PresentationContext[] presentationContexts = new PresentationContext[localPCs.Count];
            int index = 0;
            foreach (PresentationContext pc in localPCs)
            {
                // save the presentation context
                string[] transferSyntaxes = new string[pc.TransferSyntaxes.Count];
                int i = 0;
                foreach(string ts in pc.TransferSyntaxes)
                {
                    transferSyntaxes.SetValue(ts,i);
                    i++;
                }
                presentationContexts[index++] = new PresentationContext(pc.AbstractSyntax, transferSyntaxes);
            }

            return presentationContexts;
        }
Example #51
0
        /// <summary>
        ///     Splits the DICOM object into chunks that are within the max PDU size
        /// </summary>
        /// <param name="dicomObject"> the DICOM objec to be split</param>
        /// <param name="maxPduSize">the max length (in bytes) for a PDU</param>
        /// <param name="asc">the association that the file will be sent</param>
        /// <returns></returns>
        public static List <byte[]> GetChunks(DICOMObject dicomObject, int maxPduSize, PresentationContext pc)
        {
            byte[] dicomBytes;
            using (var stream = new MemoryStream())
            {
                using (var dw = new DICOMBinaryWriter(stream))
                {
                    var tx = TransferSyntaxHelper.GetSyntax(pc.TransferSyntaxes.First());
                    DICOMObjectWriter.WriteSameSyntax(dw,
                                                      new DICOMIOSettings
                    {
                        TransferSyntax             = tx,
                        DoWriteIndefiniteSequences = false
                    }, dicomObject);
                    dicomBytes = stream.ToArray();
                }
            }

            var split = new List <byte[]>();
            var i     = 0;

            while (i < dicomBytes.Length)
            {
                var toTake   = dicomBytes.Length >= maxPduSize - 6 ? maxPduSize - 6 : dicomBytes.Length;
                var fragment = dicomBytes.Skip(i).Take(toTake).ToArray();
                i += fragment.Length;
                split.Add(fragment);
            }
            return(split);
        }
Example #52
0
        private PresentationContext[] SetPresentationContexts(DicomTrigger dicomTrigger)
        {
            DicomTriggerItemCollection localTriggerItems = new DicomTriggerItemCollection();

            // use the local trigger items to establish a list of presentation contexts that
            // only appear once
            foreach (DicomTriggerItem triggerItem in dicomTrigger.TriggerItems)
            {
                if (localTriggerItems.FindMatchingPresentationContext(triggerItem) == false)
                {
                    localTriggerItems.Add(triggerItem);
                }
            }

            // now set up the returned presentation contexts from the local trigger collection
            PresentationContext[] presentationContexts = new PresentationContext[localTriggerItems.Count];
            int index = 0;
            foreach (DicomTriggerItem triggerItem in localTriggerItems)
            {
                // save the presentation context
                presentationContexts[index++] = new PresentationContext(triggerItem.SopClassUid,
                    MergeTransferSyntaxes(triggerItem.TransferSyntaxes));
            }

            return presentationContexts;
        }
Example #53
0
        /// <summary>
        /// Overridden N-ACTION-RQ message handler. Return an N-EVENT-REPORT-RQ
        /// after the N-ACTION-RSP.
        /// </summary>
        /// <param name="queryMessage">N-ACTION-RQ and Dataset.</param>
        /// <returns>Boolean - true if dicomMessage handled here.</returns>
        protected override void AfterHandlingNActionRequest(DicomMessage dicomMessage)
        {
            isEventSent = false;

            // set up the default N-ACTION-RSP with a successful status
            DicomMessage responseMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.NACTIONRSP);
            responseMessage.Set("0x00000900", DvtkData.Dimse.VR.US, 0);

            // send the response
            this.Send(responseMessage);

            IsMessageHandled = true;

            // creating information model
            QueryRetrieveInformationModels qrInfoModels = CreateQueryRetrieveInformationModels(true, _dataDirectory);

            // delay before generating the N-EVENT-REPORT-RQ
            WriteInformation(string.Format("Delaying the N-EVENT-REPORT by {0} secs", _eventDelay / 1000));

            isAssociated = true;
            int waitedTime = 0;

            if (WaitForPendingDataInNetworkInputBuffer(_eventDelay, ref waitedTime))
            {
                ReleaseRq releaseRq = ReceiveReleaseRq();

                if (releaseRq != null)
                {
                    SendReleaseRp();

                    isAssociated = false;
                }
            }

            if (!isAssociated)
            {
                string info = "Sending the N-Event-Report asynchronously.";
                WriteInformation(info);

                SCU commitScu = new SCU();

                commitScu.Initialize(this.Parent);

                // Set the correct settings for the overview DicomThread.
                //
                commitScu.Options.Identifier = "Storage_Commitment_SCU_association_" + storageCommitmentScuIndex.ToString();
                commitScu.Options.ResultsFileNameOnlyWithoutExtension = (this.overviewThread as StoreCommitScp).startDateTime + "_Storage_Commitment_SCU_association_" + storageCommitmentScuIndex.ToString();
                storageCommitmentScuIndex++;
                commitScu.Options.LocalAeTitle = this.Options.LocalAeTitle;
                commitScu.Options.RemoteAeTitle = _remoteAETitle;
                commitScu.Options.RemotePort = _port;
                commitScu.Options.RemoteHostName = _remoteHostName;
                commitScu.Options.RemoteRole = Dvtk.Sessions.SutRole.Requestor;
                commitScu.Options.ResultsDirectory = this.Options.ResultsDirectory;
                commitScu.Options.DataDirectory = this.Options.DataDirectory;
                commitScu.Options.StorageMode = Dvtk.Sessions.StorageMode.NoStorage;
                commitScu.Options.LogThreadStartingAndStoppingInParent = false;
                commitScu.Options.LogWaitingForCompletionChildThreads = false;
                commitScu.Options.AutoValidate = false;

                PresentationContext presentationContext = new PresentationContext("1.2.840.10008.1.20.1", // Abstract Syntax Name
                                                                                "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
                PresentationContext[] presentationContexts = new PresentationContext[1];
                presentationContexts[0] = presentationContext;

                // create the N-EVENT-REPORT-RQ based in the contents of the N-ACTION-RQ
                DicomMessage requestMessage = GenerateTriggers.MakeStorageCommitEvent(qrInfoModels, dicomMessage);

                if (waitedTime < _eventDelay)
                    Sleep(_eventDelay - waitedTime);

                commitScu.Start();

                isEventSent = commitScu.TriggerSendAssociationAndWait(requestMessage, presentationContexts);
            }
            else
            {
                string info = "Sending the N-Event-Report synchronously.";
                WriteInformation(info);

                if (!isEventSent)
                    SendNEventReport(qrInfoModels, dicomMessage);
            }
        }
 //
 // - Methods -
 //
 /// <summary>
 /// Adds an item to the <see cref="System.Collections.IList"/>.
 /// </summary>
 /// <param name="value">The item to add to the <see cref="System.Collections.IList"/>. </param>
 /// <returns>The position into which the new element was inserted.</returns>
 public int Add(PresentationContext value)
 {
     return base.Add(value);
 }
Example #55
0
        protected override void Execute()
        {
            PresentationContext presentationContext = new PresentationContext("1.2.840.10008.1.20.1", // Abstract Syntax Name
                                                                            "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
            PresentationContext[] presentationContexts = new PresentationContext[1];
            presentationContexts[0] = presentationContext;

            SendAssociateRq(presentationContexts);

            ReceiveAssociateAc();

            if (_nActionMessage != null)
            {
                WriteInformation("N-Action Request Information"+"\n"+_nActionMessage.DataSet.Dump(""));
                Send(_nActionMessage);
            }

            ReceiveDicomMessage();

            if (_Delay < 0)
            {
                // Async storage commitment
                SendReleaseRq();

                ReceiveReleaseRp();

                // Start the Storage commit SCP for receiving N-EVENTREPORT
                EmulateStorageCommitSCP();
            }
            else
            {
                string info;
                if (_Delay == 0)
                {
                    //Wait for 24 hrs(infinite)
                    int waitingTime = 24 * 60 * 60;
                    _Delay = (short)waitingTime;
                    info = "Waiting forever for N-Event-Report.";
                }
                else
                {
                    info = string.Format("Waiting for N-Event-Report for {0} secs", _Delay);
                }
                WriteInformation(info);

                int waitedTime = 0;
                if (WaitForPendingDataInNetworkInputBuffer(_Delay * 1000, ref waitedTime))
                {
                    DicomMessage nEventReportResponse = ReceiveDicomMessage();

                    if (nEventReportResponse.CommandSet.DimseCommand == DvtkData.Dimse.DimseCommand.NEVENTREPORTRQ)
                    {
                        // set up the default N-EVENT-REPORT-RSP with a successful status
                        DicomMessage responseMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.NEVENTREPORTRSP);
                        responseMessage.Set("0x00000900", DvtkData.Dimse.VR.US, 0);

                        // send the response
                        this.Send(responseMessage);

                        string msg = "N-Event-Report is received from PACS.";
                        WriteInformation(msg);
                        WriteInformation("N-Event-Report Information\n"+nEventReportResponse.DataSet.Dump(""));

                        SendReleaseRq();

                        ReceiveReleaseRp();

                        return;
                    }
                }
                else
                {
                    SendReleaseRq();

                    ReceiveReleaseRp();

                    // Start the Storage commit SCP for receiving N-EVENTREPORT
                    EmulateStorageCommitSCP();
                }
            }
        }
 /// <summary>
 /// Determines whether the <see cref="System.Collections.IList"/> contains a specific item.
 /// </summary>
 /// <param name="value">The item to locate in the <see cref="System.Collections.IList"/>.</param>
 /// <returns><see langword="true"/> if the item is found in the <see cref="System.Collections.IList"/>; otherwise, <see langword="false"/>.</returns>
 public bool Contains(PresentationContext value)
 {
     return base.Contains(value);
 }
Example #57
0
        private bool HandleSubOperation(System.String moveDestinationAE, System.String dcmFilename, int subOperationIndex)
        {
            SCU storageScu = new SCU();

            storageScu.Initialize(DicomThread.ThreadManager);
            storageScu.Options.DeepCopyFrom(DicomThread.Options);

            storageScu.Options.Identifier = "StorageSubOperationAsScu";

            ////Check for Secure connection
            //if (DicomThread.Options.SecureConnection)
            //{
            //    storageScu.Options.SecureConnection = true;
            //    storageScu.Options.CertificateFilename = DicomThread.Options.CertificateFilename;
            //    storageScu.Options.CredentialsFilename = DicomThread.Options.CredentialsFilename;
            //}

            storageScu.Options.ResultsFileNameOnlyWithoutExtension = "StorageSubOperationAsScu" + subOperationIndex.ToString();
            storageScu.Options.ResultsDirectory = DicomThread.Options.ResultsDirectory;

            storageScu.Options.LocalAeTitle = DicomThread.Options.LocalAeTitle;
            storageScu.Options.LocalPort = DicomThread.Options.LocalPort;
            if (IsHaveMoveDestinations)
            {
                storageScu.Options.RemoteAeTitle = moveDestinationAE;
                storageScu.Options.RemotePort = MoveDestiantions[MoveAEdetailsIndex].Port;
                storageScu.Options.RemoteHostName = MoveDestiantions[MoveAEdetailsIndex].IP;
            }
            else
            {
                storageScu.Options.RemoteAeTitle = moveDestinationAE;
                storageScu.Options.RemotePort = DicomThread.Options.RemotePort;
                storageScu.Options.RemoteHostName = DicomThread.Options.RemoteHostName;
            }

            storageScu.Options.DataDirectory = DicomThread.Options.DataDirectory;
            storageScu.Options.StorageMode = Dvtk.Sessions.StorageMode.AsDataSet;

            // Read the DCM File
            DicomFile dcmFile = new DicomFile();
            dcmFile.Read(dcmFilename, storageScu);

            FileMetaInformation fMI = dcmFile.FileMetaInformation;

            // Get the transfer syntax and SOP class UID
            System.String transferSyntax = "1.2.840.10008.1.2";
            if((fMI != null) && fMI.Exists("0x00020010"))
            {
                // Get the Transfer syntax
                DvtkHighLevelInterface.Dicom.Other.Attribute tranferSyntaxAttr = fMI["0x00020010"];
                transferSyntax = tranferSyntaxAttr.Values[0];
            }

            Values values = dcmFile.DataSet["0x00080016"].Values;
            System.String sopClassUid = values[0];

            PresentationContext presentationContext = new PresentationContext(sopClassUid, // Abstract Syntax Name
                                                                            transferSyntax); // Transfer Syntax Name(s)
            PresentationContext[] presentationContexts = new PresentationContext[1];
            presentationContexts[0] = presentationContext;

            DicomMessage storageMessage = new DicomMessage(DvtkData.Dimse.DimseCommand.CSTORERQ);
            storageMessage.DataSet.CloneFrom(dcmFile.DataSet);

            storageScu.Start();

            bool sendResult = storageScu.TriggerSendAssociationAndWait(storageMessage, presentationContexts);
            if (!sendResult)
            {
                WriteWarning("Association to move destination for Storage Sub-Operation is rejected.");
            }

            if (storageScu.HasExceptionOccured)
            {
                WriteError("Storage Sub-Operation As SCU Failed");
            }
            storageScu.Stop();

            DicomMessageCollection cStoreResponses = storageScu.Messages.DicomMessages.CStoreResponses;

            // Obtain the value of the C-STORE RSP.The value of this variable is used to determine the attributes of the C-MOVE RSP.
            foreach (DicomMessage cStoreRsp in cStoreResponses)
            {
                cStoreStatusVal = Int32.Parse(cStoreRsp.CommandSet.GetValues("0x00000900")[0]);
            }

            // Transform the sub results
            Xslt.StyleSheetFullFileName = DicomThread.Options.StyleSheetFullFileName;
            System.String htmlResultsFilename = Xslt.Transform(storageScu.Options.ResultsDirectory, storageScu.Options.ResultsFileNameOnly);

            // Make link to the sub-operation results file
            System.String message = System.String.Format("<a href=\"{0}\">Storage sub-operation {1} to AE Title \"{2}\"</a><br/>",
                htmlResultsFilename,
                subOperationIndex,
                moveDestinationAE);
            DicomThread.WriteHtmlInformation(message);

            return sendResult;
        }
Example #58
0
        private void dICOMEchoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string detailedEchoFileName = "";
            if (registeredPeersGrid.SelectedIndices.Count > 0)
            {
                int selectedIndex = registeredPeersGrid.SelectedIndices[0];

                //isStorageEcho = true;
                allThreadsFinished = false;
                if ((peers[selectedIndex].IP == null) || (peers[selectedIndex].IP.Length == 0))
                {
                    MessageBox.Show("Pl Specify SCP IP Address.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                //Update DVT & SUT settings
                OverviewThread overviewThread = new OverviewThread();
                overviewThread.Initialize(threadManager);
                overviewThread.Options.DeepCopyFrom(options);
                overviewThread.Options.Identifier = "Move_Destinations";
                overviewThread.Options.AttachChildsToUserInterfaces = true;
                overviewThread.Options.LogThreadStartingAndStoppingInParent = false;
                overviewThread.Options.LogWaitingForCompletionChildThreads = false;
                String resultsFileName = "MoveDestinations_" + System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
                overviewThread.Options.ResultsFileNameOnlyWithoutExtension = resultsFileName;

                SCU echoScu = new SCU();
                echoScu.Initialize(overviewThread);
                echoScu.Options.DeepCopyFrom(options);

                String resultsFileBaseName = "MoveDestinationsEcho_" + System.DateTime.Now.ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
                echoScu.Options.ResultsFileNameOnlyWithoutExtension = resultsFileBaseName;
                echoScu.Options.Identifier = resultsFileBaseName;

                echoScu.Options.LogThreadStartingAndStoppingInParent = false;
                echoScu.Options.LogWaitingForCompletionChildThreads = false;
                echoScu.Options.AutoValidate = false;
                echoScu.Options.ResultsDirectory = options.ResultsDirectory;

                //echoScu.Options.LocalAeTitle ="SCU";
                echoScu.Options.RemoteAeTitle = peers[selectedIndex].AE;
                echoScu.Options.RemotePort = peers[selectedIndex].Port;
                echoScu.Options.RemoteHostName = peers[selectedIndex].IP;
                //this.userControlActivityLogging.Attach(echoScu);

                detailedEchoFileName = echoScu.Options.DetailResultsFullFileName;
                PresentationContext presentationContext = new PresentationContext("1.2.840.10008.1.1", // Abstract Syntax Name
                                                                                "1.2.840.10008.1.2"); // Transfer Syntax Name(s)
                PresentationContext[] presentationContexts = new PresentationContext[1];
                presentationContexts[0] = presentationContext;

                DvtkHighLevelInterface.Dicom.Messages.DicomMessage echoMessage = new DvtkHighLevelInterface.Dicom.Messages.DicomMessage(DvtkData.Dimse.DimseCommand.CECHORQ);

                echoScu.Start();

                bool sendResult = echoScu.TriggerSendAssociationAndWait(echoMessage, presentationContexts);

                if (!sendResult)
                {
                    MessageBox.Show("DICOM Echo failed ","Failed",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
                else
                    MessageBox.Show("DICOM Echo successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

                echoScu.Stop();
                if (OnShowEchoResults != null)
                {
                    OnShowEchoResults.Invoke(detailedEchoFileName,sendResult);
                }
                allThreadsFinished=false;

            }
        }
Example #59
0
        /// <summary>
        /// Trigger the Client to send a Verification (DICOM C-ECHO-RQ).
        /// </summary>
        /// <param name="actorName">Destination Actor Name.</param>
        /// <returns>Boolean indicating success or failure.</returns>
        public bool TriggerClientVerification(ActorName actorName)
        {
            // Set up a Verification SOP Class - C-ECHO-RQ trigger
            DicomTrigger dicomTrigger = new DicomTrigger(Dvtk.IheActors.Bases.TransactionNameEnum.RAD_UNKNOWN);
            dicomTrigger.AddItem(new DicomMessage(DvtkData.Dimse.DimseCommand.CECHORQ),
                                HliScp.VERIFICATION_SOP_CLASS_UID,
                                HliScp.IMPLICIT_VR_LITTLE_ENDIAN);
            DicomTriggerItem dicomTriggerItem = dicomTrigger.TriggerItems[0];

            // thread must wait for association completion
            _scu.SignalCompletion = true;

            // set up the presentation context from the trigger
            PresentationContext[] presentationContexts = new PresentationContext[1];
            presentationContexts[0] = new PresentationContext(dicomTriggerItem.SopClassUid,
                    dicomTriggerItem.TransferSyntaxes);
            _scu.TriggerSendAssociation(dicomTriggerItem.Message, presentationContexts);

            // wait for association completion
            // - timeout of 0 means "no timeout".
            _semaphore.Wait(0);

            // return a boolean indicating if the trigger was processed successfully or not
            return _scu.ProcessTriggerResult;
        }
Example #60
0
        /// <summary>
        /// Method to handle the workflow after receiving an Associate Request.
        /// </summary>
        /// <param name="associateRq">Associate Request message.</param>
        public override void AfterHandlingAssociateRequest(AssociateRq associateRq)
        {
            if (IsMessageHandled == false)
            {
                // determine which workflow to follow
                switch(_scpRespondToAssociateRequest)
                {
                    case ScpRespondToAssociateRequestEnum.WithAssociateAccept:
                        {
                            // send an associate accept with the supported transfer syntaxes.
                            PresentationContextCollection presentationContextsForAssociateAc = new PresentationContextCollection();
                            foreach (PresentationContext reqtedPC in associateRq.PresentationContexts)
                            {
                                String abstractSyntaxInAssociateRq = reqtedPC.AbstractSyntax;

                                PresentationContext presentationContextForAssociateAc = null;

                                if (sopList.Contains(abstractSyntaxInAssociateRq))
                                {
                                    String transferSyntaxForAssociateAc = null;
                                    this.Options.LocalAeTitle = associateRq.CalledAETitle;
                                    this.Options.RemoteAeTitle = associateRq.CallingAETitle;
                                    if (reqtedPC.AbstractSyntax == "1.2.840.10008.1.20.1")
                                    {
                                        transferSyntaxForAssociateAc = DetermineTransferSyntaxToAccept
                                            (reqtedPC.TransferSyntaxes, tsCommitList);
                                    }
                                    else
                                    {
                                        transferSyntaxForAssociateAc = DetermineTransferSyntaxToAccept
                                            (reqtedPC.TransferSyntaxes, tsStoreList);
                                    }

                                    if (transferSyntaxForAssociateAc.Length == 0)
                                    {
                                        presentationContextForAssociateAc = new PresentationContext
                                            (reqtedPC.AbstractSyntax,
                                            4,
                                            "");
                                    }
                                    else
                                    {
                                        presentationContextForAssociateAc = new PresentationContext
                                            (reqtedPC.AbstractSyntax,
                                            0,
                                            transferSyntaxForAssociateAc);
                                    }
                                }
                                else
                                {
                                    presentationContextForAssociateAc = new PresentationContext
                                        (reqtedPC.AbstractSyntax,
                                        3,
                                        "");
                                }

                                presentationContextsForAssociateAc.Add(presentationContextForAssociateAc);
                            }

                            SendAssociateAc(presentationContextsForAssociateAc);
                            isAssociated = true;
                            break;
                        }
                    case ScpRespondToAssociateRequestEnum.WithAssociateReject:
                        // send an associate reject with the given parameters
                        SendAssociateRj(_rejectResult, _rejectSource, _rejectReason);
                        break;
                    case ScpRespondToAssociateRequestEnum.WithAbort:
                    default:
                        // send an abort request with the given parameters
                        SendAbort(_abortSource, _abortReason);
                        break;
                }

                // message has now been handled
                IsMessageHandled = true;
            }
        }