Beispiel #1
0
        public bool OnBeginSequence(DicomSequence sequence)
        {
            var tag = String.Format("{0}  {1}", sequence.Tag.ToString().ToUpper(), sequence.Tag.DictionaryEntry.Name);

            TextItems.Add(new DicomTextItem(_level++, tag, "SQ"));
            return(true);
        }
Beispiel #2
0
        private void FillSequenceFromElementRef(DicomDataset rootEleList)
        {
            try
            {
                DicomVR vr = _element.ValueRepresentation;

                if (vr == DicomVR.SQ)
                {
                    Sequence = new DSequence(this);
                    DicomSequence sequence = _element as DicomSequence;
                    for (int i = 0; i < sequence.Items.Count; i++)
                    {
                        DicomDataset list = sequence.Items[i];

                        DElementList dlist = new DElementList(list, rootEleList);
                        Sequence._add(dlist);
                    }
                }
            }
            catch (Exception err)
            {
                DElement errEle = new DElement(_tag, _vr);
                LogMgt.Logger.Write(err.ToString());
            }
        }
Beispiel #3
0
        /// <summary>
        /// Creates a new copy of DICOM dataset with items of VR types considered to be bulk data removed.
        /// </summary>
        /// <param name="dicomDataset">The DICOM dataset.</param>
        /// <returns>A copy of the <paramref name="dicomDataset"/> with items of VR types considered  to be bulk data removed.</returns>
        public static DicomDataset CopyWithoutBulkDataItems(this DicomDataset dicomDataset)
        {
            EnsureArg.IsNotNull(dicomDataset, nameof(dicomDataset));

            return(CopyDicomDatasetWithoutBulkDataItems(dicomDataset));

            DicomDataset CopyDicomDatasetWithoutBulkDataItems(DicomDataset dicomDatasetToCopy)
            {
                return(new DicomDataset(dicomDatasetToCopy
                                        .Select(dicomItem =>
                {
                    if (DicomBulkDataVr.Contains(dicomItem.ValueRepresentation))
                    {
                        // If the VR is bulk data type, return null so it can be filtered out later.
                        return null;
                    }
                    else if (dicomItem.ValueRepresentation == DicomVR.SQ)
                    {
                        // If the VR is sequence, then process each item within the sequence.
                        DicomSequence sequenceToCopy = (DicomSequence)dicomItem;

                        return new DicomSequence(
                            sequenceToCopy.Tag,
                            sequenceToCopy.Select(itemToCopy => itemToCopy.CopyWithoutBulkDataItems()).ToArray());
                    }
                    else
                    {
                        // The VR is not bulk data, return it.
                        return dicomItem;
                    }
                })
                                        .Where(dicomItem => dicomItem != null)));
            }
        }
