public void AddFile_AnonymizedSeries_AllFilesAddedToSameStudySeriesNode()
        {
            var dicomFiles = GetDicomFilesFromWebZip(
                "https://www.creatis.insa-lyon.fr/~jpr/PUBLIC/gdcm/gdcmSampleData/Philips_Medical_Images/mr711-mr712/abd1.zip");

            // Anonymize all files
            var anonymizer = new DicomAnonymizer();

            foreach (var dicomFile in dicomFiles)
            {
                anonymizer.AnonymizeInPlace(dicomFile);
            }

            // Create DICOM directory
            var dicomDir = new DicomDirectory();

            foreach (var dicomFile in dicomFiles)
            {
                dicomDir.AddFile(dicomFile);
            }

            var imageNodes = dicomDir.RootDirectoryRecord.LowerLevelDirectoryRecord.LowerLevelDirectoryRecord
                             .LowerLevelDirectoryRecordCollection;

            Assert.Equal(dicomFiles.Count, imageNodes.Count());
        }
Exemple #2
0
        /// <summary>
        /// Asynchronously read DICOM Directory from stream.
        /// </summary>
        /// <param name="stream">Stream to read.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomDirectory"/> instance.</returns>
        public static new async Task <DicomDirectory> OpenAsync(Stream stream, Encoding fallbackEncoding, Func <ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException(nameof(fallbackEncoding));
            }
            var df = new DicomDirectory();

            try
            {
                var source = new StreamByteSource(stream);

                var reader      = new DicomFileReader();
                var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

                var result =
                    await
                    reader.ReadAsync(
                        source,
                        new DicomDatasetReaderObserver(df.FileMetaInfo),
                        new DicomReaderMultiObserver(
                            new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding),
                            dirObserver),
                        stop).ConfigureAwait(false);

                return(FinalizeDicomDirectoryLoad(df, reader, dirObserver, result));
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Exemple #3
0
        private static void WriteMedia(string path)
        {
            var dirInfo  = new DirectoryInfo(path);
            var dicomDir = new DicomDirectory(false);

            foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                if (!file.FullName.StartsWith(dirInfo.FullName))
                {
                    throw new ArgumentException("file");
                }
                if (file.Name == "DICOMDIR")
                {
                    continue;
                }
                try
                {
                    dicomDir.AddFile(DicomFile.Open(file.FullName), file.FullName.Substring(dirInfo.FullName.Length).TrimStart(Path.DirectorySeparatorChar));
                }
                catch
                {
                }
            }
            if (dicomDir.RootDirectoryRecord != null)
            {
                dicomDir.Save(Path.Combine(path, "DICOMDIR"));
            }
        }
Exemple #4
0
        /// <summary>
        /// Read DICOM Directory.
        /// </summary>
        /// <param name="fileName">File name.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns><see cref="DicomDirectory"/> instance.</returns>
        public static new DicomDirectory Open(string fileName, Encoding fallbackEncoding, Func <ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException(nameof(fallbackEncoding));
            }
            var df = new DicomDirectory();

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

                using (var source = new FileByteSource(df.File))
                {
                    var reader      = new DicomFileReader();
                    var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

                    var result = reader.Read(
                        source,
                        new DicomDatasetReaderObserver(df.FileMetaInfo),
                        new DicomReaderMultiObserver(
                            new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding),
                            dirObserver),
                        stop);

                    return(FinalizeDicomDirectoryLoad(df, reader, dirObserver, result));
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Exemple #5
0
        public void AddFile_AnonymizedSeries_AllFilesAddedToSameStudySeriesNode()
        {
            var dicomFiles = GetDicomFilesFromWebZip(
                "https://www.creatis.insa-lyon.fr/~jpr/PUBLIC/gdcm/gdcmSampleData/Philips_Medical_Images/mr711-mr712/abd1.zip");

            // Anonymize all files
            var anonymizer = new DicomAnonymizer();

            foreach (var dicomFile in dicomFiles)
            {
                anonymizer.AnonymizeInPlace(dicomFile);
            }

            // Create DICOM directory
            var dicomDir = new DicomDirectory();

            foreach (var dicomFile in dicomFiles)
            {
                var entry = dicomDir.AddFile(dicomFile);
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID), entry.InstanceRecord.GetSingleValue <string>(DicomTag.ReferencedSOPInstanceUIDInFile));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID), entry.SeriesRecord.GetSingleValue <string>(DicomTag.SeriesInstanceUID));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID), entry.StudyRecord.GetSingleValue <string>(DicomTag.StudyInstanceUID));
            }

            var imageNodes = dicomDir.RootDirectoryRecord.LowerLevelDirectoryRecord.LowerLevelDirectoryRecord
                             .LowerLevelDirectoryRecordCollection;

            Assert.Equal(dicomFiles.Count, imageNodes.Count());
        }
