예제 #1
0
        private void AddTagNodes(TreeNode parent, DicomSequenceItem record)
        {
            foreach (DicomAttribute attrib in record)
            {
                string name;
                if (attrib is DicomAttributeSQ || attrib is DicomAttributeOB || attrib is DicomAttributeOW || attrib is DicomAttributeOF)
                {
                    name = attrib.ToString();
                }
                else
                {
                    name = String.Format("{0}: {1}", attrib.Tag.ToString(), attrib.ToString());
                }
                TreeNode tagNode = new TreeNode(name);
                parent.Nodes.Add(tagNode);

                DicomAttributeSQ sqAttrib = attrib as DicomAttributeSQ;
                if (sqAttrib != null)
                {
                    for (int i = 0; i < sqAttrib.Count; i++)
                    {
                        TreeNode sqNode = new TreeNode("Sequence Item");
                        tagNode.Nodes.Add(sqNode);
                        AddTagNodes(sqNode, sqAttrib[i]);
                    }
                }
            }
        }
예제 #2
0
        private static List <VoiDataLut> Create(DicomAttributeSQ voiLutSequence, int pixelRepresentation)
        {
            bool isFirstMappedPixelSigned = pixelRepresentation != 0;

            List <DataLut> dataLuts = Create(voiLutSequence, isFirstMappedPixelSigned, false);

            return(Convert(dataLuts));
        }
예제 #3
0
		internal static ModalityDataLut Create(DicomAttributeSQ modalityLutSequence, int pixelRepresentation)
		{
			List<DataLut> data = DataLut.Create(modalityLutSequence, pixelRepresentation != 0, false);
			if (data.Count == 0)
				return null;

			string modalityLutType = ((DicomSequenceItem[]) modalityLutSequence.Values)[0][DicomTags.ModalityLutType].ToString();
			return new ModalityDataLut(data[0], modalityLutType);
		}
예제 #4
0
        /// <summary>
        /// Initializes a new instance of the SequenceIodList class.
        /// </summary>
        public SequenceIodList(DicomAttributeSQ dicomAttributeSQ)
        {
            if (dicomAttributeSQ == null)
            {
                throw new ArgumentNullException("dicomAttributeSQ");
            }

            _dicomAttributeSQ = dicomAttributeSQ;
        }
예제 #5
0
        internal static ModalityDataLut Create(DicomAttributeSQ modalityLutSequence, int pixelRepresentation)
        {
            List <DataLut> data = DataLut.Create(modalityLutSequence, pixelRepresentation != 0, false);

            if (data.Count == 0)
            {
                return(null);
            }

            string modalityLutType = ((DicomSequenceItem[])modalityLutSequence.Values)[0][DicomTags.ModalityLutType].ToString();

            return(new ModalityDataLut(data[0], modalityLutType));
        }
예제 #6
0
        public void TestSameSequenceWithExclusionsMultipleSerializations()
        {
            List <DicomFile> images = SetupImagesWithVoiLutSequenceA(3);

            StudyXml newStudyXml;
            StudyXmlOutputSettings settings = new StudyXmlOutputSettings();

            settings.MaxTagLength = 1024;

            List <DicomFile> first2Images = new List <DicomFile>();

            first2Images.AddRange(images.GetRange(0, 2));

            List <InstanceXmlDicomAttributeCollection> dataSets1 = GetInstanceXmlDataSets(first2Images, out newStudyXml, settings);

            for (int i = 0; i < first2Images.Count; ++i)
            {
                DicomAttributeSQ sequence = (DicomAttributeSQ)dataSets1[i][DicomTags.VoiLutSequence];
                for (int j = 0; j < sequence.Count; ++j)
                {
                    Assert.IsTrue(((InstanceXmlDicomSequenceItem)sequence[j]).ExcludedTags[0].TagValue == DicomTags.LutData);
                }
            }

            Assert.AreEqual(dataSets1[0][DicomTags.VoiLutSequence], dataSets1[1][DicomTags.VoiLutSequence]);

            newStudyXml.AddFile(images[2]);
            XmlDocument document = newStudyXml.GetMemento(settings);

            //SaveStudyXml(document, @"c:\stewart\studyxml3.xml");

            newStudyXml = new StudyXml();
            newStudyXml.SetMemento(document);

            List <InstanceXmlDicomAttributeCollection> dataSets2 = GetInstanceXmlDataSets(newStudyXml);

            for (int i = 0; i < first2Images.Count; ++i)
            {
                DicomAttributeSQ sequence = (DicomAttributeSQ)dataSets2[i][DicomTags.VoiLutSequence];
                for (int j = 0; j < sequence.Count; ++j)
                {
                    Assert.IsTrue(((InstanceXmlDicomSequenceItem)sequence[j]).ExcludedTags[0].TagValue == DicomTags.LutData);
                }
            }

            Assert.AreEqual(dataSets1[0][DicomTags.VoiLutSequence], dataSets2[0][DicomTags.VoiLutSequence]);
            Assert.AreEqual(dataSets1[1][DicomTags.VoiLutSequence], dataSets2[1][DicomTags.VoiLutSequence]);

            Assert.AreEqual(dataSets2[0][DicomTags.VoiLutSequence], dataSets2[1][DicomTags.VoiLutSequence]);
            Assert.AreEqual(dataSets2[0][DicomTags.VoiLutSequence], dataSets2[2][DicomTags.VoiLutSequence]);
        }
예제 #7
0
        private void PopulateScheduledProcedureStepSequence(DicomAttributeSQ dicomAttribute, ExamsScheduled row)
        {
            DicomSequenceItem item;

            item = new DicomSequenceItem();

            item[DicomTags.ScheduledStationAeTitle].SetStringValue(row.ScheduledAET);
            item[DicomTags.ScheduledProcedureStepStartDate].SetStringValue(GetDateStringOnly(row.ExamScheduledDateAndTime));
            item[DicomTags.ScheduledProcedureStepStartTime].SetStringValue(GetTimeStringOnly(row.ExamScheduledDateAndTime));
            item[DicomTags.Modality].SetStringValue(row.Modality);
            item[DicomTags.PerformedProcedureStepId].SetStringValue(string.Format("{0}", row.ProcedureStepID)); //O M K supported
            item[DicomTags.ScheduledProcedureStepLocation].SetStringValue(row.ExamRoom);                        //return type 2 -O M K supported
            item[DicomTags.ScheduledProcedureStepDescription].SetStringValue(row.ExamDescription);              //return type 2 -O M K supported
            dicomAttribute.AddSequenceItem(item);
        }
