public bool OnElement(DicomElement element) { var tag = String.Format( "{0}{1} {2}", Indent, element.Tag.ToString().ToUpper(), element.Tag.DictionaryEntry.Name); string value = "<large value not displayed>"; if (element.Length <= 2048) { value = String.Join("\\", element.Get <string[]>()); } if (element.ValueRepresentation == DicomVR.UI && element.Count > 0) { var uid = element.Get <DicomUID>(0); var name = uid.Name; if (name != "Unknown") { value = String.Format("{0} ({1})", value, name); } } Form.AddItem(tag, element.ValueRepresentation.Code, element.Length.ToString(), value); return(true); }
public bool OnElement(DicomElement element) { StringBuilder sb = new StringBuilder(); if (_depth > 0) { sb.Append(_pad).Append("> "); } sb.Append(element.Tag); sb.Append(' '); sb.Append(element.ValueRepresentation.Code); sb.Append(' '); if (element.Length == 0) { sb.Append("(no value available)"); } else if (element.ValueRepresentation.IsString) { sb.Append('['); string val = element.Get <string>(); if (val.Length > (_value - 2 - sb.Length)) { sb.Append(val.Substring(0, _value - 2 - sb.Length)); sb.Append(')'); } else { sb.Append(val); sb.Append(']'); } } else if (element.Length >= 1024) { sb.Append("<skipping large element>"); } else { var val = String.Join("/", element.Get <string[]>()); if (val.Length > (_value - sb.Length)) { sb.Append(val.Substring(0, _value - sb.Length)); } else { sb.Append(val); } } while (sb.Length < _value) { sb.Append(' '); } sb.Append('#'); string name = element.Tag.DictionaryEntry.Keyword; sb.AppendFormat("{0,6}, {1}", element.Length, name.Substring(0, System.Math.Min(_width - sb.Length - 9, name.Length))); _log.AppendLine(sb.ToString()); return(true); }
/// <summary> /// Handler for traversing a DICOM element. /// </summary> /// <param name="element">Element to traverse.</param> /// <returns>true if traversing completed without issues, false otherwise.</returns> public bool OnElement(DicomElement element) { StringBuilder sb = new StringBuilder(); if (_depth > 0) sb.Append(_pad).Append("> "); sb.Append(element.Tag); sb.Append(' '); sb.Append(element.ValueRepresentation.Code); sb.Append(' '); if (element.Length == 0) { sb.Append("(no value available)"); } else if (element.ValueRepresentation.IsString) { sb.Append('['); string val = element.Get<string>(); if (val.Length > (_value - 2 - sb.Length)) { sb.Append(val.Substring(0, _value - 2 - sb.Length)); sb.Append(')'); } else { sb.Append(val); sb.Append(']'); } } else if (element.Length >= 1024) { sb.Append("<skipping large element>"); } else { var val = String.Join("/", element.Get<string[]>()); if (val.Length > (_value - sb.Length)) { sb.Append(val.Substring(0, _value - sb.Length)); } else { sb.Append(val); } } while (sb.Length < _value) sb.Append(' '); sb.Append('#'); string name = element.Tag.DictionaryEntry.Keyword; sb.AppendFormat( "{0,6}, {1}", element.Length, name.Substring(0, System.Math.Min(_width - sb.Length - 9, name.Length))); _log.AppendLine(sb.ToString()); return true; }
protected virtual void WriteVR_PN(DicomElement element, XmlWriter writer) { for (int index = 0; index < element.Count; index++) { writer.WriteStartElement(Constants.PN_PERSON_NAME); WriteNumberAttrib(writer, index); var pnComponents = GetTrimmedString(element.Get <string> ( )).Split('='); for (int compIndex = 0; (compIndex < pnComponents.Length) && (compIndex < 3); compIndex++) { writer.WriteStartElement(Utilities.PersonNameComponents.PN_Components[compIndex]); DicomPersonName pn = new DicomPersonName(element.Tag, pnComponents[compIndex]); writer.WriteElementString(Utilities.PersonNameParts.PN_Family, pn.Last); writer.WriteElementString(Utilities.PersonNameParts.PN_Given, pn.First); writer.WriteElementString(Utilities.PersonNameParts.PN_Midlle, pn.Middle); writer.WriteElementString(Utilities.PersonNameParts.PN_Prefix, pn.Prefix); writer.WriteElementString(Utilities.PersonNameParts.PN_Suffix, pn.Suffix); writer.WriteEndElement( ); } writer.WriteEndElement( ); } }
public bool OnElement(DicomElement element) { if (element.Tag.Equals(DicomTag.NumberOfContourPoints)) { _numberOfCountourPoints = element.Get <int>(); } if (element.Tag.Equals(DicomTag.FinalCumulativeMetersetWeight)) { _maxFinalCumulativeMetersetWeight = Math.Max( element.Get <double>(), _maxFinalCumulativeMetersetWeight); } var success = !element.Tag.Equals(DicomTag.AcquisitionDate); return(success); }
public override void Validate(DicomElement dicomElement) { base.Validate(dicomElement); string value = dicomElement.Get <string>(); Validate(value, MaxLength, dicomElement.Tag.GetFriendlyName(), dicomElement.ValueRepresentation); }
public bool OnElement(DicomElement element) { var tag = String.Format("{0} {1}", element.Tag.ToString().ToUpper(), element.Tag.DictionaryEntry.Name); var value = element.Length <= 2048 ? String.Join("\\", element.Get<string[]>()) : "<large value not displayed>"; if (element.ValueRepresentation == DicomVR.UI && element.Count > 0) { var uid = element.Get<DicomUID>(0); var name = uid.Name; if (name != "Unknown") value = String.Format("{0} ({1})", value, name); } TextItems.Add(new DicomTextItem(_level, tag, element.ValueRepresentation.Code, element.Length, value)); return true; }
public override void Validate(DicomElement dicomElement) { base.Validate(dicomElement); string value = dicomElement.Get <string>(); string name = dicomElement.Tag.GetFriendlyName(); Validate(value, name); }
public void OnElement(IByteSource source, DicomTag tag, DicomVR vr, IByteBuffer data) { DicomElement element = vr.Code switch { "AE" => new DicomApplicationEntity(tag, data), "AS" => new DicomAgeString(tag, data), "AT" => new DicomAttributeTag(tag, data), "CS" => new DicomCodeString(tag, data), "DA" => new DicomDate(tag, data), "DS" => new DicomDecimalString(tag, data), "DT" => new DicomDateTime(tag, data), "FD" => new DicomFloatingPointDouble(tag, data), "FL" => new DicomFloatingPointSingle(tag, data), "IS" => new DicomIntegerString(tag, data), "LO" => new DicomLongString(tag, _encodings.Peek(), data), "LT" => new DicomLongText(tag, _encodings.Peek(), data), "OB" => new DicomOtherByte(tag, data), "OD" => new DicomOtherDouble(tag, data), "OF" => new DicomOtherFloat(tag, data), "OL" => new DicomOtherLong(tag, data), "OV" => new DicomOtherVeryLong(tag, data), "OW" => new DicomOtherWord(tag, data), "PN" => new DicomPersonName(tag, _encodings.Peek(), data), "SH" => new DicomShortString(tag, _encodings.Peek(), data), "SL" => new DicomSignedLong(tag, data), "SS" => new DicomSignedShort(tag, data), "ST" => new DicomShortText(tag, _encodings.Peek(), data), "SV" => new DicomSignedVeryLong(tag, data), "TM" => new DicomTime(tag, data), "UC" => new DicomUnlimitedCharacters(tag, _encodings.Peek(), data), "UI" => new DicomUniqueIdentifier(tag, data), "UL" => new DicomUnsignedLong(tag, data), "UN" => new DicomUnknown(tag, data), "UR" => new DicomUniversalResource(tag, _encodings.Peek(), data), "US" => new DicomUnsignedShort(tag, data), "UT" => new DicomUnlimitedText(tag, _encodings.Peek(), data), "UV" => new DicomUnsignedVeryLong(tag, data), _ => throw new DicomDataException($"Unhandled VR in DICOM parser observer: {vr.Code}"), }; if (element.Tag == DicomTag.SpecificCharacterSet) { Encoding[] encodings = _encodings.Peek(); if (element.Count > 0) { encodings = DicomEncoding.GetEncodings(element.Get <string[]>(0)); } _encodings.Pop(); _encodings.Push(encodings); } DicomDataset ds = _datasets.Peek(); ds.AddOrUpdate(element); }
private static bool TryGetAsString(DicomElement dicomElement, out string value) { value = string.Empty; if (StringVrs.Contains(dicomElement.ValueRepresentation)) { value = dicomElement.Get <string>(); return(true); } return(false); }
/// <summary> /// Write any subclass of <see cref="DicomStringElement"/> to json /// </summary> /// <param name="writer"></param> /// <param name="elem"></param> private static void WriteJsonStringElement(JsonWriter writer, DicomElement elem) { if (elem.Count == 0) { return; } writer.WritePropertyName(VALUE_PROPERTY_NAME); string val = elem.Get <string>().TrimEnd('\0'); writer.WriteValue(val); }
public override void Validate(DicomElement dicomElement) { base.Validate(dicomElement); string value = dicomElement.Get <string>(); string name = dicomElement.Tag.GetFriendlyName(); if (string.IsNullOrEmpty(value)) { return; } DicomValidation.ValidateTM(value); }
private static void WriteJsonDecimalString(JsonWriter writer, DicomElement elem) { if (elem.Count == 0) { return; } writer.WritePropertyName("Value"); writer.WriteStartArray(); foreach (string val in elem.Get <string[]>()) { if (val == null || val.Equals("")) { writer.WriteNull(); } else { string fix = FixDecimalString(val); if (fix == null) { throw new FormatException($"Could not parse DS value {val} to a valid json number"); } if (ulong.TryParse(fix, NumberStyles.Integer, CultureInfo.InvariantCulture, out ulong xulong)) { writer.WriteValue(xulong); } else if (long.TryParse(fix, NumberStyles.Integer, CultureInfo.InvariantCulture, out long xlong)) { writer.WriteValue(xlong); } else if (decimal.TryParse(fix, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal xdecimal)) { writer.WriteValue(xdecimal); } else if (double.TryParse(fix, NumberStyles.Float, CultureInfo.InvariantCulture, out double xdouble)) { writer.WriteValue(xdouble); } else { throw new FormatException($"Could not parse DS value {fix} to a valid C# type"); } } } writer.WriteEndArray(); }
public override void Validate(DicomElement dicomElement) { base.Validate(dicomElement); string value = dicomElement.Get <string>(); string name = dicomElement.Tag.GetFriendlyName(); DicomVR vr = dicomElement.ValueRepresentation; if (string.IsNullOrEmpty(value)) { // empty values allowed return; } var groups = value.Split('='); if (groups.Length > 3) { throw ElementValidationExceptionFactory.CreatePersonNameExceedMaxGroupsException(name, value); } foreach (var group in groups) { try { ElementMaxLengthValidation.Validate(group, 64, name, dicomElement.ValueRepresentation); } catch (ElementValidationException ex) when(ex.ErrorCode == ValidationErrorCode.ExceedMaxLength) { // Reprocess the exception to make more meaningful message throw ElementValidationExceptionFactory.CreatePersonNameGroupExceedMaxLengthException(name, value); } if (ContainsControlExceptEsc(group)) { throw ElementValidationExceptionFactory.CreateInvalidCharactersException(name, vr, value); } } var groupcomponents = groups.Select(group => group.Split('^').Length); if (groupcomponents.Any(l => l > 5)) { throw ElementValidationExceptionFactory.CreatePersonNameExceedMaxComponentsException(name, value); } }
public override void Validate(DicomElement dicomElement) { base.Validate(dicomElement); string value = dicomElement.Get <string>(); string name = dicomElement.Tag.GetFriendlyName(); if (string.IsNullOrEmpty(value)) { return; } if (!DateTime.TryParseExact(value, DateFormatDA, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out _)) { throw ElementValidationExceptionFactory.CreateDateIsInvalidException(name, value); } }
public bool OnElement(DicomElement element) { var tag = String.Format("{0}{1} {2}", Indent, element.Tag.ToString().ToUpper(), element.Tag.DictionaryEntry.Name); string value = "<large value not displayed>"; if (element.Length <= 2048) { value = String.Join("\\", element.Get <string[]>()); } Form.AddItem(tag, element.ValueRepresentation.Code, element.Length.ToString(), value); return(true); }
private static void WriteDicomValueElement <T>(JsonWriter writer, DicomElement elem) where T : struct { if (elem.Count == 0) { return; } writer.WritePropertyName(VALUE_PROPERTY_NAME); writer.WriteStartArray(); foreach (T val in elem.Get <T[]>()) { writer.WriteValue(val); } writer.WriteEndArray(); }
private static void WriteJsonDecimalString(JsonWriter writer, DicomElement elem) { if (elem.Count != 0) { writer.WritePropertyName("Value"); writer.WriteStartArray(); foreach (var val in elem.Get <string[]>()) { if (val == null || val.Equals("")) { writer.WriteNull(); } else { ulong xulong; long xlong; decimal xdecimal; double xdouble; var fix = FixDecimalString(val); if (ulong.TryParse(fix, NumberStyles.Integer, CultureInfo.InvariantCulture, out xulong)) { writer.WriteValue(xulong); } else if (long.TryParse(fix, NumberStyles.Integer, CultureInfo.InvariantCulture, out xlong)) { writer.WriteValue(xlong); } else if (decimal.TryParse(fix, NumberStyles.Float, CultureInfo.InvariantCulture, out xdecimal)) { writer.WriteValue(xdecimal); } else if (double.TryParse(fix, NumberStyles.Float, CultureInfo.InvariantCulture, out xdouble)) { writer.WriteValue(xdouble); } else { throw new FormatException(string.Format("Cannot write dicom number {0} to json", val)); } } } writer.WriteEndArray(); } }
private static void WriteJsonIntegerString(JsonWriter writer, DicomElement elem) { if (elem.Count == 0) { return; } writer.WritePropertyName("Value"); writer.WriteStartArray(); foreach (string val in elem.Get <string[]>()) { if (val == null || val.Equals("")) { writer.WriteNull(); } else { // Want to try to fix the value and write as an int, otherwise have to throw since we can't read it back currently string fix = FixIntegerString(val); if (fix == null) { _logger.Warn("Could not parse IS value \"" + val + "\" to an integer, writing null and continuing"); writer.WriteNull(); continue; } if (int.TryParse(fix, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed)) { writer.WriteValue(parsed); } else { throw new FormatException(string.Format("Cannot write dicom IntegerString \"{0}\" to json", val)); } } } writer.WriteEndArray(); }
private static void WriteJsonAttributeTag(JsonWriter writer, DicomElement elem) { if (elem.Count != 0) { writer.WritePropertyName("Value"); writer.WriteStartArray(); foreach (var val in elem.Get <DicomTag[]>()) { if (val == null) { writer.WriteNull(); } else { writer.WriteValue(((uint)val).ToString("X8")); } } writer.WriteEndArray(); } }
private static void WriteJsonElement <T>(JsonWriter writer, DicomElement elem) { if (elem.Count != 0) { writer.WritePropertyName("Value"); writer.WriteStartArray(); foreach (var val in elem.Get <T[]>()) { if (val == null || (typeof(T) == typeof(string) && val.Equals(""))) { writer.WriteNull(); } else { writer.WriteValue(val); } } writer.WriteEndArray(); } }
protected virtual void WriteVR_PN(DicomElement element, JsonWriter writer) { writer.WritePropertyName(JsonConstants.ValueField); writer.WriteStartArray( ); for (int index = 0; index < element.Count; index++) { writer.WriteStartObject( ); var pnComponents = GetTrimmedString(element.Get <string> ( )).Split('='); for (int compIndex = 0; (compIndex < pnComponents.Length) && (compIndex < 3); compIndex++) { writer.WritePropertyName(Utilities.PersonNameComponents.PN_Components[compIndex]); writer.WriteValue(GetTrimmedString(pnComponents[compIndex])); writer.WriteEndObject( ); } } writer.WriteEndArray( ); }
private static void WriteJsonElement <T>(Utf8JsonWriter writer, DicomElement elem, WriteValue <T> writeValue) { if (elem.Count != 0) { writer.WritePropertyName("Value"); writer.WriteStartArray(); foreach (var val in elem.Get <T[]>()) { if (val == null || (typeof(T) == typeof(string) && val.Equals(""))) { writer.WriteNullValue(); } else if (val is float f && float.IsNaN(f)) { writer.WriteStringValue("NaN"); } else { writeValue(writer, val); } }
private static void WriteJsonDecimalString(Utf8JsonWriter writer, DicomElement elem) { if (elem.Count != 0) { writer.WritePropertyName("Value"); writer.WriteStartArray(); foreach (var val in elem.Get <string[]>()) { if (string.IsNullOrEmpty(val)) { writer.WriteNullValue(); } else { var fix = FixDecimalString(val); if (TryParseULong(fix, out ulong xulong)) { writer.WriteNumberValue(xulong); } else if (TryParseLong(fix, out long xlong)) { writer.WriteNumberValue(xlong); } else if (TryParseDecimal(fix, out decimal xdecimal)) { writer.WriteNumberValue(xdecimal); } else if (TryParseDouble(fix, out double xdouble)) { writer.WriteNumberValue(xdouble); } else { throw new FormatException($"Cannot write dicom number {val} to json"); } } } writer.WriteEndArray(); } }
private static void WriteJsonAttributeTag(JsonWriter writer, DicomElement elem) { if (elem.Count == 0) { return; } writer.WritePropertyName(VALUE_PROPERTY_NAME); var sb = new StringBuilder(); foreach (DicomTag val in elem.Get <DicomTag[]>()) { sb.Append(((uint)val).ToString("X8")); } if (sb.Length % 8 != 0) { throw new JsonException("AttributeTag string of length " + sb.Length + " is not divisible by 8"); } writer.WriteValue(sb.ToString()); }
// only works for single value dicom element public void Validate(DicomElement element) { EnsureArg.IsNotNull(element, nameof(element)); DicomVR dicomVR = element.ValueRepresentation; if (dicomVR == null) { Debug.Fail("Dicom VR type should not be null"); } if (_stringValidators.TryGetValue(dicomVR, out Action <string, string> stringValidator)) { stringValidator(element.Get <string>(), GetName(element.Tag)); } else if (_byteBufferValidators.TryGetValue(dicomVR, out Action <IByteBuffer, string> byteBufferValidator)) { byteBufferValidator(element.Buffer, GetName(element.Tag)); } else { Debug.Fail($"Missing validation action for for VR :{dicomVR.Code}, add a new validation and register in the constructor."); } }
protected virtual void WriteVR_Default ( DicomDataset ds, DicomElement element, JsonWriter writer, DicomVR dicomVr ) { writer.WritePropertyName(JsonConstants.ValueField); writer.WriteStartArray( ); for (int index = 0; index < element.Count; index++) { string stringValue = GetTrimmedString(element.Get <string> (index)); if (_numberBasedVrs.Contains(element.ValueRepresentation.Code)) { //parse with the greatest type that can handle //need to do that to remove the ' ' around the string if (_decimalBasedVrs.Contains(element.ValueRepresentation.Code)) { writer.WriteValue(double.Parse(stringValue, System.Globalization.NumberStyles.Any)); } else { writer.WriteValue(long.Parse(stringValue, System.Globalization.NumberStyles.Number)); } } else { writer.WriteValue(stringValue); } } writer.WriteEndArray( ); }
public bool OnElement(DicomElement element) { if (element.Tag.Equals(DicomTag.NumberOfContourPoints)) { this.numberOfCountourPoints = element.Get<int>(); } if (element.Tag.Equals(DicomTag.FinalCumulativeMetersetWeight)) { this.maxFinalCumulativeMetersetWeight = Math.Max( element.Get<double>(), this.maxFinalCumulativeMetersetWeight); } var success = !element.Tag.Equals(DicomTag.AcquisitionDate); return success; }
public bool OnElement(DicomElement element) { var tag = String.Format("{0}{1} {2}", Indent, element.Tag.ToString().ToUpper(), element.Tag.DictionaryEntry.Name); string value = "<large value not displayed>"; if (element.Length <= 2048) value = String.Join("\\", element.Get<string[]>()); if (element.ValueRepresentation == DicomVR.UI && element.Count > 0) { var uid = element.Get<DicomUID>(0); var name = uid.Name; if (name != "Unknown") value = String.Format("{0} ({1})", value, name); } Form.appendToInfo(String.Join( " ", tag, element.ValueRepresentation.Code, element.Length.ToString(), value) + "\r\n"); return true; }
private static void DicomElementToXml(StringBuilder xmlOutput, DicomElement item) { WriteDicomAttribute(xmlOutput, item); var vr = item.ValueRepresentation.Code; if (vr == DicomVRCode.OB || vr == DicomVRCode.OD || vr == DicomVRCode.OF || vr == DicomVRCode.OW || vr == DicomVRCode.OL || vr == DicomVRCode.UN) { var binaryString = GetBinaryBase64(item); xmlOutput.AppendLine($@"<InlineBinary>{binaryString}</InlineBinary>"); } else if (vr == DicomVRCode.PN) { for (int i = 0; i < item.Count; i++) { xmlOutput.AppendLine($@"<PersonName number=""{i+1}"">"); xmlOutput.AppendLine(@"<Alphabetic>"); var person = new DicomPersonName(item.Tag, item.Get <string>(i)); string lastName = person.Last; if (!string.IsNullOrEmpty(lastName)) { xmlOutput.AppendLine($@"<FamilyName>{EscapeXml(lastName)}</FamilyName>"); } string givenName = person.First; if (!string.IsNullOrEmpty(givenName)) { xmlOutput.AppendLine($@"<GivenName>{EscapeXml(givenName)}</GivenName>"); } string middleName = person.Middle; if (!string.IsNullOrEmpty(middleName)) { xmlOutput.AppendLine($@"<MiddleName>{EscapeXml(middleName)}</MiddleName>"); } string prefixName = person.Prefix; if (!string.IsNullOrEmpty(prefixName)) { xmlOutput.AppendLine($@"<NamePrefix>{EscapeXml(prefixName)}</NamePrefix>"); } string suffixName = person.Suffix; if (!string.IsNullOrEmpty(suffixName)) { xmlOutput.AppendLine($@"<NameSuffix>{EscapeXml(suffixName)}</NameSuffix>"); } xmlOutput.AppendLine(@"</Alphabetic>"); xmlOutput.AppendLine(@"</PersonName>"); } } else { for (int i = 0; i < item.Count; i++) { var valueString = EscapeXml(item.Get <string>(i)); xmlOutput.AppendLine($@"<Value number=""{i+1}"">{valueString}</Value>"); } } xmlOutput.AppendLine(@"</DicomAttribute>"); }