Exemple #6
0
        public new static IAsyncResult BeginOpen(string fileName, AsyncCallback callback, object state)
        {
            var df = new DicomDirectory();

            // reset datasets
            df.FileMetaInfo.Clear();
            df.Dataset.Clear();

            df.File = new FileReference(fileName);

            FileByteSource source = new FileByteSource(df.File);

            EventAsyncResult result = new EventAsyncResult(callback, state);

            DicomFileReader reader = new DicomFileReader();

            var datasetObserver = new DicomDatasetReaderObserver(df.Dataset);
            var dirObserver     = new DicomDirectoryReaderObserver(df.Dataset);

            reader.BeginRead(source,
                             new DicomDatasetReaderObserver(df.FileMetaInfo),
                             new DicomReaderMultiObserver(datasetObserver, dirObserver),
                             OnReadComplete, new Tuple <DicomFileReader, DicomDirectory, DicomDirectoryReaderObserver, EventAsyncResult>(reader, df, dirObserver, result));

            return(result);
        }
Exemple #7
0
        public new static DicomDirectory Open(string fileName)
        {
            var df = new DicomDirectory();

            // reset datasets
            df.FileMetaInfo.Clear();
            df.Dataset.Clear();

            try {
                df.File = new FileReference(fileName);

                using (var source = new FileByteSource(df.File)) {
                    DicomFileReader reader = new DicomFileReader();

                    var datasetObserver = new DicomDatasetReaderObserver(df.Dataset);
                    var dirObserver     = new DicomDirectoryReaderObserver(df.Dataset);

                    reader.Read(source,
                                new DicomDatasetReaderObserver(df.FileMetaInfo),
                                new DicomReaderMultiObserver(datasetObserver, dirObserver));

                    df.Format = reader.FileFormat;

                    df.Dataset.InternalTransferSyntax = reader.Syntax;

                    df._directoryRecordSequence = df.Dataset.Get <DicomSequence>(DicomTag.DirectoryRecordSequence);
                    df.RootDirectoryRecord      = dirObserver.BuildDirectoryRecords();

                    return(df);
                }
            } catch (Exception e) {
                throw new DicomFileException(df, e.Message, e);
            }
        }
        public void AddFile_AnonymizedSeries_AllFilesAddedToSameStudySeriesNode()
        {
            var dicomFiles = GetDicomFilesFromZip(@".\Test Data\abd1.zip");

            // Anonymize all files
            var anonymizer = new DicomAnonymizer();

            foreach (var dicomFile in dicomFiles)
            {
                anonymizer.AnonymizeInPlace(dicomFile);
            }

            // Create DICOM directory
            var dicomDir = new DicomDirectory();

            foreach (var dicomFile in dicomFiles)
            {
                var entry = dicomDir.AddFile(dicomFile);
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID), entry.InstanceRecord.GetSingleValue <string>(DicomTag.ReferencedSOPInstanceUIDInFile));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID), entry.SeriesRecord.GetSingleValue <string>(DicomTag.SeriesInstanceUID));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID), entry.StudyRecord.GetSingleValue <string>(DicomTag.StudyInstanceUID));
            }

            var imageNodes = dicomDir.RootDirectoryRecord.LowerLevelDirectoryRecord.LowerLevelDirectoryRecord
                             .LowerLevelDirectoryRecordCollection;

            Assert.Equal(dicomFiles.Count, imageNodes.Count());
        }
