Esempio n. 1
0
        public void TestBaseInstanceExclusionAfterSerialization()
        {
            foreach (string[] testSet in _overlappingTagTestSets)
            {
                List <DicomFile> images = SetupImages(testSet.Length);
                SetTestAttribute(images, testSet);

                StudyXml xml = new StudyXml();

                StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
                xml = new StudyXml();

                xml.AddFile(images[0]);
                xml.AddFile(images[1]);

                XmlDocument doc = xml.GetMemento(settings);

                settings.MaxTagLength = 1024;

                xml.AddFile(images[2]);                 //re-add
                doc = xml.GetMemento(settings);

                xml = new StudyXml();
                xml.SetMemento(doc);
                doc = xml.GetMemento(settings);
                xml.AddFile(images[2]);                 //re-add
                doc = xml.GetMemento(settings);

                xml = new StudyXml();
                xml.SetMemento(doc);
                xml.AddFile(images[1]);                 //re-add
                doc = xml.GetMemento(settings);
            }
        }
Esempio n. 2
0
        private void ButtonLoadFile_Click(object sender, EventArgs e)
        {
            openFileDialog.DefaultExt = "dcm";
            openFileDialog.ShowDialog();

            DicomFile dicomFile = new DicomFile(openFileDialog.FileName);

            dicomFile.Load(DicomReadOptions.Default);

            _theStream.AddFile(dicomFile);
        }
Esempio n. 3
0
        public void TestMultipleSerializations()
        {
            List <DicomFile> images = SetupImages(4);

            XmlDocument doc = null;
            StudyXml    xml;
            int         i;

            for (i = 0; i < images.Count; ++i)
            {
                xml = new StudyXml();

                if (doc != null)
                {
                    xml.SetMemento(doc);
                }

                xml.AddFile(images[i]);
                StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
                doc = xml.GetMemento(settings);
            }

            xml = new StudyXml();
            xml.SetMemento(doc);
            List <InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);

            i = 0;
            foreach (DicomFile file in images)
            {
                ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
            }
        }
Esempio n. 4
0
        public void TestExcludePrivateTags()
        {
            List <DicomFile> images     = SetupImages(2);
            StudyXml         xml        = new StudyXml();
            DicomTag         privateTag =
                new DicomTag(0x00210010, "Private Tag", "Private Tag", DicomVr.LTvr, false, 1, uint.MaxValue, false);

            foreach (DicomFile file in images)
            {
                file.DataSet[privateTag].SetStringValue("My Private Tag");
                xml.AddFile(file);
            }

            StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
            XmlDocument            doc      = xml.GetMemento(settings);

            List <InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);

            foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
            {
                Assert.IsFalse(dataSet.Contains(privateTag));
            }

            xml = new StudyXml();
            xml.SetMemento(doc);

            dataSets = GetInstanceXmlDataSets(xml);
            foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
            {
                Assert.IsFalse(dataSet.Contains(privateTag));
            }
        }
Esempio n. 5
0
        public void TestTransferSyntax()
        {
            List <DicomFile> images = SetupImages(4);

            string seriesUid = images[0].DataSet[DicomTags.SeriesInstanceUid].ToString();

            images[0].TransferSyntax = TransferSyntax.Jpeg2000ImageCompression;
            images[1].TransferSyntax = TransferSyntax.ExplicitVrLittleEndian;
            images[2].TransferSyntax = TransferSyntax.ExplicitVrBigEndian;
            images[3].TransferSyntax = TransferSyntax.Jpeg2000ImageCompressionLosslessOnly;

            StudyXml xml = new StudyXml();

            foreach (DicomFile file in images)
            {
                xml.AddFile(file);
            }

            XmlDocument doc = xml.GetMemento(new StudyXmlOutputSettings());

            Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompression);
            Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrLittleEndian);
            Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrBigEndian);
            Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompressionLosslessOnly);

            xml = new StudyXml();
            xml.SetMemento(doc);

            Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompression);
            Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrLittleEndian);
            Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrBigEndian);
            Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompressionLosslessOnly);
        }
Esempio n. 6
0
        public void TestExclusionsImmediatelyAfterSerialization()
        {
            //NOTE: previously, this test failed because the excluded tags were not added to the
            //xml collection until after it had been deserialized at least once from the xml.
            foreach (string[] testSet in _overlappingTagTestSets)
            {
                List <DicomFile> images = SetupImages(testSet.Length);
                SetTestAttribute(images, testSet);

                StudyXml xml = new StudyXml();

                foreach (DicomFile file in images)
                {
                    xml.AddFile(file);
                }

                StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
                settings.MaxTagLength = 1024;
                XmlDocument doc = xml.GetMemento(settings);

                List <InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
                ValidateSimpleDataSets(testSet, dataSets, settings);

                //do a little extra validation, what the hay.
                xml = new StudyXml();
                xml.SetMemento(doc);

                dataSets = GetInstanceXmlDataSets(xml);
                ValidateSimpleDataSets(testSet, dataSets, settings);
            }
        }
Esempio n. 7
0
        protected override void OnExecute(CommandProcessor theProcessor)
        {
            FileSize = 0;
            var finfo = new FileInfo(_file.Filename);

            if (finfo.Exists)
            {
                FileSize = finfo.Length;
            }

            // Setup the insert parameters
            if (false == _stream.AddFile(_file, FileSize, _outputSettings))
            {
                Platform.Log(LogLevel.Error, "Unexpected error adding SOP to XML Study Descriptor for file {0}",
                             _file.Filename);
                throw new ApplicationException("Unexpected error adding SOP to XML Study Descriptor for SOP: " +
                                               _file.MediaStorageSopInstanceUid);
            }

            // Write it back out.  We flush it out with every added image so that if a failure happens,
            // we can recover properly.
            string streamFile =
                Path.Combine(_studyStorageLocation.GetStudyPath(), _studyStorageLocation.StudyInstanceUid + ".xml");
            string gzStreamFile = streamFile + ".gz";

            WriteStudyStream(streamFile, gzStreamFile, _stream);
        }
        protected override void OnExecute(CommandProcessor theProcessor)
        {
            long fileSize = 0;

            if (File.Exists(_file.Filename))
            {
                var finfo = new FileInfo(_file.Filename);
                fileSize = finfo.Length;
            }

            String seriesInstanceUid = _file.DataSet[DicomTags.SeriesInstanceUid].GetString(0, string.Empty);
            String sopInstanceUid    = _file.DataSet[DicomTags.SopInstanceUid].GetString(0, string.Empty);

            if (_studyXml.Contains(seriesInstanceUid, sopInstanceUid))
            {
                _duplicate = true;
            }

            // Setup the insert parameters
            if (false == _studyXml.AddFile(_file, fileSize, _settings))
            {
                Platform.Log(LogLevel.Error, "Unexpected error adding SOP to XML Study Descriptor for file {0}",
                             _file.Filename);
                throw new ApplicationException("Unexpected error adding SOP to XML Study Descriptor for SOP: " +
                                               _file.MediaStorageSopInstanceUid);
            }

            if (_writeFile)
            {
                // Write it back out.  We flush it out with every added image so that if a failure happens,
                // we can recover properly.
                bool fileCreated;
                _studyStorageLocation.SaveStudyXml(_studyXml, out fileCreated);
            }
        }