예제 #8
0
        public void TestSequenceImplicitVr2()
        {
            var syntax = TransferSyntax.ImplicitVrLittleEndian;
            var sq     = new DicomAttributeSQ(DicomTags.IconImageSequence);

            var item1 = new DicomSequenceItem();

            item1[DicomTags.AccessionNumber].SetStringValue("ABCDEFG");
            sq.AddSequenceItem(item1);

            var item2 = new DicomSequenceItem();

            item2[DicomTags.AccessionNumber].SetStringValue("XYZ");
            sq.AddSequenceItem(item2);

            // note: both sequence and item delimiter tags are calculated as part of the sequence - the item considers only the total length of its contents

            // item1_length = contents(16)
            Assert.AreEqual(16, item1[DicomTags.AccessionNumber].CalculateWriteLength(syntax, DicomWriteOptions.None), "Attr1 Length");
            Assert.AreEqual(16, item1.CalculateWriteLength(syntax, DicomWriteOptions.None), "Item1 Length");

            // item2_length = contents(12)
            Assert.AreEqual(12, item2[DicomTags.AccessionNumber].CalculateWriteLength(syntax, DicomWriteOptions.None), "Attr2 Length");
            Assert.AreEqual(12, item2.CalculateWriteLength(syntax, DicomWriteOptions.None), "Item2 Length");

            // sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16) + item_delimiter_tag(4) + item_delimiter_len(4)
            //                             + item_tag(4) + item_len(4) + item2_length(12) + item_delimiter_tag(4) + item_delimiter_len(4)
            //                             + sq_delimiter_tag(4) + sq_delimiter_len(4)
            var options = DicomWriteOptions.None;

            Assert.AreEqual(76, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

            // sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16) + item_delimiter_tag(4) + item_delimiter_len(4)
            //                             + item_tag(4) + item_len(4) + item2_length(12) + item_delimiter_tag(4) + item_delimiter_len(4)
            options = DicomWriteOptions.ExplicitLengthSequence;
            Assert.AreEqual(68, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

            // sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16)
            //                             + item_tag(4) + item_len(4) + item2_length(12)
            //                             + sq_delimiter_tag(4) + sq_delimiter_len(4)
            options = DicomWriteOptions.ExplicitLengthSequenceItem;
            Assert.AreEqual(60, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

            // sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16)
            //                             + item_tag(4) + item_len(4) + item2_length(12)
            options = DicomWriteOptions.ExplicitLengthSequence | DicomWriteOptions.ExplicitLengthSequenceItem;
            Assert.AreEqual(52, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);
        }
예제 #9
0
        private static List <VoiDataLut> Create(DicomAttributeSQ voiLutSequence, DicomAttributeSQ modalityLutSequence, int pixelRepresentation)
        {
            ModalityDataLut modalityLut = ModalityDataLut.Create(modalityLutSequence, pixelRepresentation);

            if (modalityLut == null)
            {
                throw new DicomDataException("Input Modality Lut Sequence is not valid.");
            }

            //Hounsfield units are always signed.
            bool isFirstMappedPixelValueSigned = pixelRepresentation != 0 || modalityLut.ModalityLutType == "HU";

            List <DataLut> dataLuts = Create(voiLutSequence, isFirstMappedPixelValueSigned, false);

            return(Convert(dataLuts));
        }
예제 #10
0
            private static DicomAttribute AddAttributeToResult(DicomTagPath atrributePath, DicomAttributeCollection result)
            {
                int i = 0;

                while (i < atrributePath.TagsInPath.Count - 1)
                {
                    DicomAttributeSQ sequence = (DicomAttributeSQ)result[atrributePath.TagsInPath[i++]];
                    if (sequence.IsEmpty)
                    {
                        sequence.AddSequenceItem(new DicomSequenceItem());
                    }

                    result = ((DicomSequenceItem[])sequence.Values)[0];
                }

                return(result[atrributePath.TagsInPath[i]]);
            }
예제 #11
0
        private static List <VoiDataLut> Create(DicomAttributeSQ voiLutSequence, int bitsStored, int pixelRepresentation, double rescaleSlope, double rescaleIntercept)
        {
            int  minPixelValue;
            int  maxPixelValue;
            bool isSigned = pixelRepresentation != 0;

            GetMinMaxPixelValue(bitsStored, isSigned, out minPixelValue, out maxPixelValue);

            double minModalityLutValue = minPixelValue * rescaleSlope + rescaleIntercept;
            double maxModalityLutValue = maxPixelValue * rescaleSlope + rescaleIntercept;

            bool isFirstMappedPixelValueSigned = minModalityLutValue < 0 || maxModalityLutValue < 0;

            List <DataLut> dataLuts = Create(voiLutSequence, isFirstMappedPixelValueSigned, false);

            return(Convert(dataLuts));
        }
예제 #12
0
		public void TestSequenceImplicitVr2()
		{
			var syntax = TransferSyntax.ImplicitVrLittleEndian;
			var sq = new DicomAttributeSQ(DicomTags.IconImageSequence);

			var item1 = new DicomSequenceItem();
			item1[DicomTags.AccessionNumber].SetStringValue("ABCDEFG");
			sq.AddSequenceItem(item1);

			var item2 = new DicomSequenceItem();
			item2[DicomTags.AccessionNumber].SetStringValue("XYZ");
			sq.AddSequenceItem(item2);

			// note: both sequence and item delimiter tags are calculated as part of the sequence - the item considers only the total length of its contents

			// item1_length = contents(16)
			Assert.AreEqual(16, item1[DicomTags.AccessionNumber].CalculateWriteLength(syntax, DicomWriteOptions.None), "Attr1 Length");
			Assert.AreEqual(16, item1.CalculateWriteLength(syntax, DicomWriteOptions.None), "Item1 Length");

			// item2_length = contents(12)
			Assert.AreEqual(12, item2[DicomTags.AccessionNumber].CalculateWriteLength(syntax, DicomWriteOptions.None), "Attr2 Length");
			Assert.AreEqual(12, item2.CalculateWriteLength(syntax, DicomWriteOptions.None), "Item2 Length");

			// sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16) + item_delimiter_tag(4) + item_delimiter_len(4)
			//                             + item_tag(4) + item_len(4) + item2_length(12) + item_delimiter_tag(4) + item_delimiter_len(4)
			//                             + sq_delimiter_tag(4) + sq_delimiter_len(4)
			var options = DicomWriteOptions.None;
			Assert.AreEqual(76, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

			// sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16) + item_delimiter_tag(4) + item_delimiter_len(4)
			//                             + item_tag(4) + item_len(4) + item2_length(12) + item_delimiter_tag(4) + item_delimiter_len(4)
			options = DicomWriteOptions.ExplicitLengthSequence;
			Assert.AreEqual(68, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

			// sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16)
			//                             + item_tag(4) + item_len(4) + item2_length(12)
			//                             + sq_delimiter_tag(4) + sq_delimiter_len(4)
			options = DicomWriteOptions.ExplicitLengthSequenceItem;
			Assert.AreEqual(60, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

			// sq_length = tag(4) + len(4) + item_tag(4) + item_len(4) + item1_length(16)
			//                             + item_tag(4) + item_len(4) + item2_length(12)
			options = DicomWriteOptions.ExplicitLengthSequence | DicomWriteOptions.ExplicitLengthSequenceItem;
			Assert.AreEqual(52, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);
		}
예제 #13
0
        private static IList <SourceImageInfo> LoadSourceImageInfo(DicomAttributeCollection collection)
        {
            if (collection.Contains(DicomTags.SourceImageSequence))
            {
                DicomAttributeSQ        sq   = collection[DicomTags.SourceImageSequence] as DicomAttributeSQ;
                IList <SourceImageInfo> list = new List <SourceImageInfo>();
                foreach (DicomSequenceItem item in sq.Values as DicomSequenceItem[])
                {
                    list.Add(new SourceImageInfo()
                    {
                        SopInstanceUid = item[DicomTags.ReferencedSopInstanceUid].ToString()
                    });
                }
                return(list);
            }

            return(null);
        }
예제 #14
0
        private void AddSourceImageSequence(DicomFile file, string oldSopUid)
        {
            DicomAttributeSQ sourceImageSq;

            if (!file.DataSet.Contains(DicomTags.SourceImageSequence))
            {
                sourceImageSq = new DicomAttributeSQ(DicomTags.SourceImageSequence);
                file.DataSet[DicomTags.SourceImageSequence] = sourceImageSq;
            }
            else
            {
                sourceImageSq = file.DataSet[DicomTags.SourceImageSequence] as DicomAttributeSQ;
            }

            DicomSequenceItem item = new DicomSequenceItem();

            item[DicomTags.ReferencedSopClassUid].SetStringValue(file.SopClass.Uid);
            item[DicomTags.ReferencedSopInstanceUid].SetStringValue(oldSopUid);
            sourceImageSq.AddSequenceItem(item);
        }
예제 #15
0
        public static List <DataLut> Create(DicomAttributeSQ sequence, bool isFirstMappedPixelSigned, bool isLutDataSigned)
        {
            if (sequence == null)
            {
                throw new ArgumentNullException("sequence");
            }

            if (sequence.IsEmpty || sequence.IsNull)
            {
                return(new List <DataLut>());
            }

            DicomSequenceItem[] sequenceItems = sequence.Values as DicomSequenceItem[];
            if (sequenceItems == null || sequenceItems.Length == 0)
            {
                return(new List <DataLut>());
            }

            return(Create(sequenceItems, isFirstMappedPixelSigned, isLutDataSigned));
        }
예제 #16
0
		public void TestSequenceImplicitVr()
		{
			var syntax = TransferSyntax.ImplicitVrLittleEndian;
			var sq = new DicomAttributeSQ(DicomTags.IconImageSequence);

			// note: we handle an empty sequence (0 items) by explicitly encoding zero length regardless of options

			// sq_length = tag(4) + len(4)
			var options = DicomWriteOptions.None;
			Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

			// sq_length = tag(4) + len(4)
			options = DicomWriteOptions.ExplicitLengthSequence;
			Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

			// sq_length = tag(4) + len(4)
			options = DicomWriteOptions.ExplicitLengthSequenceItem;
			Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

			// sq_length = tag(4) + len(4)
			options = DicomWriteOptions.ExplicitLengthSequence | DicomWriteOptions.ExplicitLengthSequenceItem;
			Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);
		}
        public static DicomSequenceItem CreateOriginalAttributesSequence(IEnumerable <DicomAttribute> originalValues,
                                                                         string originalAttributesSource, string modifyingSystem, string reasonForModification)
        {
            DicomSequenceItem item = new DicomSequenceItem();

            item[DicomTags.AttributeModificationDatetime]
            .SetDateTime(0, DateTime.Now);
            if (!string.IsNullOrEmpty(originalAttributesSource))
            {
                item[DicomTags.SourceOfPreviousValues]
                .SetStringValue(originalAttributesSource);
            }
            if (!string.IsNullOrEmpty(modifyingSystem))
            {
                item[DicomTags.ModifyingSystem]
                .SetStringValue(modifyingSystem);
            }
            if (!string.IsNullOrEmpty(reasonForModification))
            {
                item[DicomTags.ReasonForTheAttributeModification]
                .SetStringValue(reasonForModification);
            }
            DicomAttributeSQ sq =
                new DicomAttributeSQ(DicomTags.ModifiedAttributesSequence);

            item[sq.Tag] = sq;

            DicomSequenceItem modified = new DicomSequenceItem();

            sq.AddSequenceItem(modified);

            foreach (DicomAttribute value in originalValues)
            {
                modified[value.Tag] = value;
            }
            return(item);
        }
예제 #18
0
        private void CreateSequence(List <string> elements, int currentElementIndex, DicomAttributeCollection dicomRequest, string value)
        {
            uint tag = uint.Parse(elements[currentElementIndex], System.Globalization.NumberStyles.HexNumber);   //TODO: need to handle the case of keywords

            DicomAttributeSQ  sequence = dicomRequest[tag] as DicomAttributeSQ;
            DicomSequenceItem item;


            if (sequence.Count > 0)
            {
                item = sequence[0];
            }
            else
            {
                item = new DicomSequenceItem( );

                sequence.AddSequenceItem(item);
            }

            for (int index = (currentElementIndex + 1); index < elements.Count; index++)
            {
                tag = uint.Parse(elements[index], System.Globalization.NumberStyles.HexNumber);

                DicomAttribute childElement = item[tag];  //TODO: if item.Contains(tag)??? throw error?

                if (childElement.Tag.VR.Equals(DicomVr.SQvr))
                {
                    CreateSequence(elements, index, item, value);

                    break;
                }
                else
                {
                    childElement.SetStringValue(value);
                }
            }
        }
예제 #19
0
        public void TestSequenceImplicitVr()
        {
            var syntax = TransferSyntax.ImplicitVrLittleEndian;
            var sq     = new DicomAttributeSQ(DicomTags.IconImageSequence);

            // note: we handle an empty sequence (0 items) by explicitly encoding zero length regardless of options

            // sq_length = tag(4) + len(4)
            var options = DicomWriteOptions.None;

            Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

            // sq_length = tag(4) + len(4)
            options = DicomWriteOptions.ExplicitLengthSequence;
            Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

            // sq_length = tag(4) + len(4)
            options = DicomWriteOptions.ExplicitLengthSequenceItem;
            Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);

            // sq_length = tag(4) + len(4)
            options = DicomWriteOptions.ExplicitLengthSequence | DicomWriteOptions.ExplicitLengthSequenceItem;
            Assert.AreEqual(8, sq.CalculateWriteLength(syntax, options), "SQ Length (Options={0})", options);
        }
예제 #20
0
        private static bool TryGetAttributeSQ(IDicomAttributeProvider provider, uint tag, out DicomAttributeSQ dicomAttributeSQ)
        {
            DicomAttribute dicomAttribute;

            if (provider.TryGetAttribute(tag, out dicomAttribute))
            {
                dicomAttributeSQ = dicomAttribute as DicomAttributeSQ;
                return(dicomAttributeSQ != null);
            }
            dicomAttributeSQ = null;
            return(false);
        }
예제 #21
0
        /// <summary>
        /// This methid generate an XmlElement that contains the data necessary
        /// to create Performed Series Sequences.
        /// If modality return
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        private static XmlElement GenerateXmlForPerformedSeriesSQ(DicomMessage message, string studyInstanceUID)
        {
            #region Sample Generated Node

            /*
             * <Root>
             * <Series>
             *    <Images>
             *    <Image/>             *
             * </Series>
             * <Series>
             *    <Images>
             *    <Image/>             *
             * </Series>
             * </Root>
             */
            #endregion

            XmlDocument dom    = new XmlDocument();
            XmlElement  result = dom.CreateElement("Root");

            dom.AppendChild(result);

            //get StudyIsntanceUID
            DicomAttribute attribute = message.DataSet[DicomTags.PerformedSeriesSequence];

            DicomAttributeSQ seriesSequence = attribute as DicomAttributeSQ;
            //sequence.Count   should be at least 1.

            for (int i = 0; i < seriesSequence.Count; i++)
            {
                DicomSequenceItem  seriesSqItem = seriesSequence[i];
                System.Xml.XmlNode newSeries;
                newSeries = dom.CreateElement("Series");
                //Set Attributes
                newSeries.Attributes.Append(dom.CreateAttribute("StudyInstanceUID")).Value =
                    seriesSqItem[DicomTags.StudyInstanceUid].GetString(0, "");
                newSeries.Attributes.Append(dom.CreateAttribute("PerformingPhysicianName")).Value =
                    seriesSqItem[DicomTags.PerformingPhysiciansName].GetString(0, "");
                string seriesInstanceUID = seriesSqItem[DicomTags.SeriesInstanceUid].GetString(0, DicomUid.GenerateUid().UID);
                newSeries.Attributes.Append(dom.CreateAttribute("SeriesInstanceUID")).Value = seriesInstanceUID;

                newSeries.Attributes.Append(dom.CreateAttribute("OperatorName")).Value =
                    seriesSqItem[DicomTags.OperatorsName].GetString(0, "");
                newSeries.Attributes.Append(dom.CreateAttribute("ProtocolName")).Value =
                    seriesSqItem[DicomTags.ProtocolName].GetString(0, "");
                newSeries.Attributes.Append(dom.CreateAttribute("SeriesDescription")).Value =
                    seriesSqItem[DicomTags.SeriesDescription].GetString(0, "");
                newSeries.Attributes.Append(dom.CreateAttribute("RetrieveAET")).Value =
                    seriesSqItem[DicomTags.RetrieveAeTitle].GetString(0, "");

                #region loop over Referenced Image Sequence
                //DicomAttribute referencedImageSQ = seriesSqItem.DataSet[DicomTags.ReferencedImageSequence];

                #region ReferencedImageSequence
                DicomAttributeSQ imagesSequence = (seriesSqItem[DicomTags.ReferencedImageSequence]) as DicomAttributeSQ;

                for (int j = 0; j < imagesSequence.Count; j++)
                {
                    DicomSequenceItem  imagesSeqItem = imagesSequence[j];
                    System.Xml.XmlNode newImage;
                    newImage = dom.CreateElement("Image");
                    //Set Attributes
                    newImage.Attributes.Append(dom.CreateAttribute("SeriesInstanceUID")).Value          = seriesInstanceUID;
                    newImage.Attributes.Append(dom.CreateAttribute("ReferencedImageSopClassUID")).Value =
                        imagesSeqItem[DicomTags.ReferencedSopClassUid].GetString(0, "");
                    newImage.Attributes.Append(dom.CreateAttribute("ReferencedImageSopInstanceUID")).Value =
                        imagesSeqItem[DicomTags.ReferencedSopInstanceUid].GetString(0, DicomUid.GenerateUid().UID);
                    newSeries.AppendChild(newImage);
                }
                #endregion

                #region ReferencedNonImageCompositeSopInstanceSequence
                DicomAttributeSQ nonImageCompositeSequence = (seriesSqItem[DicomTags.ReferencedNonImageCompositeSopInstanceSequence]) as DicomAttributeSQ;
                for (int k = 0; k < imagesSequence.Count; k++)
                {
                    DicomSequenceItem  nonImagesCompositeSeqItem = nonImageCompositeSequence[k];
                    System.Xml.XmlNode newNonImageComposite;
                    newNonImageComposite = dom.CreateElement("Image");
                    //Set Attributes
                    newNonImageComposite.Attributes.Append(dom.CreateAttribute("SeriesInstanceUID")).Value          = seriesInstanceUID;
                    newNonImageComposite.Attributes.Append(dom.CreateAttribute("ReferencedImageSopClassUID")).Value =
                        nonImagesCompositeSeqItem[DicomTags.ReferencedSopClassUid].GetString(0, "");
                    newNonImageComposite.Attributes.Append(dom.CreateAttribute("ReferencedImageSopInstanceUID")).Value =
                        nonImagesCompositeSeqItem[DicomTags.ReferencedSopInstanceUid].GetString(0, DicomUid.GenerateUid().UID);
                    newSeries.AppendChild(newNonImageComposite);
                }
                #endregion

                #endregion
                result.AppendChild(newSeries);
            }

            return(result);
        }
예제 #22
0
        public DicomWriteStatus Write(TransferSyntax syntax, DicomAttributeCollection dataset, DicomWriteOptions options)
        {
            TransferSyntax = syntax;

            foreach (DicomAttribute item in dataset)
            {
                if (item.Tag.Element == 0x0000)
                {
                    continue;
                }

                if (item.IsEmpty)
                {
                    continue;
                }

                if (Flags.IsSet(options, DicomWriteOptions.CalculateGroupLengths) &&
                    item.Tag.Group != _group && item.Tag.Group <= 0x7fe0)
                {
                    _group = item.Tag.Group;
                    _writer.Write((ushort)_group);
                    _writer.Write((ushort)0x0000);
                    if (_syntax.ExplicitVr)
                    {
                        _writer.Write((byte)'U');
                        _writer.Write((byte)'L');
                        _writer.Write((ushort)4);
                    }
                    else
                    {
                        _writer.Write((uint)4);
                    }
                    _writer.Write((uint)dataset.CalculateGroupWriteLength(_group, _syntax, options));
                }

                _writer.Write((ushort)item.Tag.Group);
                _writer.Write((ushort)item.Tag.Element);

                if (_syntax.ExplicitVr)
                {
                    _writer.Write((byte)item.Tag.VR.Name[0]);
                    _writer.Write((byte)item.Tag.VR.Name[1]);
                }

                if (item is DicomAttributeSQ)
                {
                    DicomAttributeSQ sq = item as DicomAttributeSQ;

                    if (_syntax.ExplicitVr)
                    {
                        _writer.Write((ushort)0x0000);
                    }

                    if (Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequence))
                    {
                        int hl = _syntax.ExplicitVr ? 12 : 8;
                        _writer.Write((uint)sq.CalculateWriteLength(_syntax, options & ~DicomWriteOptions.CalculateGroupLengths) - (uint)hl);
                    }
                    else
                    {
                        _writer.Write((uint)UndefinedLength);
                    }

                    foreach (DicomSequenceItem ids in item.Values as DicomSequenceItem[])
                    {
                        _writer.Write((ushort)DicomTag.Item.Group);
                        _writer.Write((ushort)DicomTag.Item.Element);

                        if (Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequenceItem))
                        {
                            _writer.Write((uint)ids.CalculateWriteLength(_syntax, options & ~DicomWriteOptions.CalculateGroupLengths));
                        }
                        else
                        {
                            _writer.Write((uint)UndefinedLength);
                        }

                        Write(this.TransferSyntax, ids, options & ~DicomWriteOptions.CalculateGroupLengths);

                        if (!Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequenceItem))
                        {
                            _writer.Write((ushort)DicomTag.ItemDelimitationItem.Group);
                            _writer.Write((ushort)DicomTag.ItemDelimitationItem.Element);
                            _writer.Write((uint)0x00000000);
                        }
                    }

                    if (!Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequence))
                    {
                        _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Group);
                        _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Element);
                        _writer.Write((uint)0x00000000);
                    }
                }

                else if (item is DicomFragmentSequence)
                {
                    DicomFragmentSequence fs = item as DicomFragmentSequence;

                    if (_syntax.ExplicitVr)
                    {
                        _writer.Write((ushort)0x0000);
                    }
                    _writer.Write((uint)UndefinedLength);

                    _writer.Write((ushort)DicomTag.Item.Group);
                    _writer.Write((ushort)DicomTag.Item.Element);

                    if (Flags.IsSet(options, DicomWriteOptions.WriteFragmentOffsetTable) && fs.HasOffsetTable)
                    {
                        _writer.Write((uint)fs.OffsetTableBuffer.Length);
                        fs.OffsetTableBuffer.CopyTo(_writer);
                    }
                    else
                    {
                        _writer.Write((uint)0x00000000);
                    }

                    foreach (DicomFragment bb in fs.Fragments)
                    {
                        _writer.Write((ushort)DicomTag.Item.Group);
                        _writer.Write((ushort)DicomTag.Item.Element);
                        _writer.Write((uint)bb.Length);
                        bb.GetByteBuffer(_syntax).CopyTo(_writer);
                    }

                    _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Group);
                    _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Element);
                    _writer.Write((uint)0x00000000);
                }
                else
                {
                    DicomAttribute de      = item;
                    ByteBuffer     theData = de.GetByteBuffer(_syntax, dataset.SpecificCharacterSet);
                    if (_syntax.ExplicitVr)
                    {
                        if (de.Tag.VR.Is16BitLengthField)
                        {
                            // #10890: Can't encode the value length if the length of the data exceeds max value for a 16-bit field
                            if (theData.Length > ushort.MaxValue - 1 /* must be even length so max allowed = 65534 */)
                            {
                                throw new DicomDataException(string.Format(
                                                                 "Value for {0} exceeds maximum stream length allowed for a {1} VR attribute encoded using {2}",
                                                                 de.Tag, de.Tag.VR, _syntax));
                            }
                            _writer.Write((ushort)theData.Length);
                        }
                        else
                        {
                            _writer.Write((ushort)0x0000);
                            _writer.Write((uint)theData.Length);
                        }
                    }
                    else
                    {
                        _writer.Write((uint)theData.Length);
                    }

                    if (theData.Length > 0)
                    {
                        theData.CopyTo(_writer);
                    }
                }
            }

            return(DicomWriteStatus.Success);
        }