Exemple #9
0
        private static void ReadMedia(string fileName)
        {
            var dicomDirectory = DicomDirectory.Open(fileName);

            foreach (var patientRecord in dicomDirectory.RootDirectoryRecordCollection)
            {
                Console.WriteLine(
                    "Patient: {0} ({1})",
                    patientRecord.Get <string>(DicomTag.PatientName),
                    patientRecord.Get <string>(DicomTag.PatientID));

                foreach (var studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                {
                    Console.WriteLine("\tStudy: {0}", studyRecord.Get <string>(DicomTag.StudyInstanceUID));

                    foreach (var seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                    {
                        Console.WriteLine("\t\tSeries: {0}", seriesRecord.Get <string>(DicomTag.SeriesInstanceUID));

                        foreach (var imageRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
                        {
                            Console.WriteLine(
                                "\t\t\tImage: {0} [{1}]",
                                imageRecord.Get <string>(DicomTag.ReferencedSOPInstanceUIDInFile),
                                imageRecord.Get <string>(Dicom.DicomTag.ReferencedFileID));
                        }
                    }
                }
            }
        }
Exemple #10
0
        private static DicomDirectory FinalizeDicomDirectoryLoad(
            DicomDirectory df,
            DicomFileReader reader,
            DicomDirectoryReaderObserver dirObserver,
            DicomReaderResult result)
        {
            if (result == DicomReaderResult.Processing)
            {
                throw new DicomFileException(df, "Invalid read return state: {state}", result);
            }
            if (result == DicomReaderResult.Error)
            {
                return(null);
            }
            df.IsPartial = result == DicomReaderResult.Stopped || result == DicomReaderResult.Suspended;

            df.Format = reader.FileFormat;

            df.Dataset.InternalTransferSyntax = reader.Syntax;

            df._directoryRecordSequence = df.Dataset.Get <DicomSequence>(DicomTag.DirectoryRecordSequence);
            df.RootDirectoryRecord      = dirObserver.BuildDirectoryRecords();

            return(df);
        }
        public void AddFile_AnonymizedSeries_AllFilesAddedToDifferentPatientNodes()
        {
            var dicomFiles = GetDicomFilesFromZip(@".\Test Data\abd1.zip");

            // Anonymize all files
            var patname    = "Pat^Name";
            var patname2   = "Pat^^Name^^";
            var patname3   = "PAT Name";
            var patname4   = "Name^Pat";
            var anonymizer = new DicomAnonymizer();

            foreach (var dicomFile in dicomFiles)
            {
                anonymizer.AnonymizeInPlace(dicomFile);
                dicomFile.Dataset.AddOrUpdate(DicomTag.PatientName, patname);
            }
            // the name of the first image is slightly different
            dicomFiles.First().Dataset.AddOrUpdate(DicomTag.PatientName, patname2);
            dicomFiles.ElementAt(1).Dataset.AddOrUpdate(DicomTag.PatientName, patname3);
            dicomFiles.ElementAt(2).Dataset.AddOrUpdate(DicomTag.PatientName, patname4);

            // Create DICOM directory
            var dicomDir = new DicomDirectory();

            foreach (var dicomFile in dicomFiles)
            {
                var entry = dicomDir.AddFile(dicomFile);
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID), entry.InstanceRecord.GetSingleValue <string>(DicomTag.ReferencedSOPInstanceUIDInFile));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID), entry.SeriesRecord.GetSingleValue <string>(DicomTag.SeriesInstanceUID));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID), entry.StudyRecord.GetSingleValue <string>(DicomTag.StudyInstanceUID));
            }

            // there shall be only one patient record
            Assert.Equal(4, dicomDir.RootDirectoryRecordCollection.Count());
        }
        public async Task OpenAsync_DicomDirFile_Succeeds()
        {
            var dir = await DicomDirectory.OpenAsync(@".\Test Data\DICOMDIR");

            var expected = DicomUID.MediaStorageDirectoryStorage.UID;
            var actual   = dir.FileMetaInfo.MediaStorageSOPClassUID.UID;
        }
        public void Open_DicomDirFile_Succeeds()
        {
            var dir = DicomDirectory.Open(@".\Test Data\DICOMDIR");

            var expected = DicomUID.MediaStorageDirectoryStorage.UID;
            var actual   = dir.FileMetaInfo.MediaStorageSOPClassUID.UID;
        }
 public static IAsyncResult BeginOpen(
     string fileName,
     Encoding fallbackEncoding,
     AsyncCallback callback,
     object state)
 {
     return(AsyncFactory.ToBegin(DicomDirectory.OpenAsync(fileName, fallbackEncoding), callback, state));
 }