Esempio n. 9
0
        protected Study CreateTestStudy1()
        {
            var studyUid = "1.2.3";
            var sops = base.SetupMRSeries(4, 5, studyUid);
            var xml = new StudyXml(studyUid);

            var seriesUids = new Dictionary<string, string>();
            var seriesModalities = new Dictionary<string, string>();
            var modalities = new[] { "MR", "MR", "SC", "KO" };

            foreach (var sop in sops)
            {
                //Make the UIDs constant.
                var seriesUid = sop[DicomTags.SeriesInstanceUid].ToString();
                if (!seriesUids.ContainsKey(seriesUid))
                {
                    seriesModalities[seriesUid] = modalities[seriesUids.Count];
                    seriesUids[seriesUid] = string.Format("1.2.3.{0}", seriesUids.Count + 1);
                }

                var modality = seriesModalities[seriesUid];
                seriesUid = seriesUids[seriesUid];

                sop[DicomTags.SeriesInstanceUid].SetString(0, seriesUid);
                sop[DicomTags.Modality].SetString(0, modality);

                var file = new DicomFile("", new DicomAttributeCollection(), sop);
                xml.AddFile(file);
            }

            var study = new Study();
            study.Update(xml);
            return study;
        }
Esempio n. 10
0
		public void TestSopClass()
		{
			List<DicomFile> images = SetupImages(4);

			string seriesUid = images[0].DataSet[DicomTags.SeriesInstanceUid].ToString();

			images[0].MediaStorageSopClassUid = SopClass.EnhancedCtImageStorageUid;
			images[1].MediaStorageSopClassUid = SopClass.EnhancedMrImageStorageUid;
			images[2].MediaStorageSopClassUid = SopClass.EnhancedSrStorageUid;
			images[3].MediaStorageSopClassUid = SopClass.EnhancedXaImageStorageUid;
		
			StudyXml xml = new StudyXml();
			foreach (DicomFile file in images)
				xml.AddFile(file);
	
			XmlDocument doc = xml.GetMemento(new StudyXmlOutputSettings());

			Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedCtImageStorageUid);
			Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedMrImageStorageUid);
			Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedSrStorageUid);
			Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedXaImageStorageUid);

			xml = new StudyXml();
			xml.SetMemento(doc);

			Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedCtImageStorageUid);
			Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedMrImageStorageUid);
			Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedSrStorageUid);
			Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedXaImageStorageUid);
		}
Esempio n. 11
0
        protected Study CreateTestStudy1()
        {
            var studyUid = "1.2.3";
            var sops     = base.SetupMRSeries(4, 5, studyUid);
            var xml      = new StudyXml(studyUid);

            var seriesUids       = new Dictionary <string, string>();
            var seriesModalities = new Dictionary <string, string>();
            var modalities       = new[] { "MR", "MR", "SC", "KO" };

            foreach (var sop in sops)
            {
                //Make the UIDs constant.
                var seriesUid = sop[DicomTags.SeriesInstanceUid].ToString();
                if (!seriesUids.ContainsKey(seriesUid))
                {
                    seriesModalities[seriesUid] = modalities[seriesUids.Count];
                    seriesUids[seriesUid]       = string.Format("1.2.3.{0}", seriesUids.Count + 1);
                }

                var modality = seriesModalities[seriesUid];
                seriesUid = seriesUids[seriesUid];

                sop[DicomTags.SeriesInstanceUid].SetString(0, seriesUid);
                sop[DicomTags.Modality].SetString(0, modality);

                var file = new DicomFile("", new DicomAttributeCollection(), sop);
                xml.AddFile(file);
            }

            var study = new Study();

            study.Update(xml);
            return(study);
        }
Esempio n. 12
0
        public void TestSopClass()
        {
            List <DicomFile> images = SetupImages(4);

            string seriesUid = images[0].DataSet[DicomTags.SeriesInstanceUid].ToString();

            images[0].MediaStorageSopClassUid = SopClass.EnhancedCtImageStorageUid;
            images[1].MediaStorageSopClassUid = SopClass.EnhancedMrImageStorageUid;
            images[2].MediaStorageSopClassUid = SopClass.EnhancedSrStorageUid;
            images[3].MediaStorageSopClassUid = SopClass.EnhancedXaImageStorageUid;

            StudyXml xml = new StudyXml();

            foreach (DicomFile file in images)
            {
                xml.AddFile(file);
            }

            XmlDocument doc = xml.GetMemento(new StudyXmlOutputSettings());

            Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedCtImageStorageUid);
            Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedMrImageStorageUid);
            Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedSrStorageUid);
            Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedXaImageStorageUid);

            xml = new StudyXml();
            xml.SetMemento(doc);

            Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedCtImageStorageUid);
            Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedMrImageStorageUid);
            Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedSrStorageUid);
            Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].SopClass.Uid, SopClass.EnhancedXaImageStorageUid);
        }
        protected override void OnExecute(CommandProcessor theProcessor)
        {
            if (!File.Exists(_path))
            {
                Platform.Log(LogLevel.Error, "Unexpected error finding file to add to XML {0}", _path);
                throw new ApplicationException("Unexpected error finding file to add to XML {0}" + _path);
            }

            var  finfo    = new FileInfo(_path);
            long fileSize = finfo.Length;

            var dicomFile = new DicomFile(_path);

            dicomFile.Load(DicomReadOptions.StorePixelDataReferences | DicomReadOptions.Default);

            _sopInstanceUid    = dicomFile.DataSet[DicomTags.SopInstanceUid];
            _seriesInstanceUid = dicomFile.DataSet[DicomTags.SeriesInstanceUid];

            // Setup the insert parameters
            if (false == _stream.AddFile(dicomFile, fileSize))
            {
                Platform.Log(LogLevel.Error, "Unexpected error adding SOP to XML Study Descriptor for file {0}",
                             _path);
                throw new ApplicationException("Unexpected error adding SOP to XML Study Descriptor for SOP: " +
                                               dicomFile.MediaStorageSopInstanceUid);
            }
        }
Esempio n. 14
0
        protected override void OnExecute(CommandProcessor theProcessor)
        {
            // Setup the insert parameters
            string seriesInstanceUid = _file.DataSet[DicomTags.SeriesInstanceUid].GetString(0, string.Empty);
            string sopinstanceUid    = _file.MediaStorageSopInstanceUid;

            FileSize = 0;

            var finfo = new FileInfo(_file.Filename);

            if (finfo.Exists)
            {
                FileSize = finfo.Length;
            }

            // Save the collection for undo purposes
            SeriesXml seriesXml = _stream[seriesInstanceUid];

            if (seriesXml != null)
            {
                InstanceXml instanceXml = seriesXml[sopinstanceUid];
                if (instanceXml != null)
                {
                    _saveCollection = instanceXml.Collection;
                }
            }

            if (false == _stream.RemoveFile(_file))
            {
                Platform.Log(LogLevel.Warn, "SOP was unexpectedly not in XML Study Descriptor for file: {0}",
                             _file.Filename);
            }
            if (false == _stream.AddFile(_file, FileSize, _outputSettings))
            {
                Platform.Log(LogLevel.Error, "Unexpected error adding SOP to XML Study Descriptor for file {0}",
                             _file.Filename);
                throw new ApplicationException("Unexpected error adding SOP to XML Study Descriptor for SOP: " +
                                               _file.MediaStorageSopInstanceUid);
            }
            // Write it back out.  We flush it out with every added image so that if a failure happens,
            // we can recover properly.
            WriteStudyStream(
                Path.Combine(_studyStorageLocation.GetStudyPath(), _studyStorageLocation.StudyInstanceUid + ".xml"),
                Path.Combine(_studyStorageLocation.GetStudyPath(), _studyStorageLocation.StudyInstanceUid + ".xml.gz"),
                _stream);
        }
        protected override void OnUndo()
        {
            _studyXml.AddFile(_file);

            string streamFile   = _studyLocation.GetStudyXmlPath();
            string gzStreamFile = streamFile + ".gz";

            WriteStudyStream(streamFile, gzStreamFile, _studyXml);
        }