예제 #23
0
        private bool CheckForMissingRequiredMatchingKey(DicomServer server, byte presentationID, DicomMessage message)
        {
            DicomAttribute attrib;
            bool           requiredMatchingKeyMissing = false;
            string         comment = ""; // will receive a description of the first encountred missing r key.

            // we don't need to collect all missing keys to speed up processing.
            do
            {
                attrib = message.DataSet[DicomTags.ScheduledProcedureStepSequence];
                if (attrib.IsNull)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Missing Scheduled Procedure Step Sequence";
                    break;
                }
                DicomAttributeSQ sequence = attrib as DicomAttributeSQ;
                if (attrib.Count == 0)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Scheduled Procedure Step Sequence is empty";
                    break;
                }
                if (attrib.Count > 1)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Found Multiple Items in Scheduled Procedure Step Sequence";
                    break;
                }

                DicomSequenceItem sequenceSubItems = sequence[0];

                if (sequenceSubItems[DicomTags.ScheduledStationAeTitle].IsNull)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Missing Scheduled Station Ae Title";
                    break;
                }

                if (sequenceSubItems[DicomTags.Modality].IsNull)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Missing Modality";
                    break;
                }

                if (sequenceSubItems[DicomTags.ScheduledPerformingPhysiciansName].IsNull)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Missing Scheduled Performing Physicians Name";
                    break;
                }

                if (sequenceSubItems[DicomTags.ScheduledProcedureStepStartDate].IsNull)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Missing ScheduledProcedureStepStartDate";
                    break;
                }

                if (sequenceSubItems[DicomTags.ScheduledProcedureStepStartTime].IsNull)
                {
                    requiredMatchingKeyMissing = true;
                    comment = "Missing Scheduled Procedure Step Start Time";
                    break;
                }
            } while (false);

            // send specific error status to the calling AE
            if (requiredMatchingKeyMissing)
            {
                Platform.Log(LogLevel.Error, "Required matching key missing on query from {0}," +
                             "\n Sending Failure Status Identifier Does Not Match SOPClass.",
                             server.AssociationParams.CallingAE);
                Platform.Log(LogLevel.Error, "Error Details : {0}", comment);
                DicomMessage errorResponse = new DicomMessage();
                server.SendCFindResponse(presentationID, message.MessageId, errorResponse,
                                         DicomStatuses.QueryRetrieveIdentifierDoesNotMatchSOPClass);
            }

            return(requiredMatchingKeyMissing);
        }