Exemple #15
0
        public void Open_MediaStorageSOPInstanceUID_ShouldBeConsistent()
        {
            var dir      = DicomDirectory.Open(@".\Test Data\DICOMDIR");
            var expected = dir.FileMetaInfo.Get <DicomUID>(DicomTag.MediaStorageSOPInstanceUID).UID;
            var actual   = dir.MediaStorageSOPInstanceUID.UID;

            Assert.Equal(expected, actual);
        }
Exemple #16
0
        /// <summary>
        /// Asynchronously read DICOM Directory.
        /// </summary>
        /// <param name="fileName">File name.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomDirectory"/> instance.</returns>
        public static new async Task <DicomDirectory> OpenAsync(string fileName, Encoding fallbackEncoding, Func <ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException("fallbackEncoding");
            }
            var df = new DicomDirectory();

            // reset datasets
            df.FileMetaInfo.Clear();
            df.Dataset.Clear();

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

                using (var source = new FileByteSource(df.File))
                {
                    var reader = new DicomFileReader();

                    var datasetObserver = new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding);
                    var dirObserver     = new DicomDirectoryReaderObserver(df.Dataset);

                    var result =
                        await
                        reader.ReadAsync(
                            source,
                            new DicomDatasetReaderObserver(df.FileMetaInfo),
                            new DicomReaderMultiObserver(datasetObserver, dirObserver),
                            stop).ConfigureAwait(false);

                    if (result == DicomReaderResult.Processing)
                    {
                        throw new DicomFileException(df, "Invalid read return state: {state}", result);
                    }
                    if (result == DicomReaderResult.Error)
                    {
                        return(null);
                    }
                    df.IsPartial = result == DicomReaderResult.Stopped || result == DicomReaderResult.Suspended;

                    df.Format = reader.FileFormat;

                    df.Dataset.InternalTransferSyntax = reader.Syntax;

                    df._directoryRecordSequence = df.Dataset.Get <DicomSequence>(DicomTag.DirectoryRecordSequence);
                    df.RootDirectoryRecord      = dirObserver.BuildDirectoryRecords();

                    return(df);
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
        public async Task OpenAsync_DicomDirStream_Succeeds()
        {
            using (var stream = File.OpenRead(@".\Test Data\DICOMDIR"))
            {
                DicomDirectory dir = await DicomDirectory.OpenAsync(stream);

                var expected = DicomUID.MediaStorageDirectoryStorage.UID;
                var actual   = dir.FileMetaInfo.MediaStorageSOPClassUID.UID;
            }
        }