Esempio n. 16
0
        internal void Update(DicomFile file)
        {
            Initialize(file);

            LoadStudyXml(false);
            _studyXml.AddFile(file);

            //these have to be here, rather than in Initialize b/c they are
            // computed from the series, which are parsed from the xml.
            NumberOfStudyRelatedSeries    = _studyXml.NumberOfStudyRelatedSeries;
            NumberOfStudyRelatedInstances = _studyXml.NumberOfStudyRelatedInstances;
        }
Esempio n. 17
0
        public void TestExcludeBinaryTags()
        {
            List <DicomFile> images = SetupImages(3);

            images[2].DataSet[DicomTags.SpectroscopyData].Values = new float[6];

            StudyXml xml = new StudyXml();

            foreach (DicomFile file in images)
            {
                file.DataSet[DicomTags.RedPaletteColorLookupTableData].Values   = new byte[256];
                file.DataSet[DicomTags.GreenPaletteColorLookupTableData].Values = new byte[256];
                file.DataSet[DicomTags.BluePaletteColorLookupTableData].Values  = new byte[256];
                xml.AddFile(file);
            }

            StudyXmlOutputSettings settings = new StudyXmlOutputSettings();

            settings.MaxTagLength = 100;
            XmlDocument doc = xml.GetMemento(settings);

            //SaveStudyXml(doc, @"C:\stewart\testxml.xml");
            List <InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);

            foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
            {
                Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.RedPaletteColorLookupTableData));
                Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.GreenPaletteColorLookupTableData));
                Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.BluePaletteColorLookupTableData));
            }

            //This attribute has a short value, so it should not be excluded.
            Assert.IsFalse(dataSets[2].IsTagExcluded(DicomTags.SpectroscopyData));

            xml = new StudyXml();
            xml.SetMemento(doc);

            dataSets = GetInstanceXmlDataSets(xml);
            foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
            {
                Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.RedPaletteColorLookupTableData));
                Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.GreenPaletteColorLookupTableData));
                Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.BluePaletteColorLookupTableData));
            }

            //This attribute has a short value, so it should not be excluded.
            Assert.IsFalse(dataSets[2].IsTagExcluded(DicomTags.SpectroscopyData));
        }
Esempio n. 18
0
        public void Create()
        {
            SelectFolderDialogCreationArgs args = new SelectFolderDialogCreationArgs();

            args.Path = _lastFolder ?? Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            FileDialogResult result = base.Context.DesktopWindow.ShowSelectFolderDialogBox(args);

            if (result.Action == DialogBoxAction.Ok)
            {
                _lastFolder = result.FileName;

                StudyLoaderExtensionPoint xp = new StudyLoaderExtensionPoint();
                IStudyLoader loader          = (IStudyLoader)CollectionUtils.SelectFirst(xp.CreateExtensions(),
                                                                                         delegate(object extension) { return(((IStudyLoader)extension).Name == "DICOM_LOCAL"); });

                var selected = base.Context.SelectedStudy;

                loader.Start(new StudyLoaderArgs(selected.StudyInstanceUid, selected.Server, StudyLoaderOptions.Default));
                StudyXml xml = new StudyXml();
                Sop      sop;

                while (null != (sop = loader.LoadNextSop()))
                {
                    xml.AddFile(((ILocalSopDataSource)sop.DataSource).File);
                }

                StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
                settings.IncludePrivateValues  = StudyXmlTagInclusion.IgnoreTag;
                settings.IncludeUnknownTags    = StudyXmlTagInclusion.IgnoreTag;
                settings.MaxTagLength          = 100 * 1024;
                settings.IncludeSourceFileName = true;

                XmlDocument doc      = xml.GetMemento(settings);
                string      fileName = System.IO.Path.Combine(result.FileName, "studyxml.xml");

                XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
                writer.Formatting  = Formatting.Indented;
                writer.Indentation = 5;

                doc.Save(writer);
            }
        }
Esempio n. 19
0
		public void Create()
		{
			
			SelectFolderDialogCreationArgs args = new SelectFolderDialogCreationArgs();
			args.Path = _lastFolder ?? Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

			FileDialogResult result = base.Context.DesktopWindow.ShowSelectFolderDialogBox(args);
			if (result.Action == DialogBoxAction.Ok)
			{
				_lastFolder = result.FileName;

				StudyLoaderExtensionPoint xp = new StudyLoaderExtensionPoint();
				IStudyLoader loader = (IStudyLoader)CollectionUtils.SelectFirst(xp.CreateExtensions(),
					delegate(object extension) { return ((IStudyLoader) extension).Name == "DICOM_LOCAL";});

				var selected = base.Context.SelectedStudy;

				loader.Start(new StudyLoaderArgs(selected.StudyInstanceUid, selected.Server, null));
				StudyXml xml = new StudyXml();
				Sop sop;
				
				while (null != (sop = loader.LoadNextSop()))
				{
					xml.AddFile(((ILocalSopDataSource) sop.DataSource).File);
				}

				StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
				settings.IncludePrivateValues = StudyXmlTagInclusion.IgnoreTag;
				settings.IncludeUnknownTags = StudyXmlTagInclusion.IgnoreTag;
				settings.MaxTagLength = 100 * 1024;
				settings.IncludeSourceFileName = true;

				XmlDocument doc = xml.GetMemento(settings);
				string fileName = System.IO.Path.Combine(result.FileName, "studyxml.xml");

				XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
				writer.Formatting = Formatting.Indented;
				writer.Indentation = 5;
				
				doc.Save(writer);
			}
		}
        private InstanceXml GetInstanceXml(StudyXmlOutputSettings outputSettings, out DicomFile real)
        {
            var xml = new StudyXml();

            real = new DicomFile();
            SetupMR(real.DataSet);
            real.MediaStorageSopClassUid = real.DataSet[DicomTags.SopClassUid].ToString();
            real.MetaInfo[DicomTags.SopClassUid].SetString(0, real.DataSet[DicomTags.SopClassUid].ToString());

            var bytes = new Byte[2048];

            real.DataSet[DicomTags.RedPaletteColorLookupTableData].Values = bytes;

            var privateTag = new DicomTag(0x00111301, "Private Tag", "PrivateTag", DicomVr.CSvr, false, 1, 1, false);

            real.DataSet[privateTag].SetString(0, "Private");

            var sequences = (DicomSequenceItem[])real.DataSet[DicomTags.RequestAttributesSequence].Values;
            var firstItem = sequences.First();

            firstItem[DicomTags.RedPaletteColorLookupTableData].Values = bytes;

            var attr         = real.DataSet[DicomTags.ReferencedStudySequence];
            var sequenceItem = new DicomSequenceItem();

            attr.AddSequenceItem(sequenceItem);
            sequenceItem[privateTag].SetString(0, "Private");

            xml.AddFile(real);

            var memento = xml.GetMemento(outputSettings ?? new StudyXmlOutputSettings
            {
                IncludeLargeTags     = StudyXmlTagInclusion.IncludeTagExclusion,
                IncludePrivateValues = StudyXmlTagInclusion.IgnoreTag,
                MaxTagLength         = 1024
            });

            xml = new StudyXml();
            xml.SetMemento(memento);
            return(xml.First().First());
        }