예제 #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SequenceIodList&lt;T&gt;"/> class.
 /// </summary>
 /// <param name="tag">The tag.</param>
 public SequenceIodList(uint tag)
 {
     _dicomAttributeSQ = new DicomAttributeSQ(tag);
 }
예제 #25
0
        private static void ParseAttribute(DicomAttributeCollection theCollection, XmlNode attributeNode)
        {
            if (attributeNode.Name.Equals("Attribute"))
            {
                DicomTag theTag = GetTagFromAttributeNode(attributeNode);

                DicomAttribute attribute = theCollection[theTag];
                if (attribute is DicomAttributeSQ)
                {
                    DicomAttributeSQ attribSQ = (DicomAttributeSQ)attribute;
                    //set the null value in case there are no child nodes.
                    attribute.SetNullValue();

                    if (attributeNode.HasChildNodes)
                    {
                        XmlNode itemNode = attributeNode.FirstChild;

                        while (itemNode != null)
                        {
                            DicomSequenceItem theItem = new InstanceXmlDicomSequenceItem();

                            ParseCollection(theItem, itemNode);

                            attribSQ.AddSequenceItem(theItem);

                            itemNode = itemNode.NextSibling;
                        }
                    }
                }
                else
                {
                    // Cleanup the common XML character replacements
                    string tempString = attributeNode.InnerText;
                    tempString = XmlUnescapeString(tempString);
                    try
                    {
                        attribute.SetStringValue(tempString);
                    }
                    catch (Exception e)
                    {
                        Platform.Log(LogLevel.Error, e,
                                     "Unexpected exception with tag {0} setting value '{1}'.  Ignoring tag value.",
                                     attribute.Tag,
                                     tempString);
                    }

                    ((IPrivateInstanceXmlDicomAttributeCollection)theCollection).ExcludedTagsHelper.Remove(theTag);
                }
            }
            else if (attributeNode.Name.Equals("EmptyAttribute"))
            {
                //Means that the tag should not be in this collection, but is in the base.  So, we remove it.
                DicomTag theTag = GetTagFromAttributeNode(attributeNode);

                //NOTE: we want these attributes to be in the collection and empty so that
                //the base collection doesn't need to be modified in order to insert
                //excluded tags in the correct order.
                theCollection[theTag].SetEmptyValue();

                ((IPrivateInstanceXmlDicomAttributeCollection)theCollection).ExcludedTagsHelper.Remove(theTag);
            }
            else if (attributeNode.Name.Equals("ExcludedAttribute"))
            {
                DicomTag theTag = GetTagFromAttributeNode(attributeNode);

                //NOTE: we want these attributes to be in the collection and empty so that
                //the base collection doesn't need to be modified in order to insert
                //excluded tags in the correct order.
                theCollection[theTag].SetEmptyValue();

                ((IPrivateInstanceXmlDicomAttributeCollection)theCollection).ExcludedTagsHelper.Add(theTag);
            }
        }
