public void Test_Sequence() { var subDatasets = new List <DicomDataset> { new DicomDataset { new DicomShortString(DicomTag.CodeValue, "CPELVD") } }; var dicomDataset = new DicomDataset { { DicomTag.ProcedureCodeSequence, subDatasets.ToArray() } }; object result = DicomTypeTranslaterReader.GetCSharpValue(dicomDataset, DicomTag.ProcedureCodeSequence); object flat = DicomTypeTranslater.Flatten(result); Console.WriteLine(flat); StringAssert.Contains("CPELVD", (string)flat); StringAssert.Contains("(0008,0100)", (string)flat); }
private void WriteValue(CsvWriter writer, DicomCFindResponse response, DicomTag tag) { var val = DicomTypeTranslaterReader.GetCSharpValue(response.Dataset, tag); if (val == null) { writer.WriteField(""); } else { writer.WriteField(DicomTypeTranslater.Flatten(val)); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); olvFileTags.ClearObjects(); try { var dicom = DicomFile.Open(_fileInfo.FullName, FileReadOption.ReadAll); try { using var renderedImage = new DicomImage(dicom.Dataset).RenderImage().AsSharpImage(); using MemoryStream ms = new(); renderedImage.Save(ms, renderedImage.GetConfiguration().ImageFormatsManager.FindEncoder(PngFormat.Instance)); ms.Seek(0, SeekOrigin.Begin); DicomImage = new(ms); pictureBox1.Image = DicomImage; } catch (Exception) { //no picture splitContainer1.Panel1Collapsed = true; } foreach (DicomItem item in dicom.Dataset) { var value = DicomTypeTranslater.Flatten(DicomTypeTranslaterReader.GetCSharpValue(dicom.Dataset, item)); olvFileTags.AddObject(new TagValueNode(item.Tag, value)); } } catch (Exception exception) { MessageBox.Show(exception.ToString(), "File Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static void RunBatch(IPersonCollection identifiers, ProgramOptions opts, Random r, DataTable[] batches, IBulkCopy[] uploaders) { Stopwatch swGeneration = new Stopwatch(); Stopwatch swReading = new Stopwatch(); Stopwatch swUploading = new Stopwatch(); try { using (var dicomGenerator = GetDataGenerator(opts, identifiers, r, out _)) { for (int i = 0; i < opts.NumberOfStudies; i++) { swGeneration.Start(); var p = identifiers.People[r.Next(identifiers.People.Length)]; var ds = dicomGenerator.GenerateStudyImages(p, out Study s); swGeneration.Stop(); foreach (DicomDataset dataset in ds) { var rows = new DataRow[batches.Length]; for (int j = 0; j < batches.Length; j++) { rows[j] = batches[j].NewRow(); } swReading.Start(); foreach (DicomItem item in dataset) { var column = DicomTypeTranslaterReader.GetColumnNameForTag(item.Tag, false); var value = DicomTypeTranslater.Flatten(DicomTypeTranslaterReader.GetCSharpValue(dataset, item)); foreach (DataRow row in rows) { if (row.Table.Columns.Contains(column)) { row[column] = value ?? DBNull.Value; } } } for (int j = 0; j < batches.Length; j++) { batches[j].Rows.Add(rows[j]); } swReading.Stop(); } //every 100 and last batch if (i % 100 == 0 || i == opts.NumberOfStudies - 1) { swUploading.Start(); for (var j = 0; j < uploaders.Length; j++) { uploaders[j].Upload(batches[j]); batches[j].Rows.Clear(); } swUploading.Stop(); Console.WriteLine($"{DateTime.Now} Done {i} studies"); } } } } finally { for (var i = 0; i < uploaders.Length; i++) { uploaders[i].Dispose(); batches[i].Dispose(); } } Console.WriteLine("Total time Generating Dicoms:" + swGeneration.Elapsed); Console.WriteLine("Total time Reading Dicoms:" + swReading.Elapsed); Console.WriteLine("Total time Uploading Records:" + swUploading.Elapsed); }
/// <summary> /// Iterates through each DicomItem in the DicomDataset and creates a corresponding column in the DataTable (if it is a novel tag) and then populates /// the DataTable with the data for the image. /// </summary> /// <param name="filename"></param> /// <param name="ds"></param> /// <param name="dt"></param> /// <param name="listener"></param> /// <param name="otherValuesToStoreInRow"></param> protected void ProcessDataset(string filename, DicomDataset ds, DataTable dt, IDataLoadEventListener listener, Dictionary <string, string> otherValuesToStoreInRow = null) { if (_elevationRequests == null) { _elevationRequests = LoadElevationRequestsFile(); } filename = ApplyArchiveRootToMakeRelativePath(filename); var rowValues = new Dictionary <string, object>(); foreach (DicomItem item in ds) { //get the tag name (human readable) var entry = item.Tag.DictionaryEntry; string header = entry.Keyword; if (ShouldSkip(dt, item.Tag)) { continue; } object value; switch (InvalidDataHandlingStrategy) { case InvalidDataHandling.ThrowException: //enforce types and leave any Exceptions uncaught value = DicomTypeTranslater.Flatten(DicomTypeTranslaterReader.GetCSharpValue(ds, item)); break; case InvalidDataHandling.MarkCorrupt: try { //try to enforce types value = DicomTypeTranslater.Flatten(DicomTypeTranslaterReader.GetCSharpValue(ds, item)); } catch (Exception ex) { //something went wrong pulling out the value //mark it as corrupt MarkCorrupt(ds); //but make sure to warn people listening listener.OnNotify(this, new NotifyEventArgs(ProgressEventType.Warning, "Could not GetCSharpValue for DicomItem " + item.Tag + "(" + entry.Keyword + ") for " + GetProblemFileDescription(filename, otherValuesToStoreInRow), ex)); //do not add the row to the table return; } break; case InvalidDataHandling.ConvertToNullAndWarn: //try to enforce types try { value = DicomTypeTranslater.Flatten(DicomTypeTranslaterReader.GetCSharpValue(ds, item)); } catch (Exception ex) { //but make sure to warn people listening listener.OnNotify(this, new NotifyEventArgs(ProgressEventType.Warning, "Could not GetCSharpValue for DicomItem " + item.Tag + "(" + entry.Keyword + ") for " + GetProblemFileDescription(filename, otherValuesToStoreInRow), ex)); if (InvalidDataHandlingStrategy == InvalidDataHandling.MarkCorrupt) { MarkCorrupt(ds); continue; } //It went wrong, we couldn't enforce the type so just use null instead value = DBNull.Value; } break; default: throw new ArgumentOutOfRangeException(); } if (value is string && DataTooLongHandlingStrategy != DataTooWideHandling.None) { if (!IsValidLength(listener, item.Tag, (string)value)) { //the string is too long! switch (DataTooLongHandlingStrategy) { case DataTooWideHandling.TruncateAndWarn: lock (_oDictLock) { value = ((string)value).Substring(0, _maxTagLengths[item.Tag]); } break; case DataTooWideHandling.MarkCorrupt: MarkCorrupt(ds); continue; case DataTooWideHandling.ConvertToNullAndWarn: value = DBNull.Value; break; default: throw new ArgumentOutOfRangeException(); } } } try { rowValues.Add(header, value); } catch (Exception e) { listener.OnNotify(this, new NotifyEventArgs(ProgressEventType.Warning, "Error getting Tag '" + header + "' item.ValueRepresentation is (" + item.ValueRepresentation + ") " + GetProblemFileDescription(filename, otherValuesToStoreInRow), e)); } } //now run elevation requests if (_elevationRequests != null) { foreach (TagElevationRequest request in _elevationRequests.Requests) { try { object value; switch (InvalidDataHandlingStrategy) { case InvalidDataHandling.ThrowException: value = request.Elevator.GetValue(ds); break; case InvalidDataHandling.ConvertToNullAndWarn: try { value = request.Elevator.GetValue(ds); } catch (Exception e) { if (e is TagNavigationException) { throw; } listener.OnNotify(this, new NotifyEventArgs(ProgressEventType.Warning, "Error getting Tag for ElevationRequest '" + request.ColumnName + "' for " + GetProblemFileDescription(filename, otherValuesToStoreInRow), e)); value = DBNull.Value; } break; default: throw new ArgumentOutOfRangeException(); } rowValues.Add(request.ColumnName, value); } catch (TagNavigationException e) { listener.OnNotify(this, new NotifyEventArgs(ProgressEventType.Warning, "Rule for column " + request.ColumnName + " failed to resolve GetValue for " + GetProblemFileDescription(filename, otherValuesToStoreInRow), e)); } } } //do not add rows if there is nothing to store if (!rowValues.Any()) { return; } lock (_oDataTableLock) { var row = dt.Rows.Add(); row[FilenameField] = filename; if (otherValuesToStoreInRow != null) { foreach (KeyValuePair <string, string> kvp in otherValuesToStoreInRow) { if (!dt.Columns.Contains(kvp.Key)) { dt.Columns.Add(kvp.Key); } row[kvp.Key] = kvp.Value; } } foreach (KeyValuePair <string, object> keyValuePair in rowValues) { Add(dt, row, keyValuePair.Key, keyValuePair.Value); } } }
public void ExampleUsage_Simple() { //create an Fo-Dicom dataset with a single string var ds = new DicomDataset(new List <DicomItem>() { new DicomShortString(DicomTag.PatientName, "Frank"), new DicomAgeString(DicomTag.PatientAge, "032Y"), new DicomDate(DicomTag.PatientBirthDate, new DateTime(2001, 1, 1)) }); object name = DicomTypeTranslaterReader.GetCSharpValue(ds, DicomTag.PatientName); Assert.AreEqual(typeof(string), name.GetType()); Assert.AreEqual("Frank", name); object age = DicomTypeTranslaterReader.GetCSharpValue(ds, DicomTag.PatientAge); Assert.AreEqual(typeof(string), age.GetType()); Assert.AreEqual("032Y", age); object dob = DicomTypeTranslaterReader.GetCSharpValue(ds, DicomTag.PatientBirthDate); Assert.AreEqual(typeof(DateTime), dob.GetType()); Assert.AreEqual(new DateTime(2001, 01, 01), dob); //create an Fo-Dicom dataset with string multiplicity ds = new DicomDataset(new List <DicomItem>() { new DicomShortString(DicomTag.PatientName, "Frank", "Anderson") }); //Get the C# type object name2 = DicomTypeTranslaterReader.GetCSharpValue(ds, DicomTag.PatientName); Assert.AreEqual(typeof(string[]), name2.GetType()); Assert.AreEqual(new string[] { "Frank", "Anderson" }, name2); name2 = DicomTypeTranslater.Flatten(name2); Assert.AreEqual(typeof(string), name2.GetType()); Assert.AreEqual("Frank\\Anderson", name2); //create an Fo-Dicom dataset with a sequence ds = new DicomDataset(new List <DicomItem>() { new DicomUniqueIdentifier(DicomTag.SOPInstanceUID, "1.2.3"), new DicomSequence(DicomTag.ActualHumanPerformersSequence, new [] { new DicomDataset(new List <DicomItem>() { new DicomShortString(DicomTag.PatientName, "Rabbit") }), new DicomDataset(new List <DicomItem>() { new DicomShortString(DicomTag.PatientName, "Roger") }) }) }); var seq = (Dictionary <DicomTag, object>[])DicomTypeTranslaterReader.GetCSharpValue(ds, DicomTag.ActualHumanPerformersSequence); Assert.AreEqual("Rabbit", seq[0][DicomTag.PatientName]); Assert.AreEqual("Roger", seq[1][DicomTag.PatientName]); var flattened = (string)DicomTypeTranslater.Flatten(seq); Assert.AreEqual( @"[0] - (0010,0010) - Rabbit [1] - (0010,0010) - Roger" .Replace("\r", ""), flattened.Replace("\r", "")); }