Esempio n. 21
0
        private static List <InstanceXmlDicomAttributeCollection> GetInstanceXmlDataSets(IEnumerable <DicomFile> images, out StudyXml newStudyXml, StudyXmlOutputSettings settings)
        {
            StudyXml xml = new StudyXml();

            foreach (DicomFile image in images)
            {
                xml.AddFile(image);
            }

            XmlDocument doc = xml.GetMemento(settings);

            //SaveStudyXml(doc, @"c:\stewart\LastStudyXml.xml");

            newStudyXml = new StudyXml();
            newStudyXml.SetMemento(doc);

            doc = newStudyXml.GetMemento(settings);
            //SaveStudyXml(doc, @"c:\stewart\LastStudyXml2.xml");

            return(GetInstanceXmlDataSets(newStudyXml));
        }
Esempio n. 22
0
        public void CreationTest()
        {
            IList <DicomAttributeCollection> instanceList;

            string studyInstanceUid = DicomUid.GenerateUid().UID;

            instanceList = SetupMRSeries(4, 10, studyInstanceUid);



            StudyXml studyXml = new StudyXml(studyInstanceUid);

            string studyXmlFilename = Path.GetTempFileName();

            foreach (DicomAttributeCollection instanceCollection in instanceList)
            {
                instanceCollection[DicomTags.PixelData] = null;


                DicomFile theFile = new DicomFile("test", new DicomAttributeCollection(), instanceCollection);
                SetupMetaInfo(theFile);

                studyXml.AddFile(theFile);

                WriteStudyStream(studyXmlFilename, studyXml);
            }

            StudyXml newXml = LoadStudyStream(studyXmlFilename);

            if (!Compare(newXml, instanceList))
            {
                Assert.Fail("Comparison of StudyXML failed against base loaded from disk");
            }

            if (!Compare(studyXml, instanceList))
            {
                Assert.Fail("Comparison of StudyXML failed against base in memory");
            }
        }
        private InstanceXml GetInstanceXml(StudyXmlOutputSettings outputSettings, out DicomFile real)
        {
            var xml = new StudyXml();
            real = new DicomFile();
            SetupMR(real.DataSet);
            real.MediaStorageSopClassUid = real.DataSet[DicomTags.SopClassUid].ToString();
            real.MetaInfo[DicomTags.SopClassUid].SetString(0, real.DataSet[DicomTags.SopClassUid].ToString());
            
            var bytes = new Byte[2048];
            real.DataSet[DicomTags.RedPaletteColorLookupTableData].Values = bytes;

            var privateTag = new DicomTag(0x00111301, "Private Tag", "PrivateTag", DicomVr.CSvr, false, 1, 1, false);
            real.DataSet[privateTag].SetString(0, "Private");

            var sequences = (DicomSequenceItem[])real.DataSet[DicomTags.RequestAttributesSequence].Values;
            var firstItem = sequences.First();
            firstItem[DicomTags.RedPaletteColorLookupTableData].Values = bytes;

            var attr = real.DataSet[DicomTags.ReferencedStudySequence];
            var sequenceItem = new DicomSequenceItem();
            attr.AddSequenceItem(sequenceItem);
            sequenceItem[privateTag].SetString(0, "Private");

            xml.AddFile(real);
            
            var memento = xml.GetMemento(outputSettings ?? new StudyXmlOutputSettings
            {
                IncludeLargeTags = StudyXmlTagInclusion.IncludeTagExclusion,
                IncludePrivateValues = StudyXmlTagInclusion.IgnoreTag,
                MaxTagLength = 1024
            });

            xml = new StudyXml();
            xml.SetMemento(memento);
            return xml.First().First();
        }
Esempio n. 24
0
        public void TestEqualAfterSerialization()
        {
            foreach (string[] testSet in _overlappingTagTestSets)
            {
                List <DicomFile> images = SetupImages(testSet.Length);
                SetTestAttribute(images, testSet);

                StudyXml xml = new StudyXml();

                foreach (DicomFile file in images)
                {
                    xml.AddFile(file);
                }

                StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
                settings.MaxTagLength = 1024;
                XmlDocument doc = xml.GetMemento(settings);

                List <InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
                int i = 0;
                foreach (DicomFile file in images)
                {
                    ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
                }

                xml = new StudyXml();
                xml.SetMemento(doc);

                dataSets = GetInstanceXmlDataSets(xml);
                i        = 0;
                foreach (DicomFile file in images)
                {
                    ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
                }
            }
        }
Esempio n. 25
0
		private static List<InstanceXmlDicomAttributeCollection> GetInstanceXmlDataSets(IEnumerable<DicomFile> images, out StudyXml newStudyXml, StudyXmlOutputSettings settings)
		{
			StudyXml xml = new StudyXml();
			foreach (DicomFile image in images)
				xml.AddFile(image);

			XmlDocument doc = xml.GetMemento(settings);
			//SaveStudyXml(doc, @"c:\stewart\LastStudyXml.xml");

			newStudyXml = new StudyXml();
			newStudyXml.SetMemento(doc);

			doc = newStudyXml.GetMemento(settings);
			//SaveStudyXml(doc, @"c:\stewart\LastStudyXml2.xml");

			return GetInstanceXmlDataSets(newStudyXml);
		}
Esempio n. 26
0
		public void TestBaseInstanceExclusionAfterSerialization()
		{
			foreach (string[] testSet in _overlappingTagTestSets)
			{
				List<DicomFile> images = SetupImages(testSet.Length);
				SetTestAttribute(images, testSet);

				StudyXml xml = new StudyXml();

				StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
				xml = new StudyXml();

				xml.AddFile(images[0]);
				xml.AddFile(images[1]);

				XmlDocument doc = xml.GetMemento(settings);

				settings.MaxTagLength = 1024;

				xml.AddFile(images[2]); //re-add
				doc = xml.GetMemento(settings);

				xml = new StudyXml();
				xml.SetMemento(doc);
				doc = xml.GetMemento(settings);
				xml.AddFile(images[2]); //re-add
				doc = xml.GetMemento(settings);

				xml = new StudyXml();
				xml.SetMemento(doc);
				xml.AddFile(images[1]); //re-add
				doc = xml.GetMemento(settings);
			}
		}
Esempio n. 27
0
        public void TestBaseInstanceTagsPastEnd()
        {
            //NOTE: previously, this test failed because, during xml serialization, only the
            //instance's own attributes were iterated over; if there were tags in the base instance
            //that went past the end of the individual instances, no 'EmptyAttributes' got added
            //to the xml and there would be extra attributes in the instances on deserialization.
            List <DicomFile> images    = SetupImages(2);
            DicomFile        smallFile = new DicomFile(null);

            images.Add(smallFile);
            base.SetupMetaInfo(smallFile);

            DicomAttributeCollection theSet = smallFile.DataSet;

            theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
            theSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\M\\FFE");
            theSet[DicomTags.InstanceCreationDate].SetStringValue("20070618");
            theSet[DicomTags.InstanceCreationTime].SetStringValue("133600");
            theSet[DicomTags.SopClassUid].SetStringValue(SopClass.MrImageStorageUid);
            theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
            theSet[DicomTags.StudyDate].SetStringValue("20070618");
            theSet[DicomTags.StudyTime].SetStringValue("133600");
            theSet[DicomTags.SeriesDate].SetStringValue("20070618");
            theSet[DicomTags.SeriesTime].SetStringValue("133700");
            theSet[DicomTags.AccessionNumber].SetStringValue("A1234");
            theSet[DicomTags.Modality].SetStringValue("MR");
            theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
            theSet[DicomTags.ManufacturersModelName].SetNullValue();
            theSet[DicomTags.InstitutionName].SetStringValue("Mount Sinai Hospital");
            theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
            theSet[DicomTags.StudyDescription].SetStringValue("HEART");
            theSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");

            theSet[DicomTags.StudyInstanceUid].SetStringValue(images[0].DataSet[DicomTags.StudyInstanceUid].ToString());
            theSet[DicomTags.SeriesInstanceUid].SetStringValue(images[0].DataSet[DicomTags.SeriesInstanceUid].ToString());
            theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().ToString());

            StudyXml xml = new StudyXml();

            foreach (DicomFile file in images)
            {
                xml.AddFile(file);
            }

            StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
            XmlDocument            doc      = xml.GetMemento(settings);

            List <InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
            int i = 0;

            foreach (DicomFile file in images)
            {
                ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
            }

            xml = new StudyXml();
            xml.SetMemento(doc);

            dataSets = GetInstanceXmlDataSets(xml);
            i        = 0;
            foreach (DicomFile file in images)
            {
                ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
            }
        }