예제 #26
0
		private static List<VoiDataLut> Create(DicomAttributeSQ voiLutSequence, int pixelRepresentation)
		{
			bool isFirstMappedPixelSigned = pixelRepresentation != 0;

			List<DataLut> dataLuts = Create(voiLutSequence, isFirstMappedPixelSigned, false);
			return Convert(dataLuts);
		}
예제 #27
0
		private static List<VoiDataLut> Create(DicomAttributeSQ voiLutSequence, int bitsStored, int pixelRepresentation, double rescaleSlope, double rescaleIntercept)
		{
			int minPixelValue;
			int maxPixelValue;
			bool isSigned = pixelRepresentation != 0;

			GetMinMaxPixelValue(bitsStored, isSigned, out minPixelValue, out maxPixelValue);

			double minModalityLutValue = minPixelValue*rescaleSlope + rescaleIntercept;
			double maxModalityLutValue = maxPixelValue*rescaleSlope + rescaleIntercept;

			bool isFirstMappedPixelValueSigned = minModalityLutValue < 0 || maxModalityLutValue < 0;

			List<DataLut> dataLuts = Create(voiLutSequence, isFirstMappedPixelValueSigned, false);
			return Convert(dataLuts);
		}
예제 #28
0
		private static List<VoiDataLut> Create(DicomAttributeSQ voiLutSequence, DicomAttributeSQ modalityLutSequence, int pixelRepresentation)
		{
			ModalityDataLut modalityLut = ModalityDataLut.Create(modalityLutSequence, pixelRepresentation);
			if (modalityLut == null)
				throw new DicomDataException("Input Modality Lut Sequence is not valid.");

			//Hounsfield units are always signed.
			bool isFirstMappedPixelValueSigned = pixelRepresentation != 0 || modalityLut.ModalityLutType == "HU";

			List<DataLut> dataLuts = Create(voiLutSequence, isFirstMappedPixelValueSigned, false);
			return Convert(dataLuts);
		}
