Esempio n. 1
0
        public void ManualCreateTest()
        {
            lock (sentry)
            {
                string folder = Path.Combine(Tools.RootFolder, @"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir");
                string path   = Path.Combine(folder, "ManualCreateTest");

                Directory.CreateDirectory(path);

                DicomDir dir = new DicomDir(path);
                dir.Empty();

                DateTime now = DateTime.Now;

                Patient patient = dir.NewPatient("Sadler^Michael", "12345");
                Study   study   = patient.NewStudy(now, now, Element.NewUid(), "1");
                Series  series  = study.NewSeries("CR", Element.NewUid());
                Image   image   = series.NewImage(Path.Combine(folder, "THGLUZ5J.dcm"));

                dir.Save();
                string before = Dump(dir, "before");

                dir = new DicomDir(path);
                string after = Dump(dir, "after");

                Assert.AreEqual(before, after, "before does not match after");
            }
        }
Esempio n. 2
0
 private void OnImageStored(object sender, ImageStoredEventArgs e)
 {
     if (this.InvokeRequired)
     {
         this.Invoke(new ImageStoredEventHandler(OnImageStored), new object[] { sender, e });
     }
     else
     {
         try
         {
             if (pacsmode)
             {
                 DataSet  dicom = e.DataSet;
                 DicomDir dir   = new DicomDir(".");
                 dir.Add(dicom);
                 dir.Save();
             }
             else
             {
                 NewBrowser(e.DataSet);
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(Logging.Log(ex));
         }
     }
 }
Esempio n. 3
0
        public void FolderingTest()
        {
            string folder = Path.Combine(Tools.RootFolder, @"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir");
            string path   = Path.Combine(folder, "FolderingTest");

            DicomDir dir = new DicomDir(path);

            dir.Empty();

            DirectoryInfo working = new DirectoryInfo(path);

            working = Directory.CreateDirectory(path);

            int n = 0;

            // add each test image to the DICOMDIR
            foreach (string file in Directory.GetFiles(folder, "*.dcm"))
            {
                dir.Add(file, @"parent\child");
                n++;
            }

            // write it out
            dir.Save();

            string temp = Path.Combine(path, @"parent\child");

            temp = Path.Combine(temp, String.Format("{0:00000000}", n));
            Assert.IsTrue(new FileInfo(temp).Exists);
        }
Esempio n. 4
0
        public void GetSequentialFileName()
        {
            DirectoryInfo working = new DirectoryInfo(".");

            bool existing = false;

            foreach (FileInfo file in working.GetFiles())
            {
                if (file.Extension.ToUpper() == ".DCM")
                {
                    existing = true;
                    break;
                }
            }

            Assert.IsFalse(existing, "Did not expect any DICOM files in working folder.");

            Assert.AreEqual("00000001", DicomDir.GetSequentialFileName("."));

            File.Create(Path.Combine(".", "00000001")).Dispose();
            File.Create(Path.Combine(".", "00000003")).Dispose();
            File.Create(Path.Combine(".", "00000097")).Dispose();
            Assert.AreEqual("00000098", DicomDir.GetSequentialFileName("."));

            File.Delete(Path.Combine(".", "00000097"));
            Assert.AreEqual("00000004", DicomDir.GetSequentialFileName("."));

            File.Delete(Path.Combine(".", "00000003"));
            Assert.AreEqual("00000002", DicomDir.GetSequentialFileName("."));

            File.Delete(Path.Combine(".", "00000001"));
            Assert.AreEqual("00000001", DicomDir.GetSequentialFileName("."));
        }
Esempio n. 5
0
        public void InternalCMoveTest()
        {
            // make sure DICOM at "." is empty
            DicomDir dir = new DicomDir(".");

            dir.Empty();

            ApplicationEntity storage = new ApplicationEntity("ImageServer", IPAddress.Parse("127.0.0.1"), 2000);
            ApplicationEntity server  = new ApplicationEntity("ImageServer", IPAddress.Parse("127.0.0.1"), 5104);

            Dictionary <string, ApplicationEntity> stations = new Dictionary <string, ApplicationEntity>();

            stations.Add(storage.Title, storage);

            StorageTest.Start(storage);
            CMoveTest.Start(server, stations);

            // add three images to a DICOMDIR at "."
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\Y2ASNFDS.dcm", storage, false);
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\WNGVU1P1.dcm", storage, false);
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\THGLUZ5J.dcm", storage, false);

            // ask for an image from a DICOMDIR at "." be delivered to a DICOMDIR at "."
            // should create a duplicate SOPInstanceUID, which results in a WARNING
            try
            {
                move(storage.Title, server);
            }
            catch (Exception)
            {
            }

            CMoveTest.Stop();
            StorageTest.Stop();
        }
Esempio n. 6
0
        string Dump(DicomDir dir, string title)
        {
            StringBuilder text = new StringBuilder();

            foreach (Patient patient in dir.Patients)
            {
                text.Append(String.Format("patient next={0} child={1}\n", patient.OffsetNextRecord, patient.OffsetFirstChild));
                foreach (Study study in patient)
                {
                    text.Append(String.Format("\tstudy next={0} child={1}\n", study.OffsetNextRecord, study.OffsetFirstChild));
                    foreach (Series series in study)
                    {
                        text.Append(String.Format("\t\tseries next={0} child={1}\n", series.OffsetNextRecord, series.OffsetFirstChild));
                        foreach (Image image in series)
                        {
                            text.Append(String.Format("\t\t\timage next={0} child={1} {2}\n", image.OffsetNextRecord, image.OffsetFirstChild, image.ReferencedFileID));
                        }
                    }
                }
            }

            string result = text.ToString();

            Debug.WriteLine(title + "\n" + result);

            return(result);
        }
Esempio n. 7
0
        public RecordCollection InternalQuery(Elements query)
        {
            RecordCollection records = new RecordCollection();

            if (this.SOPClassUId != SOPClass.ModalityWorklistInformationModelFIND)
            {
                DicomDir dir = new DicomDir(".");

                string level = (string)query[t.QueryRetrieveLevel].Value;

                foreach (Patient patient in dir.Patients)
                {
                    if (level == "PATIENT")
                    {
                        if (Compare(query, patient.Elements))
                        {
                            records.Add(patient.Elements);
                        }
                    }
                    else
                    {
                        foreach (Study study in patient)
                        {
                            if (level == "STUDY")
                            {
                                if (Compare(query, study.Elements))
                                {
                                    records.Add(study.Elements);
                                }
                            }
                            else
                            {
                                foreach (Series series in study)
                                {
                                    if (level == "SERIES")
                                    {
                                        if (Compare(query, series.Elements))
                                        {
                                            records.Add(series.Elements);
                                        }
                                    }
                                    else
                                    {
                                        foreach (Image image in series)
                                        {
                                            if (Compare(query, image.Elements))
                                            {
                                                records.Add(image.Elements);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(records);
        }
Esempio n. 8
0
        public static void OnImageStored(object sender, ImageStoredEventArgs e)
        {
            DataSet dicom = e.DataSet;

            DicomDir dir = new DicomDir(".");

            dir.Add(dicom);
            dir.Save();
        }
Esempio n. 9
0
        public void ManualExtraTagsTest()
        {
            string folder = Path.Combine(Tools.RootFolder, @"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir");
            string path   = Path.Combine(folder, "ManualExtraTagsTest");

            DicomDir dir = new DicomDir(path);

            dir.Empty();

            DirectoryInfo working = new DirectoryInfo(path);

            working = Directory.CreateDirectory(path);

            int n = 0;

            // add each test image to the DICOMDIR
            foreach (string file in Directory.GetFiles(folder, "*.dcm"))
            {
                DataSet temp = new DataSet();
                temp.Read(file);

                // when you add an Image, you now get back a reference to the image
                Image image = dir.Add(temp, @"parent\child");

                // and you can apply some logic to add tags

                // either hard code them
                image.Elements.Set(t.InstanceNumber, n);
                // or add them if they exist in the original image
                if (temp.Contains(t.ImagePositionPatient))
                {
                    image.Elements.Add(temp[t.ImagePositionPatient]);
                }
                else
                {
                    image.Elements.Add(t.ImagePositionPatient, "1");
                }
                if (temp.Contains(t.ImageOrientationPatient))
                {
                    image.Elements.Add(temp[t.ImageOrientationPatient]);
                }
                else
                {
                    image.Elements.Add(t.ImageOrientationPatient, "2");
                }

                n++;
            }

            // write it out
            dir.Save();
        }
Esempio n. 10
0
        public void InternalQueryTest2()
        {
            DicomDir dir = new DicomDir(".");

            dir.Empty();

            ApplicationEntity storage = new ApplicationEntity("ImageServer", IPAddress.Parse("127.0.0.1"), 2000);

            StorageTest.Start(storage);

            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\Y2ASNFDS.dcm", storage, false);
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\WNGVU1P1.dcm", storage, false);
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\THGLUZ5J.dcm", storage, false);

            StorageTest.Stop();

            ApplicationEntity host = new ApplicationEntity("IMAGESERVER", 2190);

            CFindTest.Start(host);

            CFindServiceSCU find = new CFindServiceSCU(SOPClass.StudyRootQueryRetrieveInformationModelFIND);

            find.Syntaxes.Add(Syntax.ExplicitVrLittleEndian);

            Association association = new Association();

            association.AddService(find);

            if (association.Open(host.Title, host.Address, host.Port))
            {
                Series series = new Series();
                series[t.StudyInstanceUID].Value = "1.2.840.113564.109517115.2009111711190101521";

                DataSet filter = new DataSet();
                filter.Elements = series.Elements;

                filter.Set(t.QueryRetrieveLevel, "SERIES");

                RecordCollection records = find.CFind(filter);
                RecordCollectionTest.WriteRecords(records);
            }
            else
            {
                System.Console.WriteLine("\ncan't Open.");
            }
            association.Close();
            dir.Empty();

            CFindTest.Stop();
        }
Esempio n. 11
0
        private void toolStripButton_OpenDicomDir_Click(object sender, EventArgs e)
        {
            var dicomDirPath = Path.Combine(dicomServiceWorker.StorageRootPath, toolStripComboBox_DicomDir.Text);

            if (!Directory.Exists(dicomDirPath))
            {
                Directory.CreateDirectory(dicomDirPath);
                var dicomDir = new DicomDir(dicomDirPath);
                dicomDir.Save();
            }

            LoadFile(Path.Combine(dicomDirPath, "DICOMDIR"));
            LoadAllDicomDir();
            RefreshControl();
        }
Esempio n. 12
0
        public static DicomDir Setup(string folder, string path)
        {
            DicomDir dir = new DicomDir(Path.Combine(folder, path));

            dir.Empty();

            // add each test image to the DICOMDIR
            foreach (string file in Directory.GetFiles(folder, "*.dcm"))
            {
                dir.Add(file);
            }

            // write it out
            dir.Save();

            return(dir);
        }
Esempio n. 13
0
        private long CreateDicomDirectory
        (
            CompositeInstanceDataSet dicomInstances,
            DirectoryInfo mediaDirectory,
            IDicomMediaProfileProcessor profileProcessor
        )
        {
            using (DicomDir dicomDir = new DicomDir(mediaDirectory.FullName))
            {
                List <string> createdFiles;


                createdFiles = ProcessDicomDir(mediaDirectory,
                                               dicomInstances,
                                               dicomDir,
                                               profileProcessor);

                dicomDir.SetFileSetId(mediaDirectory.Name);

                if (!string.IsNullOrEmpty(DescriptorFile))
                {
                    string descriptorFile;


                    descriptorFile = CopyDescriptorFile(mediaDirectory.FullName);

                    dicomDir.SetDescriptorFile(descriptorFile, DescriptorFileCharacterSet);

                    createdFiles.Add(descriptorFile);
                }

                profileProcessor.OnDicomDirCompleted(dicomDir.DataSet);

                dicomDir.Save( );

                createdFiles.Add(Path.Combine(mediaDirectory.FullName, "DICOMDIR"));

                return(GetFilesSize(createdFiles));
            }
        }
Esempio n. 14
0
        public void AddCreateTest()
        {
            lock (sentry)
            {
                string folder = Path.Combine(Tools.RootFolder, @"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir");

                DicomDir dir = Setup(folder, "AddCreateTest");

                string before = Dump(dir, "before");

                // then read it in
                dir = new DicomDir(Path.Combine(folder, "AddCreateTest"));
                string after = Dump(dir, "after");

                // compare dumps to see if we got the same thing
                Assert.AreEqual(before, after, "before does not match after");

                // do not like the lack of random access and inability to get a count and navigate tree

                // the next block tests the results, two patients, one with one study/series/image and
                // one with a single study/series with two images
                Assert.IsTrue(dir.Patients.Count == 2, "Expecting two Patients");
                foreach (Study study in (Patient)dir.Patients[0])
                {
                    int count = 0;
                    foreach (Series series in study)
                    {
                        count++;
                        foreach (Image image in series)
                        {
                            Assert.IsTrue(image.OffsetNextRecord != 0, "Expecting more than one Image");
                            break;
                        }
                    }
                    Assert.IsTrue(count == 1, "Expecting one Series");
                    Assert.IsTrue(study.OffsetNextRecord == 0, "Expecting one Study");
                    break;
                }
            }
        }
Esempio n. 15
0
        public ucDircomDir(ReceivedDicomElements receivedDicomElements, IDicomServiceWorkerUser dicomServiceWorkerUser)
        {
            InitializeComponent();

            tabControl_DicomDirFiles.DrawMode  = TabDrawMode.OwnerDrawFixed;
            tabControl_DicomDirFiles.DrawItem += tabControl_DicomDirFiles_DrawItem;


            this.receivedDicomElements  = receivedDicomElements;
            this.dicomServiceWorkerUser = dicomServiceWorkerUser;

            receivedDicomElements.FileName = (new FileInfo(receivedDicomElements.FileName)).DirectoryName;

            var dir = new DicomDir(receivedDicomElements.FileName);

            var rootNode = new TreeListNode {
                Text = "All Patients"
            };

            treeListView_DicomDir.Nodes.Add(rootNode);
            FillElement(dir.Patients, rootNode);
            rootNode.ExpandAll();
        }
Esempio n. 16
0
 private void FillTreeView()
 {
     try
     {
         TreeView.Nodes.Clear();
         string   title = (filename != null && filename.Length > 0) ? filename : "untitled";
         TreeNode root  = TreeView.Nodes.Add("root", title);
         if (dicomdir)
         {
             FileInfo info = new FileInfo(filename);
             if (info.Name == "DICOMDIR")
             {
                 DicomDir dir = new DicomDir(info.DirectoryName);
                 FillElement(dir.Patients, root);
             }
         }
         else
         {
             foreach (Element element in dicom)
             {
                 // do not show group length tags
                 if (element.element == 0)
                 {
                     continue;
                 }
                 TreeNode node = root.Nodes.Add(element.GetPath() + " tag", Title(element));
                 FillElement(element, node);
             }
         }
         root.Expand();
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show("Problems encountered, " + ex.Message);
     }
 }
Esempio n. 17
0
        public void SaveToDicomDir(ReceivedDicomElements receivedDicomElements, string dicomDirName)
        {
            var message  = " -- DicomDir : " + dicomDirName + ", ";
            var hasError = true;

            try
            {
                if (receivedDicomElements.ImageSource == ImageSource.LocalDicomFile)
                {
                    message += "File : " + receivedDicomElements.FileName;
                }
                else
                {
                    message += string.Format("AeTitle : {0}, IpAddress : {1}", receivedDicomElements.CallingAeTitle, receivedDicomElements.IpAddress);
                }


                var dicomDirPath = Path.Combine(StorageRootPath, dicomDirName);
                var dicomDir     = new DicomDir(dicomDirPath);
                dicomDir.Add(receivedDicomElements.Elements);
                dicomDir.Save();
                receivedDicomElements.OnDicomDirSaved(dicomDirName);
                dicomServiceWorkerUser.OnDicomDirSaved(receivedDicomElements, dicomDirName);

                message  = "Save to dicom dir successfull!" + message;
                hasError = false;
            }
            catch (Exception ex)
            {
                message = "Save to dicom dir failed!" + message + "  " + ex.Message;
            }
            finally
            {
                dicomServiceWorkerUser.ShowMessage(message, hasError, false);
            }
        }
Esempio n. 18
0
        public void BaseQueryTest()
        {
            DicomDir dir = new DicomDir(".");

            DateTime now = DateTime.Now;

            // create a patient with two studies, each with one series,
            // the first series with one image, the second with two
            Patient patient = dir.NewPatient("10", "10");
            Study   study   = patient.NewStudy(now, now, "10", "10");
            Series  series  = study.NewSeries("CR", "10");
            Image   image   = series.NewImage("10"); image.ReferencedSOPInstanceUIDinFile = "10";

            study  = patient.NewStudy(now, now, "20", "20");
            series = study.NewSeries("CR", "20");
            image  = series.NewImage("20"); image.ReferencedSOPInstanceUIDinFile = "20";
            image  = series.NewImage("30"); image.ReferencedSOPInstanceUIDinFile = "30";

            // create a patient with one study, containing two series,
            // the first series with two images, the second with one
            patient = dir.NewPatient("20", "20");
            study   = patient.NewStudy(now, now, "30", "30");
            series  = study.NewSeries("CR", "30");
            image   = series.NewImage("40"); image.ReferencedSOPInstanceUIDinFile = "40";
            image   = series.NewImage("50"); image.ReferencedSOPInstanceUIDinFile = "50";
            series  = study.NewSeries("CR", "40");
            image   = series.NewImage("60"); image.ReferencedSOPInstanceUIDinFile = "60";

            // create a patient with a single study and series containing thrww images
            patient = dir.NewPatient("30", "30");
            study   = patient.NewStudy(now, now, "40", "40");
            series  = study.NewSeries("CR", "50");
            image   = series.NewImage("70"); image.ReferencedSOPInstanceUIDinFile = "70";
            image   = series.NewImage("80"); image.ReferencedSOPInstanceUIDinFile = "80";
            image   = series.NewImage("90"); image.ReferencedSOPInstanceUIDinFile = "90";

            dir.Save();

            /*  P   ST  SE  IM
             *  10
             *      10
             *          10
             *              10
             *      20
             *          20
             *              20
             *              30
             *  20
             *      30
             *          30
             *              40
             *              50
             *          40
             *              60
             *  30
             *      40
             *          50
             *              70
             *              80
             *              90
             *
             */

            Assert.AreEqual("10,20,30", query("PATIENT", "10"));
            Assert.AreEqual("10", query("STUDY", "10"));
            Assert.AreEqual("10", query("SERIES", "10"));
            Assert.AreEqual("20,30", query("STUDY", "20"));
            Assert.AreEqual("20,30", query("SERIES", "20"));

            Assert.AreEqual("40,50,60", query("PATIENT", "20"));
            Assert.AreEqual("40,50,60", query("STUDY", "30"));
            Assert.AreEqual("40,50", query("SERIES", "30"));
            Assert.AreEqual("60", query("SERIES", "40"));

            Assert.AreEqual("70,80,90", query("PATIENT", "30"));
            Assert.AreEqual("70,80,90", query("STUDY", "40"));
            Assert.AreEqual("70,80,90", query("SERIES", "50"));

            Assert.AreEqual("10", query("IMAGE", "10"));
            Assert.AreEqual("20", query("IMAGE", "20"));
            Assert.AreEqual("30", query("IMAGE", "30"));
            Assert.AreEqual("40", query("IMAGE", "40"));
            Assert.AreEqual("50", query("IMAGE", "50"));
            Assert.AreEqual("60", query("IMAGE", "60"));
            Assert.AreEqual("70", query("IMAGE", "70"));
            Assert.AreEqual("80", query("IMAGE", "80"));
            Assert.AreEqual("90", query("IMAGE", "90"));

            dir.Empty();
        }
Esempio n. 19
0
        public void OnQuery(object sender, QueryEventArgs args)
        {
            DicomDir dir = new DicomDir(".");

            DataSet query = args.Query;

            string level = (string)query[t.QueryRetrieveLevel].Value;
            bool   found = false;
            string value = String.Empty;

            switch (level)
            {
            case "PATIENT":
                value = (string)query[t.PatientID].Value;
                foreach (Patient patient in dir.Patients)
                {
                    if (patient.PatientID == value)
                    {
                        found = true;
                        args.Records.Add(patient.Elements);
                    }
                    if (found)
                    {
                        break;
                    }
                }
                break;

            case "STUDY":
                //value = (string)query[t.StudyInstanceUID].Value;
                value = (string)query[t.PatientID].Value;
                foreach (Patient patient in dir.Patients)
                {
                    if (patient.PatientID == value)
                    {
                        found = true;
                        foreach (Study study in patient)
                        {
                            args.Records.Add(study.Elements);
                        }
                    }
                    if (found)
                    {
                        break;
                    }
                }
                break;

            case "SERIES":
                //value = (string)query[t.SeriesInstanceUID].Value;
                value = (string)query[t.StudyInstanceUID].Value;
                foreach (Patient patient in dir.Patients)
                {
                    foreach (Study study in patient)
                    {
                        if (study.StudyInstanceUID == value)
                        {
                            found = true;
                            foreach (Series series in study)
                            {
                                args.Records.Add(series.Elements);
                            }
                        }
                        if (found)
                        {
                            break;
                        }
                    }
                    if (found)
                    {
                        break;
                    }
                }
                break;

            case "IMAGE":
                //value = (string)query[t.SOPInstanceUID].Value;
                value = (string)query[t.SeriesInstanceUID].Value;
                foreach (Patient patient in dir.Patients)
                {
                    foreach (Study study in patient)
                    {
                        foreach (Series series in study)
                        {
                            if (series.SeriesInstanceUID == value)
                            {
                                found = true;
                                foreach (EK.Capture.Dicom.DicomToolKit.Image image in series)
                                {
                                    image.Elements.Add(t.SOPClassUID, image.Elements[t.ReferencedSOPClassUIDinFile].Value);
                                    image.Elements.Add(t.SOPInstanceUID, image.Elements[t.ReferencedSOPInstanceUIDinFile].Value);

                                    // added to support prior retrieval via Carestream Modality.
                                    if (query.ValueExists(t.StudyInstanceUID))
                                    {
                                        image.Elements.Add(t.StudyInstanceUID, study.StudyInstanceUID);
                                    }
                                    if (query.ValueExists(t.SeriesInstanceUID))
                                    {
                                        image.Elements.Add(t.SeriesInstanceUID, series.SeriesInstanceUID);
                                    }

                                    args.Records.Add(image.Elements);
                                }
                            }
                            if (found)
                            {
                                break;
                            }
                        }
                        if (found)
                        {
                            break;
                        }
                    }
                    if (found)
                    {
                        break;
                    }
                }
                break;
            }
        }
Esempio n. 20
0
        public void BaseQueryTest()
        {
            DicomDir dir = new DicomDir(".");

            DateTime now = DateTime.Now;

            // create a patient with two studies, each with one series,
            // the first series with one image, the second with two
            Patient patient = dir.NewPatient("Patient^Test", "10");
            Study   study   = patient.NewStudy(now, now, "10", "10");
            Series  series  = study.NewSeries("CR", "10");
            Image   image   = series.NewImage("10"); image.ReferencedSOPInstanceUIDinFile = "10";

            study  = patient.NewStudy(now, now, "20", "20");
            series = study.NewSeries("CR", "20");
            image  = series.NewImage("20"); image.ReferencedSOPInstanceUIDinFile = "20";
            image  = series.NewImage("30"); image.ReferencedSOPInstanceUIDinFile = "30";

            // create a patient with one study, containing two series,
            // the first series with two images, the second with one
            patient = dir.NewPatient("Subject^Test", "20");
            study   = patient.NewStudy(now, now, "30", "30");
            series  = study.NewSeries("DX", "30");
            image   = series.NewImage("40"); image.ReferencedSOPInstanceUIDinFile = "40";
            image   = series.NewImage("50"); image.ReferencedSOPInstanceUIDinFile = "50";
            series  = study.NewSeries("CR", "40");
            image   = series.NewImage("60"); image.ReferencedSOPInstanceUIDinFile = "60";

            // create a patient with a single study and series containing thrww images
            patient = dir.NewPatient("Patietn^Pink", "30");
            study   = patient.NewStudy(now, now, "40", "40");
            series  = study.NewSeries("MG", "50");
            image   = series.NewImage("70"); image.ReferencedSOPInstanceUIDinFile = "70";
            image   = series.NewImage("80"); image.ReferencedSOPInstanceUIDinFile = "80";
            image   = series.NewImage("90"); image.ReferencedSOPInstanceUIDinFile = "90";

            dir.Save();

            /*  P   ST  SE  IM
             *  10
             *      10
             *          10
             *              10
             *      20
             *          20
             *              20
             *              30
             *  20
             *      30
             *          30
             *              40
             *              50
             *          40
             *              60
             *  30
             *      40
             *          50
             *              70
             *              80
             *              90
             *
             */

            patient = new Patient();
            RecordCollection records = query("PATIENT", patient.Elements);

            Assert.AreEqual(3, records.Count);

            study   = new Study();
            records = query("STUDY", study.Elements);
            Assert.AreEqual(4, records.Count);

            series  = new Series();
            records = query("SERIES", series.Elements);
            Assert.AreEqual(5, records.Count);

            image   = new Image();
            records = query("IMAGE", image.Elements);
            Assert.AreEqual(9, records.Count);

            dir.Empty();
        }
Esempio n. 21
0
        private List <string> ProcessDicomDir
        (
            DirectoryInfo mediaDirectory,
            CompositeInstanceDataSet dicomInstances,
            DicomDir dicomDir,
            IDicomMediaProfileProcessor profileProcessor
        )
        {
            string        rootKey;
            List <string> createdFiles;
            int           patientIndex;
            bool          allowLossyCompression;

            rootKey      = "DICOM";
            createdFiles = new List <string> (dicomInstances.Instance.Count);
            patientIndex = 0;

            allowLossyCompression = (MediaObject.AllowLossyCompression == null ||
                                     MediaObject.AllowLossyCompression.Value != YesNo.No);

            foreach (CompositeInstanceDataSet.PatientRow patient in dicomInstances.Patient)
            {
                string patientKey;
                int    studyIndex;


                patientIndex++;

                patientKey = "PATIENT" + patientIndex.ToString( );
                studyIndex = 0;

                foreach (CompositeInstanceDataSet.StudyRow study in patient.GetStudyRows( ))
                {
                    string studyKey;
                    int    seriesIndex;

                    studyIndex++;

                    studyKey    = "STUDY" + studyIndex.ToString( );
                    seriesIndex = 0;

                    foreach (CompositeInstanceDataSet.SeriesRow series in study.GetSeriesRows( ))
                    {
                        string seriesKey;
                        int    instanceIndex;

                        seriesIndex++;

                        seriesKey     = "SERIES" + seriesIndex.ToString( );
                        instanceIndex = 0;

                        foreach (CompositeInstanceDataSet.InstanceRow instance in series.GetInstanceRows( ))
                        {
                            string instanceKey;
                            string instancePath;

                            instanceIndex++;

                            instanceKey = instanceIndex.ToString( );

                            instancePath = GetInstancePath(mediaDirectory, rootKey, patientKey, studyKey, seriesKey, instanceKey);

                            if (!Directory.Exists(Path.GetDirectoryName(instancePath)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(instancePath));
                            }

                            File.Copy(instance.ReferencedFile, instancePath, true);

                            profileProcessor.BeforeAddingToDicomDir(instancePath, instance, allowLossyCompression);

                            dicomDir.InsertFile(instancePath);

                            profileProcessor.AfterAddingToDicomDir(instancePath, instance, dicomDir.DataSet);

                            createdFiles.Add(instancePath);
                        }
                    }
                }
            }

            return(createdFiles);
        }
Esempio n. 22
0
        private MemoryStream ExportToDICOMDIR(ref ZipFile zip, List <DicomDataSet> datasets, ExportOptions options)
        {
            DicomDir     dir;
            string       dirDestination = string.Empty;
            string       folderPath;
            MemoryStream zipStream = new MemoryStream();

            dirDestination = GetDestinationFolder();
            if (!Directory.Exists(dirDestination))
            {
                Directory.CreateDirectory(dirDestination);
            }
            dir        = new DicomDir(dirDestination);
            folderPath = Path.Combine(dirDestination, @"DICOM\");
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }

            try
            {
                Dictionary <string, int> studies = new Dictionary <string, int>();
                Dictionary <string, int> series  = new Dictionary <string, int>();
                int nextStudy  = 0;
                int nextSeries = 0;

                ExportExtensions.ResetAnonymization();
                foreach (DicomDataSet dataset in datasets)
                {
                    string studyInstance  = dataset.GetValue <string>(DicomTag.StudyInstanceUID, string.Empty);
                    string seriesInstance = dataset.GetValue <string>(DicomTag.SeriesInstanceUID, string.Empty);
                    string sopInstance    = dataset.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty);
                    string fileName       = sopInstance + ".dcm";
                    string path           = GetFolderName(studies, series, ref nextStudy, ref nextSeries, studyInstance, seriesInstance);
                    if (zip == null)
                    {
                        zip = new ZipFile();
                    }

                    if (options.FileFormat.ToLower() == "dicomzip" && !string.IsNullOrEmpty(options.DczPassword))
                    {
                        zip.Password = options.DczPassword;
                    }

                    if (options.Anonymize)
                    {
                        dataset.Anonymize();
                    }
                    dataset.Save(folderPath + fileName, DicomDataSetSaveFlags.MetaHeaderPresent);
                    zip.AddEntry(@"DICOM\" + fileName, dataset.ToStream());
                    dir.InsertDataSet(dataset, folderPath + fileName);
                }

                dir.Save();
                if (zip != null)
                {
                    zip.AddFile(dirDestination + "DICOMDIR", string.Empty);
                    if (options.IncludeViewer)
                    {
                        IncludeViewer(ref zip);
                    }
                    zip.Save(zipStream);
                    zip.Dispose();
                }
                zipStream.Position = 0;
            }
            finally
            {
                if (!string.IsNullOrEmpty(dirDestination))
                {
                    if (Directory.Exists(dirDestination))
                    {
                        Directory.Delete(dirDestination, true);
                    }
                }
            }
            return(zipStream);
        }
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            int count = 0;
            int imagesToExportCount   = 0;
            InstanceCStoreCommand cmd = null;

            MatchingParameterCollection matchingParamCollection;
            MatchingParameterList       matchingParamList;

            if (this.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            ExportDicomWorkerArgs args = e.Argument as ExportDicomWorkerArgs;

            if (args == null)
            {
                throw new ArgumentException("Invalid ExportDicom argument");
            }

            if (args.CreateDicomDir)
            {
                DicomDirectory = new DicomDir(args.OutputFolder);
            }

            if (args.Anonymize)
            {
                Anonymizer.BeginBatch();
            }

            try
            {
                ViewGenerator.ViewDataRow[] exportRows = (args.Rows);

                imagesToExportCount = exportRows.Length;

                foreach (ViewGenerator.ViewDataRow exportRow in exportRows)
                {
                    try
                    {
                        string rowKeyValue;
                        string rowKeyName;
                        string viewName;

                        if (this.CancellationPending)
                        {
                            e.Cancel = true;

                            return;
                        }

                        DataRow originalRow = exportRow.OriginalRow;
                        matchingParamCollection = new MatchingParameterCollection( );
                        matchingParamList       = new MatchingParameterList( );

                        matchingParamCollection.Add(matchingParamList);

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.InstanceTableName) == 0)
                        {
                            string         sSopInstanceUid = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity imageInstance   = RegisteredEntities.GetInstanceEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Images";

                            matchingParamList.Add(imageInstance);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.SeriesTableName) == 0)
                        {
                            string         sSeriesInstanceUid = RegisteredDataRows.SeriesInfo.GetElementValue(originalRow, DicomTag.SeriesInstanceUID);
                            ICatalogEntity seriesEntity       = RegisteredEntities.GetSeriesEntity(sSeriesInstanceUid);

                            rowKeyValue = sSeriesInstanceUid;
                            rowKeyName  = "SeriesInstanceUID";
                            viewName    = "Series";

                            matchingParamList.Add(seriesEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.StudyTableName) == 0)
                        {
                            string         sStudyInstanceUid = RegisteredDataRows.StudyInfo.GetElementValue(originalRow, DicomTag.StudyInstanceUID);
                            ICatalogEntity studyEntity       = RegisteredEntities.GetStudyEntity(sStudyInstanceUid);

                            rowKeyValue = sStudyInstanceUid;
                            rowKeyName  = "StudyInstanceUID";
                            viewName    = "Studies";

                            matchingParamList.Add(studyEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.PatientTableName) == 0)
                        {
                            string         sPatientId    = RegisteredDataRows.PatientInfo.GetElementValue(originalRow, DicomTag.PatientID);
                            ICatalogEntity patientEntity = RegisteredEntities.GetPatientEntity(sPatientId);

                            rowKeyValue = sPatientId;
                            rowKeyName  = "PatientId";
                            viewName    = "Patients";

                            matchingParamList.Add(patientEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0)
                        {
                            string         sSopInstanceUid         = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity hangingProtocolInstance = RegisteredEntities.GetHangingProtocolEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Hanging Protocol";

                            matchingParamList.Add(hangingProtocolInstance);
                        }
                        else
                        {
                            throw new ApplicationException("Deleted row is not a valid DICOM format.");
                        }

                        DataSet   exportDataSet = null;
                        DataRow[] rows          = null;

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0 && _dataAccessAgent3 != null)
                        {
                            exportDataSet = _dataAccessAgent3.QueryHangingProtocol(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.HangingProtocolTableName].Select();
                        }
                        else
                        {
                            exportDataSet = _dataAccessAgent.QueryCompositeInstances(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.InstanceTableName].Select();
                        }

                        foreach (DataRow row in rows)
                        {
                            DicomDataSet dicomDataSet = RegisteredDataRows.InstanceInfo.LoadDicomDataSet(row);

                            if (args.Anonymize)
                            {
                                Anonymizer.Anonymize(dicomDataSet);
                            }

                            AddDicomBackgroundWorker.StoreClientSessionProxy proxy = new AddDicomBackgroundWorker.StoreClientSessionProxy();
                            proxy.AffectedSOPInstance = dicomDataSet.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty);
                            proxy.AbstractClass       = dicomDataSet.GetValue <string>(DicomTag.SOPClassUID, string.Empty);


                            try
                            {
                                cmd = new InstanceCStoreCommand(proxy, dicomDataSet, _dataAccessAgent);

                                OnStoreCommandCreated(this, new StoreCommandEventArgs(cmd));

                                cmd.Configuration.DataSetStorageLocation = args.OutputFolder;
#if (LEADTOOLS_V19_OR_LATER)
                                cmd.Configuration.HangingProtocolLocation = args.OutputFolder;
#endif

                                string fileLocation = CStoreCommand.GetStorageFullPath(cmd.Configuration, dicomDataSet);
                                if (args.Overwrite || !File.Exists(fileLocation))
                                {
                                    // Only exporting, so do not validate SopInstance and do not add to database
                                    cmd.DoValidateSopInstance      = false;
                                    cmd.DoUpdateDatabase           = false;
                                    cmd.DoUseExternalStoreSettings = false;
                                    cmd.DataSetStored += cmd_DataSetStored;

                                    cmd.Execute();
                                }
                                else
                                {
                                    // File already exists -- it is not overwritten
                                    DataSetStoredEventArgs storedArgs = new DataSetStoredEventArgs(dicomDataSet, string.Empty, string.Empty, fileLocation);
                                    cmd_DataSetStored(this, storedArgs);
                                }
                            }
                            finally
                            {
                                if (cmd != null)
                                {
                                    cmd.DataSetStored -= cmd_DataSetStored;
                                }
                            }
                        }

                        count++;

                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        state.Error               = null;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.ExportedImagesCount = 1;
                        state.TotalCount          = imagesToExportCount;
                        state.RowKeyValue         = rowKeyValue;
                        state.RowKeyName          = rowKeyName;
                        state.ViewName            = viewName;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                    catch (Exception exception)
                    {
                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        count++;

                        state.Error               = exception;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.TotalCount          = imagesToExportCount;
                        state.ExportedImagesCount = 0;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                }
            }
            finally
            {
                e.Result = imagesToExportCount;
                if (DicomDirectory != null)
                {
                    DicomDirectory.Save();
                    DicomDirectory = null;
                }

                if (Anonymizer != null)
                {
                    Anonymizer.EndBatch();
                    Anonymizer = null;
                }
            }
        }
Esempio n. 24
0
        static void opendicomdir(string folder)
        {
            DicomDir dir = new DicomDir(folder);

            display(dir);
        }
Esempio n. 25
0
        public virtual List <string> Query(DataSet query)
        {
            DicomDir dir = new DicomDir(".");

            const int Patient = 0;
            const int Study   = 1;
            const int Series  = 2;
            const int Image   = 3;

            string level = (string)query[t.QueryRetrieveLevel].Value;
            int    type  = Patient;
            string value = String.Empty;

            switch (level)
            {
            case "PATIENT":
                type  = Patient;
                value = (string)query[t.PatientID].Value;
                break;

            case "STUDY":
                type  = Study;
                value = (string)query[t.StudyInstanceUID].Value;
                break;

            case "SERIES":
                type  = Series;
                value = (string)query[t.SeriesInstanceUID].Value;
                break;

            case "IMAGE":
                type  = Image;
                value = (string)query[t.SOPInstanceUID].Value;
                break;
            }

            List <string> results = new List <string>();

            bool match = false;

            foreach (Patient patient in dir.Patients)
            {
                match = match || (type == Patient && patient.PatientID == value);
                if (match || type > Patient)
                {
                    foreach (Study study in patient)
                    {
                        match = match || (type == Study && study.StudyInstanceUID == value);
                        if (match || type > Study)
                        {
                            foreach (Series series in study)
                            {
                                match = match || (type == Series && series.SeriesInstanceUID == value);
                                if (match || type > Series)
                                {
                                    foreach (Image image in series)
                                    {
                                        match = match || (type == Image && image.ReferencedSOPInstanceUIDinFile == value);
                                        if (match)
                                        {
                                            results.Add(image.ReferencedFileID);
                                            if (type == Image && image.ReferencedSOPInstanceUIDinFile == value)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                    if ((type == Series && series.SeriesInstanceUID == value) || (match && type > Series))
                                    {
                                        break;
                                    }
                                }
                            }
                            if ((type == Study && study.StudyInstanceUID == value) || (match && type > Study))
                            {
                                break;
                            }
                        }
                    }
                    if ((type == Patient && patient.PatientID == value) || (match && type > Patient))
                    {
                        break;
                    }
                }
            }
            return(results);
        }