Esempio n. 28
0
		public void TestMultipleSerializations()
		{
			List<DicomFile> images = SetupImages(4);

			XmlDocument doc = null;
			StudyXml xml;
			int i;
			for(i = 0; i < images.Count; ++i)
			{
				xml = new StudyXml();

				if (doc != null)
					xml.SetMemento(doc);

				xml.AddFile(images[i]);
				StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
				doc = xml.GetMemento(settings);
			}

			xml = new StudyXml();
			xml.SetMemento(doc);
			List<InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
			i = 0;
			foreach (DicomFile file in images)
				ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
		}
Esempio n. 29
0
		public void TestExcludeBinaryTags()
		{
			List<DicomFile> images = SetupImages(3);
			images[2].DataSet[DicomTags.SpectroscopyData].Values = new float[6];

			StudyXml xml = new StudyXml();
			foreach (DicomFile file in images)
			{
				file.DataSet[DicomTags.RedPaletteColorLookupTableData].Values = new byte[256];
				file.DataSet[DicomTags.GreenPaletteColorLookupTableData].Values = new byte[256];
				file.DataSet[DicomTags.BluePaletteColorLookupTableData].Values = new byte[256];
				xml.AddFile(file);
			}

			StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
			settings.MaxTagLength = 100;
			XmlDocument doc = xml.GetMemento(settings);

			//SaveStudyXml(doc, @"C:\stewart\testxml.xml");
			List<InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
			foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
			{
				Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.RedPaletteColorLookupTableData));
				Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.GreenPaletteColorLookupTableData));
				Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.BluePaletteColorLookupTableData));
			}

			//This attribute has a short value, so it should not be excluded.
			Assert.IsFalse(dataSets[2].IsTagExcluded(DicomTags.SpectroscopyData));

			xml = new StudyXml();
			xml.SetMemento(doc);

			dataSets = GetInstanceXmlDataSets(xml);
			foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
			{
				Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.RedPaletteColorLookupTableData));
				Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.GreenPaletteColorLookupTableData));
				Assert.IsTrue(dataSet.IsTagExcluded(DicomTags.BluePaletteColorLookupTableData));
			}

			//This attribute has a short value, so it should not be excluded.
			Assert.IsFalse(dataSets[2].IsTagExcluded(DicomTags.SpectroscopyData));
		}
Esempio n. 30
0
		public void TestExcludePrivateTags()
		{
			List<DicomFile> images = SetupImages(2);
			StudyXml xml = new StudyXml();
			DicomTag privateTag =
				new DicomTag(0x00210010, "Private Tag", "Private Tag", DicomVr.LTvr, false, 1, uint.MaxValue, false);
			
			foreach (DicomFile file in images)
			{
				file.DataSet[privateTag].SetStringValue("My Private Tag");
				xml.AddFile(file);
			}

			StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
			XmlDocument doc = xml.GetMemento(settings);

			List<InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
			foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
				Assert.IsFalse(dataSet.Contains(privateTag));

			xml = new StudyXml();
			xml.SetMemento(doc);

			dataSets = GetInstanceXmlDataSets(xml);
			foreach (InstanceXmlDicomAttributeCollection dataSet in dataSets)
				Assert.IsFalse(dataSet.Contains(privateTag));
		}
Esempio n. 31
0
        private void UpdateFilesystem()
        {
            Platform.Log(LogLevel.Info, "Updating filesystem...");
            StudyXml studyXml = _oldStudyLocation.LoadStudyXml();
            StudyXmlOutputSettings outputSettings = ImageServerCommonConfiguration.DefaultStudyXmlOutputSettings;

            StudyXml newStudyXml = new StudyXml();

            foreach (SeriesXml seriesXml in studyXml)
            {
                foreach (InstanceXml instanceXml in seriesXml)
                {
                    string path = Path.Combine(_oldStudyPath, seriesXml.SeriesInstanceUid);
                    path  = Path.Combine(path, instanceXml.SopInstanceUid);
                    path += ServerPlatform.DicomFileExtension;

                    if (!File.Exists(path))
                    {
                        Platform.Log(LogLevel.Info, "SOP {0} is referenced in study xml but does not exist. It will be removed");
                        continue; // file was removed but xml was not updated?
                    }

                    try
                    {
                        DicomFile file = new DicomFile(path);
                        file.Load();

                        InstanceInfo instance = new InstanceInfo
                        {
                            SeriesInstanceUid = file.DataSet[DicomTags.SeriesInstanceUid].GetString(0, String.Empty),
                            SopInstanceUid    = file.DataSet[DicomTags.SopInstanceUid].GetString(0, String.Empty)
                        };

                        UpdateDicomFile(file);

                        // Add into the temporary study xml
                        long fileSize = 0;
                        if (File.Exists(file.Filename))
                        {
                            FileInfo finfo = new FileInfo(file.Filename);
                            fileSize = finfo.Length;
                        }
                        newStudyXml.AddFile(file, fileSize, outputSettings);


                        _updatedSopList.Add(instance);
                        Platform.Log(ServerPlatform.InstanceLogLevel, "SOP {0} has been updated [{1} of {2}].", instance.SopInstanceUid, _updatedSopList.Count, _totalSopCount);
                    }
                    catch (Exception)
                    {
                        File.Delete(Path.Combine(_backupDir, instanceXml.SopInstanceUid) + ".bak"); //dont' need to restore this file
                        throw;
                    }
                }
            }

            // Log any study-level warnings
            if (_updatedSopList.Count != _totalSopCount)
            {
                Platform.Log(LogLevel.Warn, "Inconsistent data: expected {0} instances to be updated / Found {1}.", _totalSopCount, _updatedSopList.Count);
            }

            // update the header
            Platform.Log(LogLevel.Info, "Generating new study header...");
            string newStudyXmlPath  = Path.Combine(NewStudyPath, _newStudyInstanceUid + ".xml");
            string gzipStudyXmlPath = Path.Combine(NewStudyPath, _newStudyInstanceUid + ".xml.gz");

            using (FileStream xmlStream = FileStreamOpener.OpenForSoleUpdate(newStudyXmlPath, FileMode.Create),
                   gzipStream = FileStreamOpener.OpenForSoleUpdate(gzipStudyXmlPath, FileMode.Create))
            {
                StudyXmlIo.WriteXmlAndGzip(newStudyXml.GetMemento(outputSettings), xmlStream, gzipStream);
                xmlStream.Close();
                gzipStream.Close();
            }
        }