예제 #29
0
		private static bool TryGetAttributeSQ(IDicomAttributeProvider provider, uint tag, out DicomAttributeSQ dicomAttributeSQ)
		{
			DicomAttribute dicomAttribute;
			if (provider.TryGetAttribute(tag, out dicomAttribute))
			{
				dicomAttributeSQ = dicomAttribute as DicomAttributeSQ;
				return dicomAttributeSQ != null;
			}
			dicomAttributeSQ = null;
			return false;
		}
예제 #30
0
        private void OnReceiveMWLQuery(DicomServer server, byte presentationID, DicomMessage message)
        {
            #region Non conformance checking    - Unsopported Optional matching key checking

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

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

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

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

            string sqlWhereClause = " where 1=1 ";

            DicomAttributeCollection data = message.DataSet;

            string specificCharacterSet = "";

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

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

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

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

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

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

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

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

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

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

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

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

                            default:
                                break;
                            }
                        }
                        break;
                        #endregion

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

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

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

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

                    default:
                        break;
                    }
                }
            }

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

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

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

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

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


            DicomMessage finalResponse = new DicomMessage();
            server.SendCFindResponse(presentationID, message.MessageId, finalResponse, DicomStatuses.Success);
            return;
        }
예제 #31
0
        public DicomWriteStatus Write(TransferSyntax syntax, DicomAttributeCollection dataset, DicomWriteOptions options)
        {
            TransferSyntax = syntax;

            foreach (DicomAttribute item in dataset)
            {
                if (item.Tag.Element == 0x0000)
                {
                    continue;
                }

                if (item.IsEmpty)
                {
                    continue;
                }

                if (Flags.IsSet(options, DicomWriteOptions.CalculateGroupLengths) &&
                    item.Tag.Group != _group && item.Tag.Group <= 0x7fe0)
                {
                    _group = item.Tag.Group;
                    _writer.Write((ushort)_group);
                    _writer.Write((ushort)0x0000);
                    if (_syntax.ExplicitVr)
                    {
                        _writer.Write((byte)'U');
                        _writer.Write((byte)'L');
                        _writer.Write((ushort)4);
                    }
                    else
                    {
                        _writer.Write((uint)4);
                    }
                    _writer.Write((uint)dataset.CalculateGroupWriteLength(_group, _syntax, options));
                }

                _writer.Write((ushort)item.Tag.Group);
                _writer.Write((ushort)item.Tag.Element);

                if (_syntax.ExplicitVr)
                {
                    _writer.Write((byte)item.Tag.VR.Name[0]);
                    _writer.Write((byte)item.Tag.VR.Name[1]);
                }

                if (item is DicomAttributeSQ)
                {
                    DicomAttributeSQ sq = item as DicomAttributeSQ;

                    if (_syntax.ExplicitVr)
                    {
                        _writer.Write((ushort)0x0000);
                    }

                    if (Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequence))
                    {
                        int hl = _syntax.ExplicitVr ? 12 : 8;
                        _writer.Write((uint)sq.CalculateWriteLength(_syntax, options & ~DicomWriteOptions.CalculateGroupLengths) - (uint)hl);
                    }
                    else
                    {
                        _writer.Write((uint)UndefinedLength);
                    }

                    foreach (DicomSequenceItem ids in item.Values as DicomSequenceItem[])
                    {
                        _writer.Write((ushort)DicomTag.Item.Group);
                        _writer.Write((ushort)DicomTag.Item.Element);

                        if (Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequenceItem))
                        {
                            _writer.Write((uint)ids.CalculateWriteLength(_syntax, options & ~DicomWriteOptions.CalculateGroupLengths));
                        }
                        else
                        {
                            _writer.Write((uint)UndefinedLength);
                        }

                        Write(this.TransferSyntax, ids, options & ~DicomWriteOptions.CalculateGroupLengths);

                        if (!Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequenceItem))
                        {
                            _writer.Write((ushort)DicomTag.ItemDelimitationItem.Group);
                            _writer.Write((ushort)DicomTag.ItemDelimitationItem.Element);
                            _writer.Write((uint)0x00000000);
                        }
                    }

                    if (!Flags.IsSet(options, DicomWriteOptions.ExplicitLengthSequence))
                    {
                        _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Group);
                        _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Element);
                        _writer.Write((uint)0x00000000);
                    }
                }

                else if (item is DicomFragmentSequence)
                {
                    DicomFragmentSequence fs = item as DicomFragmentSequence;

                    if (_syntax.ExplicitVr)
                    {
                        _writer.Write((ushort)0x0000);
                    }
                    _writer.Write((uint)UndefinedLength);

                    _writer.Write((ushort)DicomTag.Item.Group);
                    _writer.Write((ushort)DicomTag.Item.Element);

                    if (Flags.IsSet(options, DicomWriteOptions.WriteFragmentOffsetTable) && fs.HasOffsetTable)
                    {
                        _writer.Write((uint)fs.OffsetTableBuffer.Length);
                        fs.OffsetTableBuffer.CopyTo(_writer);
                    }
                    else
                    {
                        _writer.Write((uint)0x00000000);
                    }

                    foreach (DicomFragment bb in fs.Fragments)
                    {
                        _writer.Write((ushort)DicomTag.Item.Group);
                        _writer.Write((ushort)DicomTag.Item.Element);
                        _writer.Write((uint)bb.Length);
                        bb.GetByteBuffer(_syntax).CopyTo(_writer);
                    }

                    _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Group);
                    _writer.Write((ushort)DicomTag.SequenceDelimitationItem.Element);
                    _writer.Write((uint)0x00000000);
                }
                else
                {
                    DicomAttribute de      = item;
                    ByteBuffer     theData = de.GetByteBuffer(_syntax, dataset.SpecificCharacterSet);
                    if (_syntax.ExplicitVr)
                    {
                        if (de.Tag.VR.Is16BitLengthField)
                        {
                            _writer.Write((ushort)theData.Length);
                        }
                        else
                        {
                            _writer.Write((ushort)0x0000);
                            _writer.Write((uint)theData.Length);
                        }
                    }
                    else
                    {
                        _writer.Write((uint)theData.Length);
                    }

                    if (theData.Length > 0)
                    {
                        theData.CopyTo(_writer);
                    }
                }
            }

            return(DicomWriteStatus.Success);
        }