Beispiel #4
0
        public void Load(DicomFile file, StructureSet structureSet, IProgress <double> progress)
        {
            structureSet.FileName = file.File.Name;

            structureSet.Name = file.Dataset.GetSingleValueOrDefault <string>(DicomTag.StructureSetLabel, "");

            Dictionary <int, string> roi_names = new Dictionary <int, string>();
            DicomSequence            structs   = file.Dataset.GetSequence(DicomTag.StructureSetROISequence);

            foreach (DicomDataset item in structs)
            {
                roi_names.Add(item.GetSingleValue <int>(DicomTag.ROINumber), item.GetSingleValue <string>(DicomTag.ROIName));
            }

            DicomSequence s = file.Dataset.GetSequence(DicomTag.ROIContourSequence);

            //Track the item number to report progress
            double total = s.Items.Count;
            double num   = 0;

            foreach (DicomDataset item in s.Items)
            {
                num++;
                if (progress != null)
                {
                    progress.Report(100 * num / total);
                }

                RegionOfInterest roi = new RegionOfInterest();

                int[] color = new int[] { 0, 0, 0 };
                if (item.TryGetValues <int>(DicomTag.ROIDisplayColor, out int[] tmp))
		public uint Calculate(DicomSequence sq) {
			uint length = 0;

			foreach (DicomDataset sqi in sq) {
				// sequence item
				length += 4; // tag
				length += 4; // length

				length += Calculate(sqi);

				if (!_options.ExplicitLengthSequenceItems) {
					// sequence item delimitation item
					length += 4; // tag
					length += 4; // length
				}
			}

			if (!_options.ExplicitLengthSequences && !sq.Tag.IsPrivate) {
				// sequence delimitation item
				length += 4; // tag
				length += 4; // length
			}

			return length;
		}
		public void OnBeginSequence(IByteSource source, DicomTag tag, uint length) {
			DicomSequence sq = new DicomSequence(tag);
			_sequences.Push(sq);

			DicomDataset ds = _datasets.Peek();
			ds.Add(sq);
		}
Beispiel #7
0
        protected virtual void WriteVR_SQ(DicomSequence element, JsonWriter writer)
        {
            for (int index = 0; index < element.Items.Count; index++)
            {
                StringBuilder sqBuilder = new StringBuilder( );
                StringWriter  sw        = new StringWriter(sqBuilder);

                using (JsonWriter sqWriter = new JsonTextWriter(sw))
                {
                    var item = element.Items[index];


                    sqWriter.Formatting = Formatting.Indented;//TODO: make it an option

                    sqWriter.WriteStartArray( );

                    sqWriter.WriteStartObject( );

                    if (null != item)
                    {
                        WriteChildren(item, sqWriter);
                    }

                    sqWriter.WriteEndObject( );
                    sqWriter.WriteEndArray( );
                }

                WriteSequenceValue(writer, sqBuilder.ToString( ));
            }
        }
        public uint Calculate(DicomSequence sq)
        {
            uint length = 0;

            foreach (DicomDataset sqi in sq)
            {
                // sequence item
                length += 4; // tag
                length += 4; // length

                length += Calculate(sqi);

                if (!_options.ExplicitLengthSequenceItems)
                {
                    // sequence item delimitation item
                    length += 4; // tag
                    length += 4; // length
                }
            }

            if (!_options.ExplicitLengthSequences && !sq.Tag.IsPrivate)
            {
                // sequence delimitation item
                length += 4; // tag
                length += 4; // length
            }

            return(length);
        }
        public void Exact_Offsets_Should_All_Match()
        {
            var offsets = GenerateUniqueRandonmOffsets(155, 500000);
            var root    = new Container()
            {
                Sequence = new DicomDataset()
            };

            root.CreateChildren(offsets, 5, 3, 3, 2);

            var allChildren = root.AllContainer.Skip(1).ToArray();
            var sequence    = new DicomSequence(DicomTag.DirectoryRecordSequence);

            root.Sequence.AddOrUpdate(sequence);

            var byteSource = new TestByteSource();
            var observer   = new DicomDirectoryReaderObserver(root.Sequence);

            observer.OnBeginSequence(byteSource, DicomTag.DirectoryRecordSequence, 0);
            foreach (var container in allChildren)
            {
                sequence.Items.Add(container.Sequence);
                byteSource.Position = container.Offset + 8;
                observer.OnBeginSequenceItem(byteSource, 0);
                observer.OnEndSequenceItem();
            }
            observer.OnEndSequence();

            var rootRecord = new DicomDirectoryRecord
            {
                LowerLevelDirectoryRecord = observer.BuildDirectoryRecords(),
            };

            root.AssertRecord(rootRecord);
        }
Beispiel #10
0
        /// <summary>
        /// get waveform data from dataset
        /// </summary>
        /// <param name="waveform"></param>
        private void GetWaveformData(DicomSequence waveform)
        {
            if (waveform.Items.Count == 0)
            {
                return;
            }

            // first dataset
            ushort channels = waveform.Items[0].GetSingleValue <ushort>(DicomTag.NumberOfWaveformChannels);
            ulong  samples  = waveform.Items[0].GetSingleValue <ulong>(DicomTag.NumberOfWaveformSamples);

            ushort[] temp  = waveform.Items[0].GetValues <ushort>(DicomTag.WaveformData);
            short[]  temp2 = new short[temp.Length];
            Buffer.BlockCopy(temp, 0, temp2, 0, temp.Length * sizeof(ushort));

            waveformData = new short[channels, samples];

            for (int i = 0; i < channels; i++)
            {
                for (ulong j = 0; j < samples; j++)
                {
                    waveformData[i, j] = temp2[(int)(j * channels) + i];
                }
            }

            hasData = true;
        }
        public async Task GivenStoredDicomFileWithNoContent_WhenRetrieved_TheFileIsRetrievedCorrectly()
        {
            var       studyInstanceUid = TestUidGenerator.Generate();
            DicomFile dicomFile1       = Samples.CreateRandomDicomFile(studyInstanceUid);
            var       dicomInstance    = dicomFile1.Dataset.ToInstanceIdentifier();
            DicomWebResponse <DicomDataset> response = await _client.StoreAsync(new[] { dicomFile1 }, studyInstanceUid);

            DicomSequence successSequence = response.Value.GetSequence(DicomTag.ReferencedSOPSequence);

            string studyRetrieveLocation    = response.Value.GetSingleValue <string>(DicomTag.RetrieveURL);
            string instanceRetrieveLocation = successSequence.Items[0].GetSingleValue <string>(DicomTag.RetrieveURL);

            DicomWebResponse <IReadOnlyList <DicomFile> > studyByUrlRetrieve = await _client.RetrieveInstancesAsync(new Uri(studyRetrieveLocation));

            ValidateRetrieveTransaction(studyByUrlRetrieve, HttpStatusCode.OK, DicomTransferSyntax.ExplicitVRLittleEndian, singleInstance: false, dicomFile1);

            DicomWebResponse <IReadOnlyList <DicomFile> > instanceByUrlRetrieve = await _client.RetrieveInstancesAsync(new Uri(instanceRetrieveLocation), true);

            ValidateRetrieveTransaction(instanceByUrlRetrieve, HttpStatusCode.OK, DicomTransferSyntax.ExplicitVRLittleEndian, singleInstance: true, dicomFile1);

            DicomWebResponse <IReadOnlyList <DicomFile> > studyRetrieve = await _client.RetrieveStudyAsync(dicomInstance.StudyInstanceUid);

            ValidateRetrieveTransaction(studyRetrieve, HttpStatusCode.OK, DicomTransferSyntax.ExplicitVRLittleEndian, singleInstance: false, dicomFile1);

            DicomWebResponse <IReadOnlyList <DicomFile> > seriesRetrieve = await _client.RetrieveSeriesAsync(dicomInstance.StudyInstanceUid, dicomInstance.SeriesInstanceUid);

            ValidateRetrieveTransaction(seriesRetrieve, HttpStatusCode.OK, DicomTransferSyntax.ExplicitVRLittleEndian, singleInstance: false, dicomFile1);

            DicomWebResponse <IReadOnlyList <DicomFile> > instanceRetrieve = await _client.RetrieveInstanceAsync(dicomInstance.StudyInstanceUid, dicomInstance.SeriesInstanceUid, dicomInstance.SopInstanceUid);

            ValidateRetrieveTransaction(instanceRetrieve, HttpStatusCode.OK, DicomTransferSyntax.ExplicitVRLittleEndian, singleInstance: true, dicomFile1);
        }
Beispiel #12
0
        public static string GetStringFromSequence(DicomSequence seq, int recursionDepth)
        {
            string result = "";
            string offset = "";

            for (int a = 0; a < recursionDepth; a++)
            {
                offset = offset + ">";
            }
            foreach (var i in seq.Items)
            {
                foreach (var d in i)
                {
                    if (d.ValueRepresentation != DicomVR.SQ)
                    {
                        string output;
                        if (i.TryGetString(d.Tag, out output))
                        {
                            result = result + offset + d.ToString() + " - " + output + Environment.NewLine;
                        }
                        else
                        {
                            result = result + offset + d.ToString() + " - " + Environment.NewLine;
                        }
                    }
                    else
                    {
                        result = result + offset + "------ begin subsequence -------" + Environment.NewLine + offset + GetStringFromSequence(d as DicomSequence, recursionDepth + 1) + offset + "------ end subsequence -------" + Environment.NewLine;
                    }
                }
            }
            //seq.Items.Each(x => Console.WriteLine(x.ToString()));
            return(result);
        }
		public bool OnBeginSequence(DicomSequence sequence)
		{
			var tag = String.Format("{0}  {1}", sequence.Tag.ToString().ToUpper(), sequence.Tag.DictionaryEntry.Name);

			TextItems.Add(new DicomTextItem(_level++, tag, "SQ"));
			return true;
		}
 public void OnBeginSequence(IByteSource source, DicomTag tag, uint length)
 {
     _currentSequenceTag.Push(tag);
     if (tag == DicomTag.DirectoryRecordSequence) {
         _directoryRecordSequence = _dataset.Get<DicomSequence>(tag);
     }
 }
Beispiel #15
0
        internal static void RegisterAllimage(String Path)
        {
            var response       = DicomFile.Open(Path);
            var SOPInstanceUID = response.Dataset.GetSingleValue <String>(DicomTag.SOPInstanceUID);
            int RowPositionInTotalImagePixelMatrix;
            int ColumnPositionInTotalImagePixelMatrix;
            int TotalPixelMatrixRows;
            int TotalPixelMatrixColumns;
            int Rows;
            int Columns;

            TotalPixelMatrixRows    = response.Dataset.GetSingleValue <int>(DicomTag.TotalPixelMatrixRows);
            TotalPixelMatrixColumns = response.Dataset.GetSingleValue <int>(DicomTag.TotalPixelMatrixColumns);
            Rows    = response.Dataset.GetSingleValue <int>(DicomTag.Rows);
            Columns = response.Dataset.GetSingleValue <int>(DicomTag.Columns);
            var           Level = 0;
            DicomSequence PerFrameFunctionalGroupsSequence = response.Dataset.GetSequence(DicomTag.PerFrameFunctionalGroupsSequence);

            if (PerFrameFunctionalGroupsSequence != null)
            {
                var PerFrameFunctionalGroupsItems = PerFrameFunctionalGroupsSequence.GetEnumerator();
                var FrameIndex = 0;
                while (PerFrameFunctionalGroupsItems.MoveNext())
                {
                    var PlanePositionSlideSequence = PerFrameFunctionalGroupsItems.Current.GetSequence(DicomTag.PlanePositionSlideSequence);

                    ColumnPositionInTotalImagePixelMatrix = PlanePositionSlideSequence.Items[0].GetSingleValue <int>(DicomTag.ColumnPositionInTotalImagePixelMatrix);
                    RowPositionInTotalImagePixelMatrix    = PlanePositionSlideSequence.Items[0].GetSingleValue <int>(DicomTag.RowPositionInTotalImagePixelMatrix);
                    DataManager.AddFrame(SOPInstanceUID, RowPositionInTotalImagePixelMatrix, ColumnPositionInTotalImagePixelMatrix, FrameIndex++);
                }
            }
            DataManager.AddImage(SOPInstanceUID, Rows, Columns, TotalPixelMatrixColumns, TotalPixelMatrixRows, Level);
        }
Beispiel #16
0
        private void ReadSequence
        (
            DicomDataset ds,
            XElement element,
            DicomTag tag,
            int level
        )
        {
            DicomSequence seq = new DicomSequence(tag, new DicomDataset[0]);


            foreach (var item in  element.Elements(Constants.ATTRIBUTE_ITEM_NAME))
            {
                DicomDataset itemDs = new DicomDataset( )
                {
                    AutoValidate = false
                };

                level++;

                ReadChildren(itemDs, item, level);

                level--;

                seq.Items.Add(itemDs);
            }

            ds.AddOrUpdate(seq);
        }
Beispiel #17
0
        public void CreateLutSequence()
        {
            var lutSequence = new DicomSequence(DicomTag.PresentationLUTSequence);

            lutSequence.Items.Add(new DicomDataset());
            this.Add(lutSequence);
        }
        /// <inheritdoc />
        public void AddFailure(DicomDataset dicomDataset, ushort failureReasonCode)
        {
            CreateDatasetIfNeeded();

            if (!_dataset.TryGetSequence(DicomTag.FailedSOPSequence, out DicomSequence failedSopSequence))
            {
                failedSopSequence = new DicomSequence(DicomTag.FailedSOPSequence);

                _dataset.Add(failedSopSequence);
            }

            var failedSop = new DicomDataset()
            {
                { DicomTag.FailureReason, failureReasonCode },
            };

            // We want to turn off auto validation for FailedSOPSequence item
            // because the failure might be caused by invalid UID value.
#pragma warning disable CS0618 // Type or member is obsolete
            failedSop.AutoValidate = false;
#pragma warning restore CS0618 // Type or member is obsolete

            failedSop.AddValueIfNotNull(
                DicomTag.ReferencedSOPClassUID,
                dicomDataset?.GetSingleValueOrDefault <string>(DicomTag.SOPClassUID));

            failedSop.AddValueIfNotNull(
                DicomTag.ReferencedSOPInstanceUID,
                dicomDataset?.GetSingleValueOrDefault <string>(DicomTag.SOPInstanceUID));

            failedSopSequence.Items.Add(failedSop);
        }
Beispiel #19
0
        protected virtual void ReadVr_SQ(JsonTextReader reader, DicomTag tag, DicomDataset dataset, int level)
        {
            DicomSequence seq = new DicomSequence(tag, new DicomDataset[0]);


            if (reader.Value as string == JsonConstants.ValueField)
            {
                while (reader.Read( ) && reader.TokenType == JsonToken.StartArray)
                {
                    while (reader.Read( ) && reader.TokenType != JsonToken.EndArray)
                    {
                        DicomDataset itemDs = new DicomDataset( )
                        {
                            AutoValidate = false
                        };

                        ReadChildren(reader, itemDs, ++level);

                        --level;

                        seq.Items.Add(itemDs);
                    }

                    break;
                }
            }

            dataset.AddOrUpdate(seq);
        }
Beispiel #20
0
 public void OnBeginSequence(IByteSource source, DicomTag tag, uint length)
 {
     _currentSequenceTag.Push(tag);
     if (tag == DicomTag.DirectoryRecordSequence)
     {
         _directoryRecordSequence = _dataset.Get <DicomSequence>(tag);
     }
 }
Beispiel #21
0
 public DicomReferencedSOP(DicomSequence sequence)
 {
     if (sequence.Items.Count == 0)
     {
         throw new DicomDataException("No referenced SOP pair item found in sequence.");
     }
     Add(sequence.Items[0]);
 }
 public DicomCodeItem(DicomSequence sequence)
 {
     if (sequence.Items.Count == 0)
     {
         throw new DicomDataException("No code item found in sequence.");
     }
     Add(sequence.Items[0]);
 }
Beispiel #23
0
 public DicomMeasuredValue(DicomSequence sequence)
 {
     if (sequence.Items.Count == 0)
     {
         throw new DicomDataException("No measurement item found in sequence.");
     }
     Add(sequence.Items[0]);
 }
Beispiel #24
0
            public bool OnBeginSequence(DicomSequence sequence)
            {
                var tag = String.Format("{0}{1}  {2}", Indent, sequence.Tag.ToString().ToUpper(), sequence.Tag.DictionaryEntry.Name);

                Form.appendToInfo(String.Join(" ", tag, "SQ", String.Empty, String.Empty) + "\r\n");

                Level++;
                return(true);
            }
Beispiel #25
0
            public bool OnBeginSequence(DicomSequence sequence)
            {
                var tag = String.Format("{0}{1}  {2}", Indent, sequence.Tag.ToString().ToUpper(), sequence.Tag.DictionaryEntry.Name);

                Form.AddItem(tag, "SQ", String.Empty, String.Empty);

                Level++;
                return(true);
            }
Beispiel #26
0
        public uint Calculate(DicomItem item)
        {
            uint length = 0;

            length += 4;             // tag

            if (_syntax.IsExplicitVR)
            {
                length += 2;                 // vr
                if (item.ValueRepresentation.Is16bitLength)
                {
                    length += 2;                     // length
                }
                else
                {
                    length += 2;                     // reserved
                    length += 4;                     // length
                }
            }
            else
            {
                length += 4;                 // length
            }

            if (item is DicomElement)
            {
                length += (uint)(item as DicomElement).Buffer.Size;
            }
            else if (item is DicomFragmentSequence)
            {
                DicomFragmentSequence sq = item as DicomFragmentSequence;
                // fragment item (offset table)
                length += 4;                 // tag
                length += 4;                 // length
                length += (uint)(sq.OffsetTable.Count / 4);

                foreach (IByteBuffer fragment in sq)
                {
                    // fragment item
                    length += 4;                     // tag
                    length += 4;                     // length
                    length += fragment.Size;
                }

                // sequence delimitation item
                length += 4;                 // tag
                length += 4;                 // length
            }
            else if (item is DicomSequence)
            {
                DicomSequence sq = item as DicomSequence;
                length += Calculate(sq);
            }

            return(length);
        }
Beispiel #27
0
 public bool OnBeginSequence(DicomSequence sequence)
 {
     _log.AppendFormat(
         "{0}{1} SQ {2}",
         (_depth > 0) ? _pad + "> " : "",
         sequence.Tag,
         sequence.Tag.DictionaryEntry.Name).AppendLine();
     IncreaseDepth();
     return true;
 }
Beispiel #28
0
        public void OnBeginSequence(IByteSource source, DicomTag tag, uint length)
        {
            var sq = new DicomSequence(tag);

            _sequences.Push(sq);

            DicomDataset ds = _datasets.Peek();

            ds.AddOrUpdate(sq);
        }
Beispiel #29
0
 /// <summary>
 /// Handler for traversing beginning of sequence.
 /// </summary>
 /// <param name="sequence">Sequence to traverse.</param>
 /// <returns>true if traversing completed without issues, false otherwise.</returns>
 public bool OnBeginSequence(DicomSequence sequence)
 {
     _log.AppendFormat(
         "{0}{1} SQ {2}",
         (_depth > 0) ? _pad + "> " : "",
         sequence.Tag,
         sequence.Tag.DictionaryEntry.Name).AppendLine();
     IncreaseDepth();
     return(true);
 }
        public void OnBeginSequenceItem(IByteSource source, uint length)
        {
            DicomSequence sq = _sequences.Peek();

            DicomDataset item = new DicomDataset();

            sq.Items.Add(item);

            _datasets.Push(item);
        }
Beispiel #31
0
        public void SourceRead_InvalidFloatInSequence_ToTable(InvalidDataHandling dataHandlingStrategy)
        {
            var source = new DicomDatasetCollectionSource();

            source.InvalidDataHandlingStrategy = dataHandlingStrategy;

            //when we have a dicom file with an invalid Float number
            var ds = new DicomDataset();

            ds.Add(DicomTag.PatientAge, "123Y");

            var sequence = new DicomSequence(DicomTag.AcquisitionContextSequence,
                                             new DicomDataset()
            {
                { DicomTag.WedgeAngleFloat, "3.40282347e+038" }
            });

            ds.Add(sequence);

            var worklist = new ExplicitListDicomDatasetWorklist(new[] { ds }, "fish.dcm");

            source.PreInitialize(worklist, new ThrowImmediatelyDataLoadEventListener());
            source.FilenameField = "RelFileName";

            DataTable dt = null;

            switch (dataHandlingStrategy)
            {
            case InvalidDataHandling.MarkCorrupt:
                dt = source.GetChunk(new ThrowImmediatelyDataLoadEventListener(), new GracefulCancellationToken());

                //row was not processed (which leaves data table with 0 rows and hence component returns null)
                Assert.IsNull(dt);

                //corrupt message should appear in the worklist
                Assert.AreEqual(1, worklist.CorruptMessages.Count);
                return;

            case InvalidDataHandling.ConvertToNullAndWarn:
                dt = source.GetChunk(new ThrowImmediatelyDataLoadEventListener(), new GracefulCancellationToken());

                Assert.AreEqual("123Y", dt.Rows[0]["PatientAge"]);
                Assert.AreEqual("fish.dcm", dt.Rows[0]["RelFileName"]);
                Assert.AreEqual(DBNull.Value, dt.Rows[0]["AcquisitionContextSequence"]);
                Assert.AreEqual(0, worklist.CorruptMessages.Count);
                break;

            case InvalidDataHandling.ThrowException:
                Assert.Throws <OverflowException>(() => source.GetChunk(new ThrowImmediatelyDataLoadEventListener(), new GracefulCancellationToken()));
                return;

            default:
                throw new ArgumentOutOfRangeException("dataHandlingStrategy");
            }
        }
Beispiel #32
0
 /// <summary>
 /// Handler for traversing beginning of sequence.
 /// </summary>
 /// <param name="sequence">Sequence to traverse.</param>
 /// <returns>true if traversing completed without issues, false otherwise.</returns>
 public bool OnBeginSequence(DicomSequence sequence)
 {
     _log.Log(
         _level,
         "{padding}{tag} SQ {tagDictionaryEntryName}",
         (_depth > 0) ? _pad + "> " : "",
         sequence.Tag,
         sequence.Tag.DictionaryEntry.Name);
     IncreaseDepth();
     return(true);
 }
Beispiel #33
0
        /// <summary>
        /// Handler for traversing end of sequence item.
        /// </summary>
        /// <returns>true if traversing completed without issues, false otherwise.</returns>
        /// <remarks>On false return value, the method will invoke the callback method passed in <see cref="IDicomDatasetWalker.OnBeginWalk"/> before returning.</remarks>
        public bool OnEndSequenceItem()
        {
            DicomSequence sequence = _sequences.Peek();

            if (!_options.ExplicitLengthSequenceItems)
            {
                WriteTagHeader(DicomTag.ItemDelimitationItem, DicomVR.NONE, 0);
            }

            return(true);
        }
Beispiel #34
0
        public void SourceRead_ToTable_IgnoringSuperflousColumn_LoadMetadata()
        {
            var repo = new MemoryCatalogueRepository();

            var lmd = new LoadMetadata(repo, "MyLoad");

            var cata1    = new Catalogue(repo, "PatientCatalogue");
            var ci1      = new CatalogueItem(repo, cata1, "PatientAge");
            var ti1      = new TableInfo(repo, "PatientTableInfo");
            var colInfo1 = new ColumnInfo(repo, "PatientAge", "varchar(100)", ti1);

            ci1.ColumnInfo_ID = colInfo1.ID;
            ci1.SaveToDatabase();
            cata1.LoadMetadata_ID = lmd.ID;
            cata1.SaveToDatabase();

            var cata2    = new Catalogue(repo, "FileCatalogue");
            var ci2      = new CatalogueItem(repo, cata2, "RelFileName");
            var ti2      = new TableInfo(repo, "FileTableInfo");
            var colInfo2 = new ColumnInfo(repo, "RelFileName", "varchar(100)", ti2);

            ci2.ColumnInfo_ID = colInfo2.ID;
            ci2.SaveToDatabase();
            cata2.LoadMetadata_ID = lmd.ID;
            cata2.SaveToDatabase();

            var source = new DicomDatasetCollectionSource();

            source.InvalidDataHandlingStrategy = InvalidDataHandling.ThrowException;

            var ds = new DicomDataset();

            ds.Add(DicomTag.PatientAge, "123Y");

            var sequence = new DicomSequence(DicomTag.AcquisitionContextSequence,
                                             new DicomDataset()
            {
                { DicomTag.WedgeAngleFloat, "3.40282347e+038" }
            });

            ds.Add(sequence);

            var worklist = new ExplicitListDicomDatasetWorklist(new[] { ds }, "fish.dcm");

            source.PreInitialize(worklist, new ThrowImmediatelyDataLoadEventListener());
            source.FilenameField = "RelFileName";
            source.UseAllTableInfoInLoadAsFieldMap = lmd;

            var dt = source.GetChunk(new ThrowImmediatelyDataLoadEventListener(), new GracefulCancellationToken());

            Assert.AreEqual("123Y", dt.Rows[0]["PatientAge"]);
            Assert.AreEqual("fish.dcm", dt.Rows[0]["RelFileName"]);
            Assert.AreEqual(2, dt.Columns.Count);
        }
Beispiel #35
0
        /// <summary>
        /// Handler for traversing end of sequence.
        /// </summary>
        /// <returns>true if traversing completed without issues, false otherwise.</returns>
        /// <remarks>On false return value, the method will invoke the callback method passed in <see cref="IDicomDatasetWalker.OnBeginWalk"/> before returning.</remarks>
        public bool OnEndSequence()
        {
            DicomSequence sequence = _sequences.Pop();

            if (!_options.ExplicitLengthSequences && !sequence.Tag.IsPrivate)
            {
                WriteTagHeader(DicomTag.SequenceDelimitationItem, DicomVR.NONE, 0);
            }

            return(true);
        }
Beispiel #36
0
 public bool OnBeginSequence(DicomSequence sequence)
 {
     _log.Log(
         _level,
         "{padding}{tag} SQ {tagDictionaryEntryName}",
         (_depth > 0) ? _pad + "> " : "",
         sequence.Tag,
         sequence.Tag.DictionaryEntry.Name);
     IncreaseDepth();
     return true;
 }
Beispiel #37
0
		public bool OnBeginSequence(DicomSequence sequence) {
			uint length = UndefinedLength;

			if (_options.ExplicitLengthSequences || sequence.Tag.IsPrivate) {
				DicomWriteLengthCalculator calc = new DicomWriteLengthCalculator(_syntax, _options);
				length = calc.Calculate(sequence);
			}

			_sequences.Push(sequence);

			WriteTagHeader(sequence.Tag, DicomVR.SQ, length);
			return true;
		}
Beispiel #38
0
		public DicomDirectory() : base() {
			FileMetaInfo.Add<byte>(DicomTag.FileMetaInformationVersion, new byte[] { 0x00, 0x01 });
			FileMetaInfo.MediaStorageSOPClassUID = DicomUID.MediaStorageDirectoryStorage;
			FileMetaInfo.MediaStorageSOPInstanceUID = DicomUID.Generate();
			FileMetaInfo.SourceApplicationEntityTitle = string.Empty;
			FileMetaInfo.TransferSyntax = DicomTransferSyntax.ImplicitVRLittleEndian;
			FileMetaInfo.ImplementationClassUID = DicomImplementation.ClassUID;
			FileMetaInfo.ImplementationVersionName = DicomImplementation.Version;

			_directoryRecordSequence = new DicomSequence(DicomTag.DirectoryRecordSequence);

			Dataset.Add<string>(DicomTag.FileSetID, string.Empty)
				   .Add<ushort>(DicomTag.FileSetConsistencyFlag, 0)
				   .Add<uint>(DicomTag.OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity, 0)
				   .Add<uint>(DicomTag.OffsetOfTheLastDirectoryRecordOfTheRootDirectoryEntity, 0);
		}
Beispiel #39
0
            public bool OnBeginSequence(DicomSequence sequence)
            {
                var tag = String.Format("{0}{1}  {2}", Indent, sequence.Tag.ToString().ToUpper(), sequence.Tag.DictionaryEntry.Name);

                Form.appendToInfo(String.Join(" ", tag, "SQ", String.Empty, String.Empty) + "\r\n");

                Level++;
                return true;
            }
Beispiel #40
0
        private void CompareSequences(DicomSequence s1, DicomSequence s2)
        {
            if (s1 == null)
            {
                AddItem(s1, lvFile1, Gray);
                AddItem(s2, lvFile2, Green);
            }
            else if (s2 == null)
            {
                AddItem(s1, lvFile1, Green);
                AddItem(s2, lvFile2, Gray);
            }
            else
            {
                AddItem(s1, lvFile1, None);
                AddItem(s2, lvFile2, None);
            }

            Level++;

            int count = 0;
            if (s1 != null) count = s1.Items.Count;
            if (s2 != null && s2.Items.Count > count) count = s2.Items.Count;

            for (int i = 0; i < count; i++)
            {
                DicomDataset d1 = null;
                if (s1 != null && i < s1.Items.Count) d1 = s1.Items[i];

                DicomDataset d2 = null;
                if (s2 != null && i < s2.Items.Count) d2 = s2.Items[i];

                if (d1 == null)
                {
                    AddItem(String.Empty, UInt32.MaxValue, String.Empty, lvFile1, Gray);
                    AddItem(GetTagName(DicomTag.Item), UInt32.MaxValue, String.Empty, lvFile2, Green);
                }
                else if (d2 == null)
                {
                    AddItem(GetTagName(DicomTag.Item), UInt32.MaxValue, String.Empty, lvFile1, Green);
                    AddItem(String.Empty, UInt32.MaxValue, String.Empty, lvFile2, Gray);
                }
                else
                {
                    AddItem(GetTagName(DicomTag.Item), UInt32.MaxValue, String.Empty, lvFile1, None);
                    AddItem(GetTagName(DicomTag.Item), UInt32.MaxValue, String.Empty, lvFile2, None);
                }

                Level++;
                CompareDatasets(d1, d2);
                Level--;
            }

            Level--;
        }
Beispiel #41
0
        private DicomNGetResponse GetPrinterConfiguration(DicomNGetRequest request)
        {
            var dataset = new DicomDataset();
            var config = new DicomDataset();

            var sequence = new DicomSequence(DicomTag.PrinterConfigurationSequence, config);

            dataset.Add(sequence);

            var response = new DicomNGetResponse(request, DicomStatus.Success);
            response.Command.Add(DicomTag.AffectedSOPInstanceUID, request.SOPInstanceUID);
            response.Dataset = dataset;
            return response;

        }
		public DicomMeasuredValue(DicomSequence sequence) {
			if (sequence.Items.Count == 0)
				throw new DicomDataException("No measurement item found in sequence.");
			Add(sequence.Items[0]);
		}
Beispiel #43
0
 public DicomReferencedSOP(DicomSequence sequence)
 {
     if (sequence.Items.Count == 0) throw new DicomDataException("No referenced SOP pair item found in sequence.");
     Add(sequence.Items[0]);
 }
Beispiel #44
0
 public DicomCodeItem(DicomSequence sequence)
 {
     if (sequence.Items.Count == 0) throw new DicomDataException("No code item found in sequence.");
     Add(sequence.Items[0]);
 }
 public bool OnBeginSequence(DicomSequence sequence)
 {
     return true;
 }
Beispiel #46
0
			public bool OnBeginSequence(DicomSequence sequence) {
				var tag = String.Format("{0}{1}  {2}", Indent, sequence.Tag.ToString().ToUpper(), sequence.Tag.DictionaryEntry.Name);

				Form.AddItem(tag, "SQ", String.Empty, String.Empty);

				Level++;
				return true;
			}
Beispiel #47
0
 public void CreateLutSequence()
 {
     var lutSequence = new DicomSequence(DicomTag.PresentationLUTSequence);
     lutSequence.Items.Add(new DicomDataset());
     this.Add(lutSequence);
 }