Esempio n. 32
0
		public void TestExclusionsImmediatelyAfterSerialization()
		{
			//NOTE: previously, this test failed because the excluded tags were not added to the
			//xml collection until after it had been deserialized at least once from the xml.
			foreach (string[] testSet in _overlappingTagTestSets)
			{
				List<DicomFile> images = SetupImages(testSet.Length);
				SetTestAttribute(images, testSet);

				StudyXml xml = new StudyXml();

				foreach (DicomFile file in images)
					xml.AddFile(file);

				StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
				settings.MaxTagLength = 1024;
				XmlDocument doc = xml.GetMemento(settings);

				List<InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
				ValidateSimpleDataSets(testSet, dataSets, settings);

				//do a little extra validation, what the hay.
				xml = new StudyXml();
				xml.SetMemento(doc);

				dataSets = GetInstanceXmlDataSets(xml);
				ValidateSimpleDataSets(testSet, dataSets, settings);
			}
		}
Esempio n. 33
0
		public void TestEqualAfterSerialization()
		{
			foreach (string[] testSet in _overlappingTagTestSets)
			{
				List<DicomFile> images = SetupImages(testSet.Length);
				SetTestAttribute(images, testSet);

				StudyXml xml = new StudyXml();

				foreach (DicomFile file in images)
					xml.AddFile(file);

				StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
				settings.MaxTagLength = 1024;
				XmlDocument doc = xml.GetMemento(settings);

				List<InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
				int i = 0;
				foreach (DicomFile file in images)
					ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);

				xml = new StudyXml();
				xml.SetMemento(doc);

				dataSets = GetInstanceXmlDataSets(xml);
				i = 0;
				foreach (DicomFile file in images)
					ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
			}
		}
Esempio n. 34
0
		public void CreationTest()
		{
			IList<DicomAttributeCollection> instanceList;

			string studyInstanceUid = DicomUid.GenerateUid().UID;

			instanceList = SetupMRSeries(4, 10, studyInstanceUid);



			StudyXml studyXml = new StudyXml(studyInstanceUid);

			string studyXmlFilename = Path.GetTempFileName();

			foreach (DicomAttributeCollection instanceCollection in instanceList)
			{
				instanceCollection[DicomTags.PixelData] = null;


				DicomFile theFile = new DicomFile("test", new DicomAttributeCollection(), instanceCollection);
				SetupMetaInfo(theFile);

				studyXml.AddFile(theFile);

				WriteStudyStream(studyXmlFilename, studyXml);
			}

			StudyXml newXml = LoadStudyStream(studyXmlFilename);

			if (!Compare(newXml, instanceList))
				Assert.Fail("Comparison of StudyXML failed against base loaded from disk");

			if (!Compare(studyXml, instanceList))
				Assert.Fail("Comparison of StudyXML failed against base in memory");

		}
Esempio n. 35
0
        private void RebuildStudyXml()
        {         
            try
            {                        
                var studyXml = new StudyXml(Location.Study.StudyInstanceUid);

                DicomFile lastLoadedFile = null;

                FileProcessor.Process(Location.StudyFolder, "*.dcm", delegate(string file, out bool cancel)
                                                           {
                                                               cancel = _cancelRequested;
                                                               try
                                                               {
                                                                   var dicomFile = new DicomFile(file);
                                                                   dicomFile.Load(DicomReadOptions.Default |
                                                                                  DicomReadOptions.StorePixelDataReferences);
                                                                  
                                                                   String sopInstanceUid = dicomFile.DataSet[DicomTags.SopInstanceUid].GetString(0, dicomFile.MediaStorageSopInstanceUid);
                                                                   if (Path.GetFileNameWithoutExtension(file) == sopInstanceUid)
                                                                   {
                                                                       if (!studyXml.AddFile(dicomFile))
                                                                       {
                                                                           Platform.Log(LogLevel.Warn,
                                                                                        "Importing file that was in the wrong study folder: {0}",
                                                                                        file);
                                                                           var context =
                                                                               new ImportStudyContext(
                                                                                   dicomFile.SourceApplicationEntityTitle,
                                                                                   StudyStore.GetConfiguration(),EventSource.CurrentProcess);
                                                                           var importer = new ImportFilesUtility(context);
                                                                           var result = importer.Import(dicomFile,
                                                                                                        BadFileBehaviourEnum.Delete,
                                                                                                        FileImportBehaviourEnum.Move);
                                                                           if (result.DicomStatus != DicomStatuses.Success)
                                                                           {
                                                                               Platform.Log(LogLevel.Error,
                                                                                            "Unable to import file: {0}",
                                                                                            result.ErrorMessage);
                                                                               Failed = true;
                                                                               FailureMessage = result.ErrorMessage;
                                                                           }
                                                                       }
                                                                       else
                                                                           lastLoadedFile = dicomFile;
                                                                   }
                                                                   else
                                                                   {
                                                                       Platform.Log(LogLevel.Info, "Ignoring duplicate file: {0}", file);
                                                                   }
                                                               }
                                                               catch (Exception x)
                                                               {
                                                                   Platform.Log(LogLevel.Error, x,
                                                                                "Failed to load file for reprocessing: {0}", file);
                                                                   Failed = true;
                                                                   FailureMessage = x.Message;
                                                               }

                                                           }, false);

                // This saves the study Xml to disk, and ensures the database is updated and the study is not marked as "deleted".
                // If a cancel was requested, don't save the file, and it will remain "as is"
                if (lastLoadedFile !=null && !_cancelRequested)
                {
                    var p = new ProcessStudyUtility(Location) { IsReprocess = true };

                    p.ProcessFile(lastLoadedFile, studyXml, null);
                }
            }
            catch (Exception x)
            {
                Platform.Log(LogLevel.Error, x, "Unexpected exception reindexing folder: {0}", Location.StudyFolder);
                Failed = true;
                FailureMessage = x.Message;
            }

            if (_cancelRequested)
                Platform.Log(LogLevel.Info, "Cancel requested while rebuilding Study XML in folder: {0}", Location.StudyFolder);
            else
                Platform.Log(LogLevel.Info, "Rebuilt Study XML for study: {0}", Location.Study.StudyInstanceUid);
        }
Esempio n. 36
0
        private void RebuildStudyXml()
        {
            try
            {
                var studyXml = new StudyXml(Location.Study.StudyInstanceUid);

                DicomFile lastLoadedFile = null;

                FileProcessor.Process(Location.StudyFolder, "*.dcm",
                                      delegate(string file, out bool cancel)
                {
                    cancel = _cancelRequested;
                    try
                    {
                        var dicomFile = new DicomFile(file);
                        dicomFile.Load(DicomReadOptions.Default | DicomReadOptions.StorePixelDataReferences);

                        String sopInstanceUid = dicomFile.DataSet[DicomTags.SopInstanceUid].GetString(0, dicomFile.MediaStorageSopInstanceUid);
                        if (Path.GetFileNameWithoutExtension(file) == sopInstanceUid)
                        {
                            if (!studyXml.AddFile(dicomFile))
                            {
                                Platform.Log(LogLevel.Warn, "Importing file that was in the wrong study folder: {0}", file);
                                var context  = new ImportStudyContext(dicomFile.SourceApplicationEntityTitle, StudyStore.GetConfiguration(), EventSource.CurrentProcess);
                                var importer = new ImportFilesUtility(context);
                                var result   = importer.Import(dicomFile, BadFileBehaviourEnum.Delete, FileImportBehaviourEnum.Move);
                                if (result.DicomStatus != DicomStatuses.Success)
                                {
                                    Platform.Log(LogLevel.Error, "Unable to import file: {0}", result.ErrorMessage);
                                    Failed         = true;
                                    FailureMessage = result.ErrorMessage;
                                }
                            }
                            else
                            {
                                lastLoadedFile = dicomFile;
                            }
                        }
                        else
                        {
                            Platform.Log(LogLevel.Info, "Ignoring duplicate file: {0}", file);
                        }
                    }
                    catch (Exception x)
                    {
                        Platform.Log(LogLevel.Error, x, "Failed to load file for reprocessing: {0}", file);
                        Failed         = true;
                        FailureMessage = x.Message;
                    }
                }, false);

                // This saves the study Xml to disk, and ensures the database is updated and the study is not marked as "deleted".
                // If a cancel was requested, don't save the file, and it will remain "as is"
                if (lastLoadedFile != null && !_cancelRequested)
                {
                    var p = new ProcessStudyUtility(Location)
                    {
                        IsReprocess = true
                    };

                    p.ProcessFile(lastLoadedFile, studyXml, null);
                }
            }
            catch (Exception x)
            {
                Platform.Log(LogLevel.Error, x, "Unexpected exception reindexing folder: {0}", Location.StudyFolder);
                Failed         = true;
                FailureMessage = x.Message;
            }

            if (_cancelRequested)
            {
                Platform.Log(LogLevel.Info, "Cancel requested while rebuilding Study XML in folder: {0}", Location.StudyFolder);
            }
            else
            {
                Platform.Log(LogLevel.Info, "Rebuilt Study XML for study: {0}", Location.Study.StudyInstanceUid);
            }
        }