예제 #32
0
        public SingleImageDisplaySetDescriptor(ISeriesIdentifier sourceSeries, ImageSop imageSop, int position)
            : base(sourceSeries)
        {
            Platform.CheckForNullReference(sourceSeries, "sourceSeries");
            Platform.CheckForNullReference(imageSop, "imageSop");

            _sopInstanceUid    = imageSop.SopInstanceUid;
            _seriesInstanceUid = imageSop.SeriesInstanceUid;
            _position          = position;

            string laterality   = imageSop.ImageLaterality;
            string viewPosition = imageSop.ViewPosition;

            if (string.IsNullOrEmpty(viewPosition))
            {
                DicomAttributeSQ codeSequence = imageSop[DicomTags.ViewCodeSequence] as DicomAttributeSQ;
                if (codeSequence != null && !codeSequence.IsNull && codeSequence.Count > 0)
                {
                    viewPosition = codeSequence[0][DicomTags.CodeMeaning].GetString(0, null);
                }
            }

            string lateralityViewPosition = null;

            if (!String.IsNullOrEmpty(laterality) && !String.IsNullOrEmpty(viewPosition))
            {
                lateralityViewPosition = String.Format("{0}/{1}", laterality, viewPosition);
            }
            else if (!String.IsNullOrEmpty(laterality))
            {
                lateralityViewPosition = laterality;
            }
            else if (!String.IsNullOrEmpty(viewPosition))
            {
                lateralityViewPosition = viewPosition;
            }

            if (sourceSeries.SeriesInstanceUid == imageSop.SeriesInstanceUid)
            {
                if (lateralityViewPosition != null)
                {
                    _suffix = String.Format(SR.SuffixFormatSingleImageDisplaySetWithLateralityViewPosition, lateralityViewPosition, imageSop.InstanceNumber);
                }
                else
                {
                    _suffix = String.Format(SR.SuffixFormatSingleImageDisplaySet, imageSop.InstanceNumber);
                }
            }
            else
            {
                //this is a referenced image (e.g. key image).
                if (lateralityViewPosition != null)
                {
                    _suffix = String.Format(SR.SuffixFormatSingleReferencedImageDisplaySetWithLateralityViewPosition,
                                            lateralityViewPosition, imageSop.SeriesNumber, imageSop.InstanceNumber);
                }
                else
                {
                    _suffix = String.Format(SR.SuffixFormatSingleReferencedImageDisplaySet,
                                            imageSop.SeriesNumber, imageSop.InstanceNumber);
                }
            }
        }
예제 #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SequenceIodList&lt;T&gt;"/> class.
 /// </summary>
 /// <param name="dicomTag">The dicom tag.</param>
 public SequenceIodList(DicomTag dicomTag)
 {
     _dicomAttributeSQ = new DicomAttributeSQ(dicomTag);
 }