Exemple #18
0
        public void Open_DicomDirStream_Succeeds()
        {
            using (var stream = File.OpenRead(@".\Test Data\DICOMDIR"))
            {
                DicomDirectory dir = DicomDirectory.Open(stream);

                var expected = DicomUID.MediaStorageDirectoryStorage.UID;
                var actual   = dir.FileMetaInfo.MediaStorageSOPClassUID.UID;
                Assert.Equal(expected, actual);
            }
        }
        public void AddFile_LongFilename()
        {
            string filename  = "TestPattern_Palette_16.dcm";
            var    dicomFile = DicomFile.Open(@".\Test Data\" + filename);

            var dicomDir = new DicomDirectory();

            Assert.Throws <DicomValidationException>(()
                                                     => dicomDir.AddFile(dicomFile, filename));

            dicomDir.AutoValidate = false;
            dicomDir.AddFile(dicomFile, filename);
            Assert.Single(dicomDir.RootDirectoryRecordCollection);
        }
Exemple #20
0
		private static void WriteMedia(string path) {
			var dicomDirPath = Path.Combine(path, "DICOMDIR");

			var dirInfo = new DirectoryInfo(path);

			var dicomDir = new DicomDirectory();
			foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories)) {
				var dicomFile = Dicom.DicomFile.Open(file.FullName);

				dicomDir.AddFile(dicomFile, String.Format(@"000001\{0}", file.Name));
			}

			dicomDir.Save(dicomDirPath);
		}
        public void AddFile_LongFilename_WithGlobalValidationSupression()
        {
            string filename  = "TestPattern_Palette_16.dcm";
            var    dicomFile = DicomFile.Open(@".\Test Data\" + filename);

            DicomValidation.AutoValidation = false;

            var dicomDir = new DicomDirectory();

            Assert.Null(Record.Exception(()
                                         => dicomDir.AddFile(dicomFile, filename)));
            Assert.Single(dicomDir.RootDirectoryRecordCollection);

            DicomValidation.AutoValidation = true;
        }
Exemple #22
0
        private static void WriteMedia(string path)
        {
            var dicomDirPath = Path.Combine(path, "DICOMDIR");

            var dirInfo = new DirectoryInfo(path);

            var dicomDir = new DicomDirectory();

            foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var dicomFile = Dicom.DicomFile.Open(file.FullName);

                dicomDir.AddFile(dicomFile, String.Format(@"000001\{0}", file.Name));
            }

            dicomDir.Save(dicomDirPath);
        }
        public void AddFile_InvalidUIDInExistingFileShouldNotThrow()
        {
            // first create a file with invalid UIDs
            string filename  = "TestPattern_Palette_16.dcm";
            var    dicomFile = DicomFile.Open(@".\Test Data\" + filename);

            var invalidDs = dicomFile.Dataset.NotValidated();

            invalidDs.AddOrUpdate(DicomTag.SOPInstanceUID, "1.2.4.100000.94849.4239.32.00121");
            invalidDs.AddOrUpdate(DicomTag.SeriesInstanceUID, "1.2.4.100000.94849.4239.32.00122");
            invalidDs.AddOrUpdate(DicomTag.StudyInstanceUID, "1.2.4.100000.94849.4239.32.00123");

            var invalidFile = new DicomFile(invalidDs);

            var ex = Record.Exception(() =>
            {
                var dicomDir = new DicomDirectory();
                dicomDir.AddFile(invalidFile, "FILE1");
            });

            Assert.Null(ex);
        }
Exemple #24
0
        private static void WriteMedia(string path)
        {
            var dirInfo = new DirectoryInfo(path);
            var dicomDir = new DicomDirectory(false);
            foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                if (!file.FullName.StartsWith(dirInfo.FullName))
                    throw new ArgumentException("file");
                if (file.Name == "DICOMDIR")
                    continue;
                try
                {
                    dicomDir.AddFile(DicomFile.Open(file.FullName), file.FullName.Substring(dirInfo.FullName.Length).TrimStart(Path.DirectorySeparatorChar));
                }
                catch
                {

                }
            }
            if (dicomDir.RootDirectoryRecord != null)
                dicomDir.Save(Path.Combine(path, "DICOMDIR"));
        }
        public string DownloadDicomFile(int[] frameIdArray, string guid)
        {
            int count = (from dfr in ObjectContext.DicomFrame where frameIdArray.Contains(dfr.FrameId) select dfr.FileId).Distinct().Count();

            if (count == 1) // DICOM File
            {
                CreateDicomFile(frameIdArray, guid, guid);

                return guid + ".dcm";
            }
            else // DICOMDIR File
            {
                int[] fileIdArray = (from dfr in ObjectContext.DicomFrame where frameIdArray.Contains(dfr.FrameId) select dfr.FileId).Distinct().ToArray();

                foreach (var fileId in fileIdArray)
                {
                    int[] frameIdForFileArray = (from dfr in ObjectContext.DicomFrame where dfr.FileId == fileId && frameIdArray.Contains(dfr.FrameId) select dfr.FrameId).ToArray();
                    string fileName = (from df in ObjectContext.DicomFile where df.FileId == fileId select df.FileId).First().ToString(CultureInfo.InvariantCulture);
                    CreateDicomFile(frameIdForFileArray, guid, fileName);
                }

                string dirPath = HttpRuntime.AppDomainAppPath + @"\temp\" + guid;

                string dicomDirPath = Path.Combine(dirPath, "DICOMDIR");
                var dirInfo = new DirectoryInfo(dirPath);
                var dicomDir = new DicomDirectory();
                foreach (var file in dirInfo.GetFiles("*.dcm"))
                {
                    var dicomFile = Dicom.DicomFile.Open(file.FullName);
                    dicomDir.AddFile(dicomFile, String.Format(@".\{0}", file.Name));
                }
                dicomDir.Save(dicomDirPath);

                var files = dirInfo.GetFiles();
                var binaryFormatter = new BinaryFormatter();
                var fileStream = new FileStream(dirPath + @"\" + guid + ".dcmdir", FileMode.Create, FileAccess.Write, FileShare.None);
                foreach (var file in files)
                {
                    var dicomSerializableFile = new DicomSerializableFile(file.Name, File.ReadAllBytes(file.FullName));
                    binaryFormatter.Serialize(fileStream, dicomSerializableFile);
                }
                fileStream.Close();

                return guid + ".dcmdir";
            }
        }
        /// <summary>
        /// Asynchronously read DICOM Directory.
        /// </summary>
        /// <param name="fileName">File name.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomDirectory"/> instance.</returns>
        public static new async Task<DicomDirectory> OpenAsync(string fileName, Encoding fallbackEncoding, Func<ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException("fallbackEncoding");
            }
            var df = new DicomDirectory();

            // reset datasets
            df.FileMetaInfo.Clear();
            df.Dataset.Clear();

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

                using (var source = new FileByteSource(df.File))
                {
                    var reader = new DicomFileReader();

                    var datasetObserver = new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding);
                    var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

                    var result =
                        await
                        reader.ReadAsync(
                            source,
                            new DicomDatasetReaderObserver(df.FileMetaInfo),
                            new DicomReaderMultiObserver(datasetObserver, dirObserver),
                            stop).ConfigureAwait(false);

                    if (result == DicomReaderResult.Processing)
                    {
                        throw new DicomFileException(df, "Invalid read return state: {state}", result);
                    }
                    if (result == DicomReaderResult.Error)
                    {
                        return null;
                    }
                    df.IsPartial = result == DicomReaderResult.Stopped || result == DicomReaderResult.Suspended;

                    df.Format = reader.FileFormat;

                    df.Dataset.InternalTransferSyntax = reader.Syntax;

                    df._directoryRecordSequence = df.Dataset.Get<DicomSequence>(DicomTag.DirectoryRecordSequence);
                    df.RootDirectoryRecord = dirObserver.BuildDirectoryRecords();

                    return df;
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Exemple #27
0
		public new static IAsyncResult BeginOpen(string fileName, AsyncCallback callback, object state) {
			var df = new DicomDirectory();

			// reset datasets
			df.FileMetaInfo.Clear();
			df.Dataset.Clear();

			df.File = new FileReference(fileName);

			FileByteSource source = new FileByteSource(df.File);

			EventAsyncResult result = new EventAsyncResult(callback, state);

			DicomFileReader reader = new DicomFileReader();

			var datasetObserver = new DicomDatasetReaderObserver(df.Dataset);
			var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

			reader.BeginRead(source,
				new DicomDatasetReaderObserver(df.FileMetaInfo),
				new DicomReaderMultiObserver(datasetObserver, dirObserver),
				OnReadComplete, new Tuple<DicomFileReader, DicomDirectory, DicomDirectoryReaderObserver, EventAsyncResult>(reader, df, dirObserver, result));

			return result;
		}
Exemple #28
0
		public new static DicomDirectory Open(string fileName) {
			var df = new DicomDirectory();

			// reset datasets
			df.FileMetaInfo.Clear();
			df.Dataset.Clear();

			try {
				df.File = new FileReference(fileName);

				using (var source = new FileByteSource(df.File)) {
					DicomFileReader reader = new DicomFileReader();

					var datasetObserver = new DicomDatasetReaderObserver(df.Dataset);
					var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

					reader.Read(source,
						new DicomDatasetReaderObserver(df.FileMetaInfo),
						new DicomReaderMultiObserver(datasetObserver, dirObserver));

					df.Format = reader.FileFormat;

					df.Dataset.InternalTransferSyntax = reader.Syntax;

					df._directoryRecordSequence = df.Dataset.Get<DicomSequence>(DicomTag.DirectoryRecordSequence);
					df.RootDirectoryRecord = dirObserver.BuildDirectoryRecords();

					return df;
				}
			} catch (Exception e) {
				throw new DicomFileException(df, e.Message, e);
			}
		}
Exemple #29
0
        /// <summary>
        /// Read DICOM Directory.
        /// </summary>
        /// <param name="fileName">File name.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns><see cref="DicomDirectory"/> instance.</returns>
        public static new DicomDirectory Open(string fileName, Encoding fallbackEncoding, Func<ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException(nameof(fallbackEncoding));
            }
            var df = new DicomDirectory();

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

                using (var source = new FileByteSource(df.File))
                {
                    var reader = new DicomFileReader();
                    var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

                    var result = reader.Read(
                        source,
                        new DicomDatasetReaderObserver(df.FileMetaInfo),
                        new DicomReaderMultiObserver(
                            new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding),
                            dirObserver),
                        stop);

                    return FinalizeDicomDirectoryLoad(df, reader, dirObserver, result);
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Exemple #30
0
        /// <summary>
        /// Asynchronously read DICOM Directory from stream.
        /// </summary>
        /// <param name="stream">Stream to read.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomDirectory"/> instance.</returns>
        public static new async Task<DicomDirectory> OpenAsync(Stream stream, Encoding fallbackEncoding, Func<ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException(nameof(fallbackEncoding));
            }
            var df = new DicomDirectory();

            try
            {
                var source = new StreamByteSource(stream);

                var reader = new DicomFileReader();
                var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

                var result =
                    await
                    reader.ReadAsync(
                        source,
                        new DicomDatasetReaderObserver(df.FileMetaInfo),
                        new DicomReaderMultiObserver(
                        new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding),
                        dirObserver),
                        stop).ConfigureAwait(false);

                return FinalizeDicomDirectoryLoad(df, reader, dirObserver, result);
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Exemple #31
0
        private static DicomDirectory FinalizeDicomDirectoryLoad(
            DicomDirectory df,
            DicomFileReader reader,
            DicomDirectoryReaderObserver dirObserver,
            DicomReaderResult result)
        {
            if (result == DicomReaderResult.Processing)
            {
                throw new DicomFileException(df, "Invalid read return state: {state}", result);
            }
            if (result == DicomReaderResult.Error)
            {
                return null;
            }
            df.IsPartial = result == DicomReaderResult.Stopped || result == DicomReaderResult.Suspended;

            df.Format = reader.FileFormat;

            df.Dataset.InternalTransferSyntax = reader.Syntax;

            df._directoryRecordSequence = df.Dataset.Get<DicomSequence>(DicomTag.DirectoryRecordSequence);
            df.RootDirectoryRecord = dirObserver.BuildDirectoryRecords();

            return df;
        }