Esempio n. 37
0
        /// <summary>
        /// 刻录
        /// </summary>
        private void Writing()
        {
            List <IBurnMediaData> data         = new List <IBurnMediaData>();
            MediaFileSet          mediaFileSet = new MediaFileSet();

            mediaFileSet.Id = "Gold";
            List <MediaFileSetStudy> fileSetStudies = new List <MediaFileSetStudy>();
            string RootPath       = "CD";
            string studysPath     = "IMAGES";
            string studyitemPath  = "Study{0}";
            string seriesitemPath = "Series{0}";
            string filename       = "IM{0}";
            string xmlSavePath    = "studies";
            string XmlName        = "Study{0}.xml";
            int    study          = -1;
            int    series         = -1;
            int    Sopcount       = -1;

            string studyIndexName = "index.xml";

            string xmlPath = Path.Combine(this.StagingFolderPath, xmlSavePath);

            if (Directory.Exists(xmlPath))
            {
                Directory.Delete(xmlPath, true);
            }
            Directory.CreateDirectory(xmlPath);

            if (MediaWriterSettings.Default.PortablePath == null || !Directory.Exists(MediaWriterSettings.Default.PortablePath))
            {
                this.Host.ShowMessageBox("指定光盘浏览器目录不存在", MessageBoxActions.Ok);
                return;
            }
            FileDirectoryUtility.CopyFiles(MediaWriterSettings.Default.PortablePath, this.StagingFolderPath, true, true);
            RootPath = Path.Combine(this.StagingFolderPath, studysPath);
            DicomDirectory dicomDirectory = new DicomDirectory(VolumeName);

            dicomDirectory.SourceApplicationEntityTitle = VolumeName;
            dicomDirectory.FileSetId = "File Set Desc";
            try
            {
                foreach (IStudyTreeItem item in Tree.Items)
                {
                    StudyTreeItem treeitem = (StudyTreeItem)item;
                    if (!treeitem.Ischecked)
                    {
                        continue;
                    }
                    study++;
                    MediaFileSetStudy fileSet       = new MediaFileSetStudy();
                    string            tempstudypath = Path.Combine(RootPath, string.Format(studyitemPath, study));
                    StudyXml          studyXml      = new StudyXml();
                    foreach (ISeriesTreeItem seriss in treeitem.Tree.Items)
                    {
                        SeriesTreeItem seriesitem = (SeriesTreeItem)seriss;
                        if (!seriesitem.Ischecked)
                        {
                            continue;
                        }
                        series++;
                        string tempseriespath = Path.Combine(tempstudypath, string.Format(seriesitemPath, series));
                        if (Directory.Exists(tempseriespath))
                        {
                            Directory.Delete(tempseriespath, true);
                        }
                        Directory.CreateDirectory(tempseriespath);

                        foreach (var sop in seriesitem.Series.GetSopInstances())
                        {
                            if (LoadImageWorker.CancellationPending == true)
                            {
                                break;
                            }

                            if (File.Exists(sop.FilePath))
                            {
                                Sopcount++;
                                string temp = Path.Combine(tempseriespath, string.Format(filename, Sopcount));
                                File.Copy(sop.FilePath, temp);
                                int    start       = temp.IndexOf(studysPath);
                                string dirFilePath = temp.Substring(start);
                                dicomDirectory.AddFile(temp, dirFilePath);
                                string    fileName = string.Format("..\\{0}", dirFilePath);
                                DicomFile file     = new DicomFile(temp);
                                file.Load();
                                file.Filename = fileName;
                                studyXml.AddFile(file);
                                fileSet.UID = sop.StudyInstanceUid;
                            }
                        }
                    }
                    //保存studyXml
                    string xmlFileName = string.Format(XmlName, study);
                    string path        = Path.Combine(xmlPath, xmlFileName);
                    StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
                    settings.IncludeSourceFileName = true;
                    XmlDocument document = studyXml.GetMemento(settings);

                    // Create an XML declaration.
                    XmlDeclaration xmldecl;
                    xmldecl          = document.CreateXmlDeclaration("1.0", null, null);
                    xmldecl.Encoding = "UTF-8";
                    document.Save(path);

                    fileSet.Value = Path.Combine(xmlSavePath, xmlFileName);;
                    fileSetStudies.Add(fileSet);
                }

                if (!Directory.Exists(RootPath))
                {
                    throw new Exception(string.Format("复制检查图像到{0}目录出错", StagingFolderPath));
                }

                IBurnMediaData info = new BurnMediaData();
                info.Type = MediaType.Dir;
                info.Path = RootPath;
                data.Add(info);

                IBurnMediaData xml = new BurnMediaData();
                xml.Path = xmlPath;
                xml.Type = MediaType.Dir;
                data.Add(xml);

                string studyindexfilename = Path.Combine(this.StagingFolderPath, studyIndexName);
                if (File.Exists(studyindexfilename))
                {
                    File.Delete(studyindexfilename);
                }
                Stream stream = File.Open(studyindexfilename, FileMode.Create);
                mediaFileSet.StudyIndex = fileSetStudies.ToArray();
                XmlSerializer serializer = new XmlSerializer(typeof(MediaFileSet));
                serializer.Serialize(stream, mediaFileSet);
                IBurnMediaData studyindex = new BurnMediaData();
                studyindex.Path = studyindexfilename;
                studyindex.Type = MediaType.File;
                data.Add(studyindex);

                string dirfilename = Path.Combine(this.StagingFolderPath, "DICOMDIR");
                dicomDirectory.Save(dirfilename);
                info      = new BurnMediaData();
                info.Type = MediaType.File;
                info.Path = dirfilename;
                data.Add(info);
                DoBurn(data);
            }
            catch (COMException ex)
            {
                this.Host.ShowMessageBox(ImapiReturnValues.GetName(ex.ErrorCode), MessageBoxActions.Ok);
            }
            catch (Exception e)
            {
                this.Host.ShowMessageBox(e.Message, MessageBoxActions.Ok);
            }
            finally
            {
                this.IsWriting = false;
            }
        }