예제 #34
0
        public override string GetAnnotationText(IPresentationImage presentationImage)
        {
            string nullString = SR.ValueNil;

            IImageSopProvider provider = presentationImage as IImageSopProvider;

            if (provider == null)
            {
                return("");
            }

            string laterality = null;

            if (_showLaterality)
            {
                laterality = provider.ImageSop.ImageLaterality;
                if (string.IsNullOrEmpty(laterality))
                {
                    laterality = provider.ImageSop.Laterality;
                }
            }

            string viewPosition = null;

            if (_showViewPosition)
            {
                viewPosition = provider.ImageSop.ViewPosition;
                if (string.IsNullOrEmpty(viewPosition))
                {
                    //TODO: later, we could translate to ACR MCQM equivalent, at least for mammo.
                    DicomAttributeSQ codeSequence = provider.ImageSop[DicomTags.ViewCodeSequence] as DicomAttributeSQ;
                    if (codeSequence != null && !codeSequence.IsNull && codeSequence.Count > 0)
                    {
                        viewPosition = codeSequence[0][DicomTags.CodeMeaning].GetString(0, null);
                    }
                }
            }

            string str = "";

            if (_showLaterality && _showViewPosition)
            {
                if (string.IsNullOrEmpty(laterality))
                {
                    laterality = nullString;
                }
                if (string.IsNullOrEmpty(viewPosition))
                {
                    viewPosition = nullString;
                }

                if (laterality == nullString && viewPosition == nullString)
                {
                    str = "";                     // if both parts are null then just show one hyphen (rather than -/-)
                }
                else
                {
                    str = String.Format(SR.FormatLateralityViewPosition, laterality, viewPosition);
                }
            }
            else if (_showLaterality)
            {
                str = laterality;
            }
            else if (_showViewPosition)
            {
                str = viewPosition;
            }

            return(str);
        }
        private static void DoParseAttributes(
            StudyLoaderArgs studyLoaderArgs,
            ParseResult result,
            string metaUri,
            XmlElement elem)
        {
            var collection = result.Attributes;

            collection.ValidateVrValues  = false;
            collection.ValidateVrLengths = false;
            foreach (var node in elem)
            {
                var attrElem = node as XmlElement;
                if (attrElem == null)
                {
                    continue;
                }
                if (!attrElem.Name.Equals("attr"))
                {
                    continue;
                }
                var              dcmTag = GetTagFromAttrElement(attrElem);
                DicomAttribute   attr   = collection[dcmTag];
                DicomAttributeSQ sq     = attr as DicomAttributeSQ;
                if (sq != null)
                {
                    sq.ClearSequenceItems();
                    foreach (XmlNode itemNode in attrElem)
                    {
                        var itemElem = itemNode as XmlElement;
                        if (itemElem != null)
                        {
                            if (itemElem.Name.Equals("item"))
                            {
                                var subResult   = new ParseResult();
                                var subSequence = new DicomSequenceItem();
                                subResult.Attributes = subSequence;
                                DoParseAttributes(studyLoaderArgs, subResult, metaUri, itemElem);
                                sq.AddSequenceItem(subSequence);
                            }
                        }
                    }
                }
                else
                {
                    string val = null;
                    if (attrElem.Attributes["val"] != null)
                    {
                        val = attrElem.Attributes["val"].Value;
                        attr.SetStringValue(val);
                    }
                    else if (attrElem.Attributes["bid"] != null)
                    {
                        // TODO: This tag's value is binary. We're not interested in binary items other
                        // than the pixel data so we ignore them -- they will be added to the
                        // sequence but they will not have any value set.
                        if (attr.Tag.TagValue == DicomTags.PixelData)
                        {
                            result.PixelDataBid = attrElem.Attributes["bid"].Value;
                        }
                    }
                    else if (attrElem.Attributes["bytes"] != null)
                    {
                        // TODO: This tag's value is binary. We're not interested in binary items other
                        // than the pixel data so we ignore them -- they will be added to the
                        // sequence but they will not have any value set.
                        ;
                    }
                    else if (attrElem.Attributes["bsize"] != null)
                    {
                        // TODO: Bulk binary loading can use this.
                    }
                    else
                    {
                        Platform.Log(LogLevel.Warn, "Attr element {0} missing ",
                                     attr.Tag, val);
                    }
                }
            }
        }
예제 #36
0
        private bool CheckForUnSupportedOptionalMatchingKey(DicomServer server, byte presentationID, DicomMessage message,
                                                            bool logFirstUnsupportedAttributeOnly)
        {
            DicomAttribute attrib;
            bool           UnsupportedOptionalMatchingDetected = false;
            string         comments = "";

            do
            {
                // ModalityWorklistIod modalityWorklistIod = new ModalityWorklistIod(message.DataSet);

                attrib = message.DataSet[DicomTags.ScheduledProcedureStepSequence];

                DicomAttributeSQ sequence = attrib as DicomAttributeSQ;

                DicomSequenceItem sequenceSubItems = sequence[0]; //sequence supposed non empty as
                                                                  // it have to be checked by the function
                                                                  // CheckForMissingRequiredMatchingKey() first.

                if (!sequenceSubItems[DicomTags.ScheduledProcedureStepDescription].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Scheduled Procedure Step Description\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                if (!sequenceSubItems[DicomTags.ScheduledStationName].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Scheduled Station Name\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                if (!sequenceSubItems[DicomTags.ScheduledProcedureStepLocation].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Scheduled Procedure Step Location\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                if (!sequenceSubItems[DicomTags.ScheduledProtocolCodeSequence].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Scheduled Protocol Code Sequence\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                if (!sequenceSubItems[DicomTags.PreMedication].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "PreMedication\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                if (!sequenceSubItems[DicomTags.RequestedContrastAgent].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Requested Contrast Agent\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }
                if (!sequenceSubItems[DicomTags.RequestedContrastAgent].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Requested Contrast Agent\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                if (!sequenceSubItems[DicomTags.ScheduledProcedureStepStatus].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Scheduled Procedure Step Status\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                if (!sequenceSubItems[DicomTags.CommentsOnTheScheduledProcedureStep].IsNull)
                {
                    UnsupportedOptionalMatchingDetected = true;
                    comments += "Comments On The Scheduled Procedure Step\n";
                    if (logFirstUnsupportedAttributeOnly)
                    {
                        break;
                    }
                }

                //TODO:  verify the rest of the Optional Matching keys against  your database existing fields in order
                // to send appropriate status.
            } while (false);

            // send specific error status to the calling AE
            if (UnsupportedOptionalMatchingDetected)
            {
                Platform.Log(LogLevel.Warn, "One or more Optional matching Sent by {0} key are note supported.",
                             server.AssociationParams.CallingAE);
                Platform.Log(LogLevel.Warn, "Unsupported Optional Matching Key Attributes Details : {0}", comments);
            }
            return(UnsupportedOptionalMatchingDetected);
        }