/// <summary>
        /// Gets a single value if the value exists; otherwise the default value for the type <typeparamref name="T"/>.
        /// </summary>
        /// <typeparam name="T">The value type.</typeparam>
        /// <param name="dicomDataset">The dataset to get the VR value from.</param>
        /// <param name="dicomTag">The DICOM tag.</param>
        /// <param name="expectedVR">Expected VR of the element.</param>
        /// <remarks>If expectedVR is provided, and not match, will return default<typeparamref name="T"/></remarks>
        /// <returns>The value if the value exists; otherwise, the default value for the type <typeparamref name="T"/>.</returns>
        public static T GetSingleValueOrDefault <T>(this DicomDataset dicomDataset, DicomTag dicomTag, DicomVR expectedVR = null)
        {
            EnsureArg.IsNotNull(dicomDataset, nameof(dicomDataset));

            // If VR doesn't match, return default(T)
            if (expectedVR != null && dicomDataset.GetDicomItem <DicomElement>(dicomTag)?.ValueRepresentation != expectedVR)
            {
                return(default);
Beispiel #2
0
 public void Transform(DicomDataset dataset, DicomDataset modifiedAttributesSequenceItem = null)
 {
     if (dataset.Contains(_src))
     {
         dataset.CopyTo(modifiedAttributesSequenceItem, _dst);
         dataset.AddOrUpdate(_dst, dataset.GetDicomItem <DicomElement>(_src).Buffer);
     }
 }
Beispiel #3
0
 public void OnBeginSequence(IByteSource source, DicomTag tag, uint length)
 {
     _currentSequenceTag.Push(tag);
     if (tag == DicomTag.DirectoryRecordSequence)
     {
         _directoryRecordSequence = _dataset.GetDicomItem <DicomSequence>(tag);
     }
 }
Beispiel #4
0
        private static void GetPixelSpacing(DicomDataset dataSet, ImageData image)
        {
            var dicomPixelSpacing = dataSet.GetDicomItem <DicomDecimalString>(DicomTag.PixelSpacing);

            if (dicomPixelSpacing != null)
            {
                image.PixelSpacing.X = dicomPixelSpacing.Get <double>(0);
                image.PixelSpacing.Y = dicomPixelSpacing.Get <double>(1);
            }
        }
Beispiel #5
0
        private static void GetPositionPatient(DicomDataset dataSet, ImageData image)
        {
            var dicomPositionPatient = dataSet.GetDicomItem <DicomDecimalString>(DicomTag.ImagePositionPatient);

            if (dicomPositionPatient != null)
            {
                image.PositionPatient.X = dicomPositionPatient.Get <double>(0);
                image.PositionPatient.Y = dicomPositionPatient.Get <double>(1);
                image.PositionPatient.Z = dicomPositionPatient.Get <double>(2);
            }
        }
        public void TestSetDicomTagWithNullElement()
        {
            var dataset = new DicomDataset();

            // Test with a string element and a value element
            var asTag = DicomTag.SelectorASValue;
            var flTag = DicomTag.SelectorFLValue;

            DicomTypeTranslaterWriter.SetDicomTag(dataset, asTag, null);
            DicomTypeTranslaterWriter.SetDicomTag(dataset, flTag, null);

            Assert.True(dataset.Count() == 2);

            var asElement = dataset.GetDicomItem <DicomElement>(DicomTag.SelectorASValue);

            Assert.True(asElement.Buffer.Size == 0);

            var flElement = dataset.GetDicomItem <DicomElement>(DicomTag.SelectorFLValue);

            Assert.True(flElement.Buffer.Size == 0);
        }
        private void ValidateTags(DicomDataset dicomDataset, IEnumerable <QueryTag> queryTags)
        {
            foreach (QueryTag queryTag in queryTags)
            {
                DicomElement dicomElement = dicomDataset.GetDicomItem <DicomElement>(queryTag.Tag);

                if (dicomElement != null && dicomElement.ValueRepresentation == queryTag.VR)
                {
                    _minimumValidator.Validate(dicomElement);
                }
            }
        }
        public void GivenADataSetWithDicomFragmentSequence_WhenRedact_ValueWillBeRedact()
        {
            var tag  = DicomTag.PixelData;
            var item = new DicomOtherByteFragment(tag);

            item.Fragments.Add(new MemoryByteBuffer(Convert.FromBase64String("fragment")));
            item.Fragments.Add(new MemoryByteBuffer(Convert.FromBase64String("fragment")));

            var dataset = new DicomDataset(item);

            Processor.Process(dataset, item);
            Assert.Equal(new byte[] { }, dataset.GetDicomItem <DicomElement>(tag).Get <byte[]>());
        }
        public void GivenADataSetWithASItem_WhenRedactWithPartialRedact_ValueWillBePartialRedact()
        {
            var tag1 = DicomTag.PatientAge;
            var tag2 = DicomTag.SelectorASValue;

            var dataset = new DicomDataset
            {
                { tag1, "090Y" },
                { tag2, "010D", "010W", "100M", "010Y", "090Y" },
            };

            var itemList = dataset.ToArray();

            var newProcessor = new RedactProcessor(JObject.Parse("{\"EnablePartialAgesForRedact\" : \"true\"}"));

            foreach (var item in itemList)
            {
                newProcessor.Process(dataset, item);
            }

            Assert.Equal(string.Empty, dataset.GetDicomItem <DicomElement>(tag1).Get <string>());
            Assert.Equal(@"010D\010W\100M\010Y", dataset.GetDicomItem <DicomElement>(tag2).Get <string>());
        }
        public void GivenADataSetWithDAItem_WhenRedactWithPartialRedact_ValueWillBePartialRedact()
        {
            var tag1 = DicomTag.Instance​Creation​Date;
            var tag2 = DicomTag.Calibration​Date;

            var dataset = new DicomDataset
            {
                { tag1, "20210320" },
                { tag2, "20210320", "19110101", "20200101" },
            };

            var itemList = dataset.ToArray();

            var newProcessor = new RedactProcessor(JObject.Parse("{\"EnablePartialDatesForRedact\" : \"true\"}"));

            foreach (var item in itemList)
            {
                newProcessor.Process(dataset, item);
            }

            Assert.Equal("20210101", dataset.GetDicomItem <DicomElement>(tag1).Get <string>());
            Assert.Equal(@"20210101\20200101", dataset.GetDicomItem <DicomElement>(tag2).Get <string>());
        }
 static private DicomItem GetAttributeValue(DicomDataset dataset, DicomTag attributeTag, DicomVR vr)
 {
     if (dataset.Contains(attributeTag) && dataset.GetDicomItem <DicomItem>(attributeTag).ValueRepresentation == vr)
     {
         return(dataset.GetDicomItem <DicomItem>(attributeTag));
     }
     foreach (var item in dataset)
     {
         if (item.ValueRepresentation != DicomVR.SQ)
         {
             continue;
         }
         foreach (var sequenceDataset in dataset.GetSequence(item.Tag))
         {
             var value = GetAttributeValue(sequenceDataset, attributeTag, vr);
             if (value != null)
             {
                 return(value);
             }
         }
     }
     return(null);
 }
        public void TestWriteMultiplicity()
        {
            DicomTag stringMultiTag = DicomTag.SpecimenShortDescription;

            string[] values = { "this", "is", "a", "multi", "element", "" };

            var ds = new DicomDataset();

            DicomTypeTranslaterWriter.SetDicomTag(ds, stringMultiTag, values);

            Assert.AreEqual(1, ds.Count());
            Assert.AreEqual(6, ds.GetDicomItem <DicomElement>(stringMultiTag).Count);
            Assert.AreEqual("this\\is\\a\\multi\\element\\", ds.GetString(stringMultiTag));
        }
Beispiel #13
0
 /// <summary>
 /// Initialize new instance of OtherWordPixelData
 /// </summary>
 /// <param name="dataset">The source dataset to extract from or create new pixel data for</param>
 /// <param name="newPixelData">True to create new pixel data, false to read pixel data</param>
 public OtherWordPixelData(DicomDataset dataset, bool newPixelData)
     : base(dataset)
 {
     if (newPixelData)
     {
         NumberOfFrames = 0;
         _element       = new DicomOtherWord(DicomTag.PixelData, new CompositeByteBuffer());
         Dataset.AddOrUpdate(_element);
     }
     else
     {
         _element = dataset.GetDicomItem <DicomOtherWord>(DicomTag.PixelData);
     }
 }
        public static void GivenDicomJsonDatasetWithFloatingVRContainsNAN_WhenDeserialized_IsSuccessful()
        {
            const string json = @"
            {
                ""00720076"": {
                    ""vr"": ""FL"",
                     ""Value"": [""NaN""]
                 }
            } ";

            DicomDataset tagValue = JsonSerializer.Deserialize <DicomDataset>(json, SerializerOptions);

            Assert.NotNull(tagValue.GetDicomItem <DicomFloatingPointSingle>(DicomTag.SelectorFLValue));
        }
Beispiel #15
0
        private void ValidateIndexedItems(DicomDataset dicomDataset)
        {
            HashSet <DicomTag> indexableTags = QueryLimit.AllInstancesTags;

            foreach (DicomTag indexableTag in indexableTags)
            {
                DicomElement dicomElement = dicomDataset.GetDicomItem <DicomElement>(indexableTag);

                if (dicomElement != null)
                {
                    string value = dicomDataset.GetSingleValueOrDefault <string>(indexableTag, default);
                    _minimumValidator.Validate(indexableTag, value);
                }
            }
        }
        /// <summary>
        /// Create a single BsonValue from a DicomItem
        /// </summary>
        /// <param name="dataset"></param>
        /// <param name="item"></param>
        /// <param name="writeVr"></param>
        /// <returns></returns>
        private static BsonValue CreateBsonValue(DicomDataset dataset, DicomItem item, bool writeVr)
        {
            if (item is DicomSequence)
            {
                return(CreateBsonValueFromSequence(dataset, item.Tag, writeVr));
            }

            var element = dataset.GetDicomItem <DicomElement>(item.Tag);

            BsonValue retVal;

            if (element is null || element.Count == 0)
            {
                retVal = BsonNull.Value;
            }
Beispiel #17
0
        public override List <DicomItem> LocateDicomTag(DicomDataset dataset, ProcessContext context)
        {
            EnsureArg.IsNotNull(dataset, nameof(dataset));
            EnsureArg.IsNotNull(context, nameof(context));

            var item   = dataset.GetDicomItem <DicomItem>(Tag);
            var result = new List <DicomItem>();

            if (item != null && !context.VisitedNodes.Contains(item.ToString()))
            {
                result.Add(item);
            }

            return(result);
        }
Beispiel #18
0
        private bool CompareDicomFileDataSet(DicomDataset dcm1, DicomDataset dcm2)
        {
            foreach (var item in dcm1)
            {
                if (item.ValueRepresentation != DicomVR.UI && item is DicomElement)
                {
                    if (!string.Equals(
                            dcm1.GetDicomItem <DicomElement>(item.Tag).Get <string>(),
                            dcm2.GetDicomItem <DicomElement>(item.Tag).Get <string>()))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Beispiel #19
0
        public void AddOrUpdate_NonDefaultEncodedStringElement_StringIsPreserved()
        {
            var          encoding = Encoding.GetEncoding("SHIFT_JIS");
            var          tag      = DicomTag.AdditionalPatientHistory;
            const string expected = "YamadaTarou山田太郎ヤマダタロウ";

            var dataset = new DicomDataset();

            dataset.AddOrUpdate(DicomTag.SpecificCharacterSet, DicomEncoding.GetCharset(encoding));
            dataset.AddOrUpdate(tag, expected);

            // simulate some kind of serialization, so that the buffer data is created correctly
            dataset.OnBeforeSerializing();

            var actual = encoding.GetString(dataset.GetDicomItem <DicomElement>(tag).Buffer.Data);

            Assert.Equal(expected, actual);
        }
Beispiel #20
0
        public void Add_PrivateTag_ShouldBeAddedWithCorrectVR()
        {
            var privCreatorDictEntry = new DicomDictionaryEntry(new DicomTag(0x0011, 0x0010), "Private Creator", "PrivateCreator", DicomVM.VM_1, false, DicomVR.LO);

            DicomDictionary.Default.Add(privCreatorDictEntry);

            DicomPrivateCreator privateCreator1 = DicomDictionary.Default.GetPrivateCreator("TESTCREATOR1");
            DicomDictionary     privDict1       = DicomDictionary.Default[privateCreator1];

            var dictEntry = new DicomDictionaryEntry(DicomMaskedTag.Parse("0011", "xx10"), "TestPrivTagName", "TestPrivTagKeyword", DicomVM.VM_1, false, DicomVR.CS);

            privDict1.Add(dictEntry);

            var ds = new DicomDataset
            {
                { dictEntry.Tag, "VAL1" }
            };

            Assert.Equal(DicomVR.CS, ds.GetDicomItem <DicomItem>(dictEntry.Tag).ValueRepresentation);
        }
Beispiel #21
0
        public void Get_ByteArrayFromStringElement_ReturnsValidArray()
        {
            // now the actual unit-test
            var          encoding = Encoding.GetEncoding("SHIFT_JIS");
            var          tag      = DicomTag.AdditionalPatientHistory;
            const string expected = "YamadaTarou山田太郎ヤマダタロウ";

            var dataset = new DicomDataset
            {
                new DicomLongText(tag, expected)
            };

            dataset.AddOrUpdate(DicomTag.SpecificCharacterSet, DicomEncoding.GetCharset(encoding));

            // simulate some rendering into stream (file, network,..)
            dataset.OnBeforeSerializing();

            var actual = encoding.GetString(dataset.GetDicomItem <DicomElement>(tag).Buffer.Data);

            Assert.Equal(expected, actual);
        }
        public void GivenADataSetWithDTItem_WhenRedactWithPartialRedact_ValueWillBePartialRedact()
        {
            var tag1 = DicomTag.Instance​Coercion​Date​Time;
            var tag2 = DicomTag.Referenced​Date​Time;

            var dataset = new DicomDataset
            {
                { tag1, "20210320202020.20+0800" },
                { tag2, "20210320202020.20+0800", "20210320202020.00654", "20210320202020+1400", "19000320202020+1400" },
            };

            var itemList = dataset.ToArray();

            var newProcessor = new RedactProcessor(JObject.Parse("{\"EnablePartialDatesForRedact\" : \"true\"}"));

            foreach (var item in itemList)
            {
                newProcessor.Process(dataset, item);
            }

            Assert.Equal("20210101000000.000000+0800", dataset.GetDicomItem <DicomElement>(tag1).Get <string>());
            Assert.Equal(@"20210101000000.000000+0800\20210101120000.000000\20210101000000.000000+1400", dataset.GetDicomItem <DicomElement>(tag2).Get <string>());
        }
Beispiel #23
0
        private void ValidateTags(DicomDataset dicomDataset, IEnumerable <QueryTag> queryTags)
        {
            foreach (QueryTag queryTag in queryTags)
            {
                DicomElement dicomElement = dicomDataset.GetDicomItem <DicomElement>(queryTag.Tag);

                if (dicomElement != null)
                {
                    if (dicomElement.ValueRepresentation != queryTag.VR)
                    {
                        throw new DatasetValidationException(
                                  FailureReasonCodes.ValidationFailure,
                                  string.Format(
                                      CultureInfo.InvariantCulture,
                                      DicomCoreResource.MismatchVR,
                                      queryTag.Tag,
                                      queryTag.VR,
                                      dicomElement.ValueRepresentation));
                    }

                    _minimumValidator.Validate(dicomElement);
                }
            }
        }
Beispiel #24
0
        private IList <Reporting.Failure> ProcessDataset(ObjectId documentId, DicomDataset ds, string tagTree = "")
        {
            var nodeCounts = new Dictionary <string, int>();
            var failures   = new List <Reporting.Failure>();

            ds.TryGetString(DicomTag.Modality, out string modality);
            bool hasImageType = ds.TryGetValues(DicomTag.ImageType, out string[] imageTypeArr);

            var imageTypeStr = "";

            if (hasImageType)
            {
                imageTypeStr = string.Join(@"\\", imageTypeArr.Take(2));
            }

            // Prefix the Modality and ImageType tags to allow grouping. This is a temporary solution until the reporting API supports grouping.
            string groupPrefix = modality + SEP + imageTypeStr + SEP;

            foreach (DicomItem item in ds)
            {
                string kw = item.Tag.DictionaryEntry.Keyword;

                var asSequence = item as DicomSequence;
                if (asSequence != null)
                {
                    for (var i = 0; i < asSequence.Count(); ++i)
                    {
                        DicomDataset subDataset = asSequence.ElementAt(i);
                        string       newTagTree = tagTree + kw + "[" + i + "]->";
                        failures.AddRange(ProcessDataset(documentId, subDataset, newTagTree));
                    }

                    continue;
                }

                var    element     = ds.GetDicomItem <DicomElement>(item.Tag);
                string fullTagPath = groupPrefix + tagTree + kw;

                //TODO OverlayRows...
                if (!nodeCounts.ContainsKey(fullTagPath))
                {
                    nodeCounts.Add(fullTagPath, 1);
                }
                else
                {
                    nodeCounts[fullTagPath]++;
                }

                if (element.Count == 0)
                {
                    continue;
                }

                // If it is not a (multi-)string element, continue
                if (!element.ValueRepresentation.IsString)
                {
                    continue;
                }

                // For each string in the element
                //TODO This is slow and should be refactored
                foreach (string s in ds.GetValues <string>(element.Tag))
                {
                    List <FailurePart> parts = Validate(kw, s).ToList();

                    if (parts.Any())
                    {
                        failures.Add(_factory.Create(documentId, fullTagPath, s, parts));
                    }
                }
            }

            AddNodeCounts(nodeCounts);

            return(failures);
        }
 /// <summary>
 /// Returns a basic type (string, double, int, array, dictionary etc) for the given top level <paramref name="tag"/> in the <paramref name="dataset"/>.
 /// </summary>
 /// <param name="dataset"></param>
 /// <param name="tag"></param>
 /// <returns></returns>
 public static object GetCSharpValue(DicomDataset dataset, DicomTag tag)
 {
     return(GetCSharpValue(dataset, dataset.GetDicomItem <DicomItem>(tag)));
 }
Beispiel #26
0
 /// <summary>
 /// Initialize new instance of EncapsulatedPixelData based on existing pixel data.
 /// </summary>
 /// <param name="dataset">The source dataset to extract pixel data from.</param>
 public EncapsulatedPixelData(DicomDataset dataset)
     : base(dataset)
 {
     _element = dataset.GetDicomItem <DicomFragmentSequence>(DicomTag.PixelData);
 }