Esempio n. 38
0
		public void TestTransferSyntax()
		{
			List<DicomFile> images = SetupImages(4);

			string seriesUid = images[0].DataSet[DicomTags.SeriesInstanceUid].ToString();

			images[0].TransferSyntax = TransferSyntax.Jpeg2000ImageCompression;
			images[1].TransferSyntax = TransferSyntax.ExplicitVrLittleEndian;
			images[2].TransferSyntax = TransferSyntax.ExplicitVrBigEndian;
			images[3].TransferSyntax = TransferSyntax.Jpeg2000ImageCompressionLosslessOnly;

			StudyXml xml = new StudyXml();
			foreach (DicomFile file in images)
				xml.AddFile(file);

			XmlDocument doc = xml.GetMemento(new StudyXmlOutputSettings());

			Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompression);
			Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrLittleEndian);
			Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrBigEndian);
			Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompressionLosslessOnly);

			xml = new StudyXml();
			xml.SetMemento(doc);

			Assert.AreEqual(xml[seriesUid][images[0].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompression);
			Assert.AreEqual(xml[seriesUid][images[1].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrLittleEndian);
			Assert.AreEqual(xml[seriesUid][images[2].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.ExplicitVrBigEndian);
			Assert.AreEqual(xml[seriesUid][images[3].DataSet[DicomTags.SopInstanceUid]].TransferSyntax, TransferSyntax.Jpeg2000ImageCompressionLosslessOnly);
		}
Esempio n. 39
0
		private void UpdateFilesystem()
		{
			Platform.Log(LogLevel.Info, "Updating filesystem...");
			StudyXml studyXml = _oldStudyLocation.LoadStudyXml();
			StudyXmlOutputSettings outputSettings = ImageServerCommonConfiguration.DefaultStudyXmlOutputSettings;

			StudyXml newStudyXml = new StudyXml();
            foreach (SeriesXml seriesXml in studyXml)
			{
				foreach (InstanceXml instanceXml in seriesXml)
				{
					string path = Path.Combine(_oldStudyPath, seriesXml.SeriesInstanceUid);
					path = Path.Combine(path, instanceXml.SopInstanceUid);
					path += ServerPlatform.DicomFileExtension;

                    if (!File.Exists(path))
                    {
                        Platform.Log(LogLevel.Info, "SOP {0} is referenced in study xml but does not exist. It will be removed");
                        continue; // file was removed but xml was not updated?
                    }

                    try
                    {                        
                        DicomFile file = new DicomFile(path);
                        file.Load();

                        InstanceInfo instance = new InstanceInfo
                        {
                            SeriesInstanceUid = file.DataSet[DicomTags.SeriesInstanceUid].GetString(0, String.Empty),
                            SopInstanceUid = file.DataSet[DicomTags.SopInstanceUid].GetString(0, String.Empty)
                        };
                        
                        UpdateDicomFile(file);

                        // Add into the temporary study xml
                        long fileSize = 0;
                        if (File.Exists(file.Filename))
                        {
                            FileInfo finfo = new FileInfo(file.Filename);
                            fileSize = finfo.Length;
                        }
                        newStudyXml.AddFile(file, fileSize, outputSettings);

                        
                        _updatedSopList.Add(instance);
                        Platform.Log(ServerPlatform.InstanceLogLevel, "SOP {0} has been updated [{1} of {2}].", instance.SopInstanceUid, _updatedSopList.Count, _totalSopCount);

						EventManager.FireEvent(this, new UpdateSopEventArgs { File = file, ServerPartitionEntry = _partition, WorkQueueUidEntry = null, WorkQueueEntry = _workQueue, FileLength = (ulong)fileSize });

                    }
                    catch (Exception)
                    {
                        File.Delete(Path.Combine(_backupDir, instanceXml.SopInstanceUid) + ".bak"); //dont' need to restore this file
                        throw;
                    }
                }                
			}

            // Log any study-level warnings
			if (_updatedSopList.Count != _totalSopCount)
			{
				Platform.Log(LogLevel.Warn, "Inconsistent data: expected {0} instances to be updated / Found {1}.", _totalSopCount, _updatedSopList.Count);
			}

            // update the header
			Platform.Log(LogLevel.Info, "Generating new study header...");
			string newStudyXmlPath = Path.Combine(NewStudyPath, _newStudyInstanceUid + ".xml");
			string gzipStudyXmlPath = Path.Combine(NewStudyPath, _newStudyInstanceUid + ".xml.gz");
			using (FileStream xmlStream = FileStreamOpener.OpenForSoleUpdate(newStudyXmlPath, FileMode.Create),
			                  gzipStream = FileStreamOpener.OpenForSoleUpdate(gzipStudyXmlPath, FileMode.Create))
			{
				StudyXmlIo.WriteXmlAndGzip(newStudyXml.GetMemento(outputSettings), xmlStream, gzipStream);
				xmlStream.Close();
				gzipStream.Close();
			}
		}
Esempio n. 40
0
		public void TestBaseInstanceTagsPastEnd()
		{
			//NOTE: previously, this test failed because, during xml serialization, only the
			//instance's own attributes were iterated over; if there were tags in the base instance
			//that went past the end of the individual instances, no 'EmptyAttributes' got added
			//to the xml and there would be extra attributes in the instances on deserialization.
			List<DicomFile> images = SetupImages(2);
			DicomFile smallFile = new DicomFile(null);
			images.Add(smallFile);
			base.SetupMetaInfo(smallFile);

			DicomAttributeCollection theSet = smallFile.DataSet;
			theSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
			theSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\M\\FFE");
			theSet[DicomTags.InstanceCreationDate].SetStringValue("20070618");
			theSet[DicomTags.InstanceCreationTime].SetStringValue("133600");
			theSet[DicomTags.SopClassUid].SetStringValue(SopClass.MrImageStorageUid);
			theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			theSet[DicomTags.StudyDate].SetStringValue("20070618");
			theSet[DicomTags.StudyTime].SetStringValue("133600");
			theSet[DicomTags.SeriesDate].SetStringValue("20070618");
			theSet[DicomTags.SeriesTime].SetStringValue("133700");
			theSet[DicomTags.AccessionNumber].SetStringValue("A1234");
			theSet[DicomTags.Modality].SetStringValue("MR");
			theSet[DicomTags.Manufacturer].SetStringValue("ClearCanvas");
			theSet[DicomTags.ManufacturersModelName].SetNullValue();
			theSet[DicomTags.InstitutionName].SetStringValue("Mount Sinai Hospital");
			theSet[DicomTags.ReferringPhysiciansName].SetStringValue("Last^First");
			theSet[DicomTags.StudyDescription].SetStringValue("HEART");
			theSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");

			theSet[DicomTags.StudyInstanceUid].SetStringValue(images[0].DataSet[DicomTags.StudyInstanceUid].ToString());
			theSet[DicomTags.SeriesInstanceUid].SetStringValue(images[0].DataSet[DicomTags.SeriesInstanceUid].ToString());
			theSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().ToString());

			StudyXml xml = new StudyXml();

			foreach (DicomFile file in images)
				xml.AddFile(file);

			StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
			XmlDocument doc = xml.GetMemento(settings);

			List<InstanceXmlDicomAttributeCollection> dataSets = GetInstanceXmlDataSets(xml);
			int i = 0;
			foreach (DicomFile file in images)
				ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);

			xml = new StudyXml();
			xml.SetMemento(doc);

			dataSets = GetInstanceXmlDataSets(xml);
			i = 0;
			foreach (DicomFile file in images)
				ValidateEqualExceptExclusions(file.DataSet, dataSets[i++], DicomTags.ImageComments, DicomTags.PixelData);
		}