Exemplo n.º 1
1
        public static void WithSeries(this IEnumerable<CFindResponse> cFinds, DICOMSCU scu, Entity daemon)
        {
            var iods = cFinds.Where(r => r.Status == (ushort)Status.PENDING)
            .Where(r => r.HasData)
            .Where(r => r.Data.Elements.Any(e => e.Tag == TagHelper.STUDY_INSTANCE_UID))
            .Where(r => !string.IsNullOrEmpty(r.Data.Elements.First(e => e.Tag == TagHelper.STUDY_INSTANCE_UID).DData as string))
            .Select(r => r.GetIOD())
            .ToList();
            
            iods.ForEach(i=>i.QueryLevel = QueryLevel.SERIES);

            foreach (var iod in iods)
            {
                var req = new CFindRequest(iod, Root.STUDY);
                var seriesUids = scu.GetResponse(req, daemon)
                     .Where(r => r.Status == (ushort)Status.PENDING)
                     .Where(r => r.HasData)
                     .Where(r => r.Data.Elements.Any(e => e.Tag == TagHelper.SERIES_INSTANCE_UID))
                     .Select(r => new
                     {
                        // Study = study,
                         Series = r.Data.GetSelector().SeriesInstanceUID.Data,
                         Modality = r.Data.GetSelector().Modality.Data
                     })
                     .ToList();
                System.Console.Write("");
            }
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var    process   = Process.GetCurrentProcess();
            string fullPath  = Path.GetDirectoryName(process.MainModule.FileName);
            var    me        = Entity.CreateLocal("DCMGRBC", 51167);
            var    scu       = new DICOMSCU(me);
            var    path      = fullPath + @"\temp\";
            var    scpEntity = Entity.CreateLocal("DCMGRB2", 50401);
            var    scp       = new FileWriterSCP(scpEntity, path);

            scp.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
            scp.ListenForIncomingAssociations(true);
            var logger = new ConsoleLogger(scp.Logger, ConsoleColor.White);

            try
            {
                using (var app = vapi.Application.CreateApplication(null, null))
                {
                    Execute(app, daemon, scu, scp, path);
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString(), "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// This tutorial is outlined in chapter 4 of Scripting in RT for Physicists (C-Store)
        /// </summary>
        public static void Run()
        {
            //Store the details of the daemon (Ae Title, IP, port)
            var daemon = new Entity("PHYSX_DICOM", "10.22.86.64", 51402);
            //Store the details of the client (Ae Title, port) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal("DICOMEC1", 9999);
            //Set up a client (DICOM SCU = Service Class User)
            var client = new DICOMSCU(local);
            var storer = client.GetCStorer(daemon);

            var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var storagePath = Path.Combine(desktopPath, "DICOM Storage");

            ushort msgId    = 1;
            var    dcmFiles = Directory.GetFiles(storagePath);

            foreach (var path in dcmFiles)
            {
                //Reads DICOM object into memory
                var dcm      = DICOMObject.Read(path);
                var response = storer.SendCStore(dcm, ref msgId);
                //Write results to console
                Console.WriteLine($"DICOM C-Store from {local.AeTitle} => " +
                                  $"{daemon.AeTitle} @{daemon.IpAddress}:{daemon.Port}:" +
                                  $"{(Status)response.Status}");
            }
            Console.Read(); //Stop here
        }
        private void echoButton_Click(object sender, RoutedEventArgs e)
        {
            // Store the details of the daemon (Ae Title , IP , port )
            var daemon = new Entity(DaemonTitleTextBox.Text, DaemonIpTextBox.Text, int.Parse(DaemonPortTextBox.Text));
            // Store the details of the client (Ae Title , port ) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal(AEtitleTextBox.Text, int.Parse(AEportTextBox.Text));
            // Set up a client ( DICOM SCU = Service Class User )
            var client = new DICOMSCU(local);
            var storer = client.GetCStorer(daemon);
            //ushort msgId = 1;

            var canPing = client.Ping(daemon);

            if (canPing)
            {
                echoButton.Background = System.Windows.Media.Brushes.LawnGreen;
                ShowLogMsg("\nImport is possible. Echo to Daemon succeeded.");
                ProgressTextBlock.Text = "Echo succeeded. Press Start to begin Import.";
            }
            else
            {
                echoButton.Background = System.Windows.Media.Brushes.PaleVioletRed;
                ShowLogMsg("\nNo import is possible. Echo to Daemon failed.");
                ProgressTextBlock.Text = "Echo failed. Import will also fail.";
            }
        }
Exemplo n.º 5
0
        public static void WithSeries(this IEnumerable <CFindResponse> cFinds, DICOMSCU scu, Entity daemon)
        {
            var iods = cFinds.Where(r => r.Status == (ushort)Status.PENDING)
                       .Where(r => r.HasData)
                       .Where(r => r.Data.Elements.Any(e => e.Tag == TagHelper.STUDY_INSTANCE_UID))
                       .Where(r => !string.IsNullOrEmpty(r.Data.Elements.First(e => e.Tag == TagHelper.STUDY_INSTANCE_UID).DData as string))
                       .Select(r => r.GetIOD())
                       .ToList();

            iods.ForEach(i => i.QueryLevel = QueryLevel.SERIES);

            foreach (var iod in iods)
            {
                var req        = new CFindRequest(iod, Root.STUDY);
                var seriesUids = scu.GetResponse(req, daemon)
                                 .Where(r => r.Status == (ushort)Status.PENDING)
                                 .Where(r => r.HasData)
                                 .Where(r => r.Data.Elements.Any(e => e.Tag == TagHelper.SERIES_INSTANCE_UID))
                                 .Select(r => new
                {
                    // Study = study,
                    Series   = r.Data.GetSelector().SeriesInstanceUID.Data,
                    Modality = r.Data.GetSelector().Modality.Data
                })
                                 .ToList();
                System.Console.Write("");
            }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            var    path    = @"\\hnas1-users\USERS\rcardan\Desktop\ToSend\CT.1.2.246.352.71.3.173326327737.18364155.20171204090851.dcm";
            var    scu     = new DICOMSCU(Entity.CreateLocal("DICOMAnonSCU", 11122));
            var    cStorer = new CStorer(scu, Entity.CreateLocal("DVTK_STR_SCP", 104));
            var    dcm     = DICOMObject.Read(path);
            ushort msg     = 1;

            scu.Logger.LogRequested += Logger_LogRequested;
            var resp = cStorer.SendCStore(dcm, ref msg);

            Thread.Sleep(2000);
            scu = new DICOMSCU(Entity.CreateLocal("DVTK_STRC_SCU", 115));
            var verifier = new StorageVerifier(scu, Entity.CreateLocal("DVTK_STRC_SCP", 105));
            var results  = verifier.VerifyStorage(new Dictionary <string, string>()
            {
                { dcm.GetSelector().SOPClassUID.Data, dcm.GetSelector().SOPInstanceUID.Data }
            }, 10000);

            Console.Read();

            //var scp = new DICOMSCP(Entity.CreateLocal("DVTK_STR_SCP", 104));
            //scp.DIMSEService.CStoreService.CStorePayloadAction = new Func<DICOMObject, Association, bool>((d, asc) =>
            //{
            //    return true;
            //});
            //scp.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
            //scp.SupportedAbstractSyntaxes.Add(AbstractSyntax.StorageCommitment_Push);
            //scp.ListenForIncomingAssociations(true);
            //scp.Logger.LogRequested += Logger_LogRequested;
            //Console.Read();
        }
Exemplo n.º 7
0
        public static void Run()
        {
            //Store the details of the daemon (Ae Title, IP, port)
            var daemon = new Entity("PHYSX_DICOM", "10.22.86.64", 51402);
            //Store the details of the client (Ae Title, port) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal("DICOMEC1", 9999);
            //Set up a client (DICOM SCU = Service Class User)
            var client = new DICOMSCU(local);
            //Set up a receiver to catch the files as they come in
            var receiver = new DICOMSCP(local);

            //Let the daemon know we can take anything it sends
            receiver.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
            //Set up storage location
            var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var storagePath = Path.Combine(desktopPath, "DICOM Storage");

            Directory.CreateDirectory(storagePath);
            //Set the action when a DICOM files comes in
            receiver.DIMSEService.CStoreService.CStorePayloadAction = (dcm, asc) =>
            {
                var path = Path.Combine(storagePath, dcm.GetSelector().SOPInstanceUID.Data + ".dcm");
                Console.WriteLine($"Writing file {path}...");
                dcm.Write(path);
                return(true); // Lets daemom know if you successfully wrote to drive
            };
            receiver.ListenForIncomingAssociations(true);

            //Build a finder class to help with C-FIND operations
            var finder  = client.GetCFinder(daemon);
            var studies = finder.FindStudies("DA00001");
            var series  = finder.FindSeries(studies);

            //Filter series by modality, then create list of
            var plans = series.Where(s => s.Modality == "RTPLAN")
                        .SelectMany(ser => finder.FindImages(ser));
            var doses = series.Where(s => s.Modality == "RTDOSE")
                        .SelectMany(ser => finder.FindImages(ser));
            var cts = series.Where(s => s.Modality == "CT")
                      .SelectMany(ser => finder.FindImages(ser));

            var    mover = client.GetCMover(daemon);
            ushort msgId = 1;

            foreach (var plan in plans)
            {
                Console.WriteLine($"Sending plan {plan.SOPInstanceUID}...");
                //Make sure Mobius is on the whitelist of the daemon
                var response = mover.SendCMove(plan, local.AeTitle, ref msgId);
                Console.WriteLine($"DICOM C-Move Results : ");
                Console.WriteLine($"Number of Completed Operations : {response.NumberOfCompletedOps}");
                Console.WriteLine($"Number of Failed Operations : {response.NumberOfFailedOps}");
                Console.WriteLine($"Number of Remaining Operations : {response.NumberOfRemainingOps}");
                Console.WriteLine($"Number of Warning Operations : {response.NumberOfWarningOps}");
            }

            Console.Read(); //Stop here
        }
Exemplo n.º 8
0
        public static void Main(string[] args)
        {
            List <IDpair> idPairs = new List <IDpair>();
            var           IDlist  = new List <string>();

            if (args.Length == 1)
            {
                IDlist = args[0].Split(';').ToList();
            }
            else
            {
                throw new Exception("Wrong number of inputs");
            }


            // Split in pairs
            foreach (string line in IDlist)
            {
                idPairs.Add(new IDpair(line));
            }

            // Create all required entities
            //var me = new Entity("EvilDICOMC", "10.0.129.139", 50401);
            //var me = Entity.CreateLocal("DCMGRBC", 51167);
            var me  = Entity.CreateLocal("DCMGRBer", 50400);
            var scu = new DICOMSCU(me);

            //var scp = new DICOMSCP
            Entity   reciever = new Entity(AEtitle, ipadress, port);
            DICOMSCP scp      = new DICOMSCP(reciever);
            //var scpEntity = Entity.CreateLocal("EvilDICOM", 50400);
            //var scpEntity = new Entity("EvilDICOM", "10.0.129.139", 50400);
            //var scp = new FileWriterSCP(scpEntity, outPath);
            //var scp = new DICOMSCP(scpEntity);
            //scp.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
            //scp.ListenForIncomingAssociations(true);
            //var logger = new ConsoleLogger(scp.Logger, ConsoleColor.Red);
            var    qb    = new QueryBuilder(scu, daemon);
            ushort msgId = 1;

            // Loop over ID pairs and pull files from ARIA OIS to finalPath
            foreach (IDpair idPair in idPairs)
            {
                try
                {
                    //qb.SendImage(new EvilDICOM.Network.DIMSE.IOD.CFindImageIOD() { PatientId = idPair.Id, SOPInstanceUID = idPair.Uid }, "EvilDICOM", ref msgId);
                    CFindImageIOD iod = new CFindImageIOD()
                    {
                        PatientId = idPair.Id, SOPInstanceUID = idPair.Uid
                    };
                    scu.SendCMoveImage(daemon, iod, scp.ApplicationEntity.AeTitle, ref msgId);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + "\n" + idPair.Uid);
                }
            }
        }
Exemplo n.º 9
0
        public SelectPlanUI(VMS.TPS.Common.Model.API.Application app, Entity daemon, DICOMSCU scu, FileWriterSCP scp, string path)
        {
            this.app      = app;
            this.daemon   = daemon;
            this.scu      = scu;
            this.scp      = scp;
            this.path     = path;
            this.Location = new Point(0, 0);

            InitializeComponent();

            //textBoxPatId.Text = "QC_Checklista";
        }
        /// <summary>
        /// This tutorial is outlined in chapter 4 of Scripting in RT for Physicists (C-ECHO)
        /// </summary>
        public static void Run()
        {
            //Store the details of the daemon (Ae Title, IP, port)
            var daemon = new Entity("PHYSX_DICOM", "10.22.86.64", 51402);
            //Store the details of the client (Ae Title, port) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal("DICOMEC1", 9999);
            //Set up a client (DICOM SCU = Service Class User)
            var client = new DICOMSCU(local);
            //TRY C-ECHO
            var canPing = client.Ping(daemon);

            //Write results to console
            Console.WriteLine($"DICOM C-Echo from {local.AeTitle} => " +
                              $"{daemon.AeTitle} @{daemon.IpAddress}:{daemon.Port} was successfull? {canPing}");

            Console.Read(); //Stop here
        }
Exemplo n.º 11
0
        public DICOMhandler(string id, string planUID, string doseUID, string tempPath, Entity daemon, DICOMSCU puller, FileWriterSCP catcher, double alphaBeta, double dosePerFraction, int nFractions)
        {
            this.id              = id;
            this.planUID         = planUID;
            this.doseUID         = doseUID;
            this.alphaBeta       = alphaBeta;
            this.dosePerFraction = dosePerFraction;
            this.tempPath        = tempPath;
            this.nFractions      = nFractions;

            this.daemon  = daemon;
            this.puller  = puller;
            this.catcher = catcher;


            this.qb = new QueryBuilder(puller, daemon);
        }
Exemplo n.º 12
0
        public static void Run()
        {
            //Store the details of the daemon (Ae Title, IP, port)
            var daemon = new Entity("PHYSX_DICOM", "10.22.86.64", 51402);
            //Store the details of the mobius DICOM entity (Ae Title, IP, port)
            var mobius = new Entity("MOBIUST", "10.241.20.41", 104);
            //Store the details of the client (Ae Title, port) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal("DICOMEC1", 9999);
            //Set up a client (DICOM SCU = Service Class User)
            var client = new DICOMSCU(local);

            //Build a finder class to help with C-FIND operations
            var finder  = client.GetCFinder(daemon);
            var studies = finder.FindStudies("DA00001");
            var series  = finder.FindSeries(studies);

            //Filter series by modality, then create list of
            var plans = series.Where(s => s.Modality == "RTPLAN")
                        .SelectMany(ser => finder.FindImages(ser));
            var doses = series.Where(s => s.Modality == "RTDOSE")
                        .SelectMany(ser => finder.FindImages(ser));
            var cts = series.Where(s => s.Modality == "CT")
                      .SelectMany(ser => finder.FindImages(ser));

            var    mover = client.GetCMover(daemon);
            ushort msgId = 1;

            foreach (var plan in plans)
            {
                Console.WriteLine($"Sending plan {plan.SOPInstanceUID}...");
                //Make sure Mobius is on the whitelist of the daemon
                var response = mover.SendCMove(plan, mobius.AeTitle, ref msgId);
                Console.WriteLine($"DICOM C-Move Results : ");
                Console.WriteLine($"Number of Completed Operations : {response.NumberOfCompletedOps}");
                Console.WriteLine($"Number of Failed Operations : {response.NumberOfFailedOps}");
                Console.WriteLine($"Number of Remaining Operations : {response.NumberOfRemainingOps}");
                Console.WriteLine($"Number of Warning Operations : {response.NumberOfWarningOps}");
            }

            Console.Read(); //Stop here
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            var scp = new DICOMSCP(Entity.CreateLocal("SCP", 9999));
            ////new ConsoleLogger(scp.Logger);
            //scp.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
            //int i = 1;
            //scp.DIMSEService.CStoreService.CStorePayloadAction = (dcm, asc) =>
            //{
            //    Thread.Sleep(6000);
            //    Assert.AreEqual(dcm.SOPClass, SOPClass.CTImageStorage);
            //    Assert.AreEqual(dcm.PixelStream.Length, 10000);
            //    Assert.AreEqual(dcm.GetSelector().PatientID.Data, "123456");
            //    Console.WriteLine($"Received {i++} files");
            //    return true;
            //};
            //scp.ListenForIncomingAssociations(true);


            var scu = new DICOMSCU(Entity.CreateLocal("SCU", 9998));

            scu.IdleTimeout = 10000;
            ushort msg = 1;

            foreach (var dcm in GenerateDICOMFiles())
            {
                var resp = scu.GetCStorer(scp.ApplicationEntity).SendCStore(dcm, ref msg);
                if (resp == null)
                {
                    Console.WriteLine("SCU Timeout!");
                    break;
                }
                else if (resp.Status == (ushort)Status.FAILURE)
                {
                    Console.WriteLine("No connection");
                    break;
                }
            }
            Console.Read();
        }
Exemplo n.º 14
0
        public EQD2Control(User currentUser, Patient pat, PlanSetup plan, Entity daemon, DICOMSCU scu, FileWriterSCP scp, string tempPath)
        {
            this.tempPath        = tempPath;
            this.currentUser     = currentUser;
            this.patient         = pat;
            this.plan            = plan;
            this.daemon          = daemon;
            this.scu             = scu;
            this.scp             = scp;
            this.totalDose       = Convert.ToDouble(plan.TotalPrescribedDose.ValueAsString);
            this.dosePerFraction = plan.UniqueFractionation.PrescribedDosePerFraction.Dose;
            this.nFractions      = (int)plan.UniqueFractionation.NumberOfFractions;
            this.planUID         = plan.UID;
            this.doseUID         = plan.Dose.UID;

            InitializeComponent();

            // place info
            textBoxPat.Text           = patient.ToString();
            textBoxPlan.Text          = plan.ToString();
            textBoxFractionation.Text = plan.UniqueFractionation.PrescribedDosePerFraction.ToString() + " × " + this.nFractions + " = " + plan.TotalPrescribedDose.ToString();
            textBox1.Text             = alphaBeta.ToString();
        }
Exemplo n.º 15
0
        /// <summary>
        /// This tutorial is outlined in chapter 4 of Scripting in RT for Physicists (C-FIND)
        /// </summary>
        public static void Run()
        {
            //Store the details of the daemon (Ae Title, IP, port)
            var daemon = new Entity("PHYSX_DICOM", "10.22.86.64", 51402);
            //Store the details of the client (Ae Title, port) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal("DICOMEC1", 9999);
            //Set up a client (DICOM SCU = Service Class User)
            var client = new DICOMSCU(local);
            //Build a finder class to help with C-FIND operations
            var finder = client.GetCFinder(daemon);

            var studies = finder.FindStudies("DA00001");
            var series  = finder.FindSeries(studies);
            var images  = finder.FindImages(series);

            //Write results to console
            Console.WriteLine($"DICOM C-Find from {local.AeTitle} => " +
                              $"{daemon.AeTitle} @{daemon.IpAddress}:{daemon.Port}:");
            Console.WriteLine($"{studies.Count()} Studies Found");
            Console.WriteLine($"{series.Count()} Series Found");
            Console.WriteLine($"{images.Count()} Images Found");
            Console.Read(); //Stop here
        }
Exemplo n.º 16
0
 /// <summary>
 /// A Query builder constructor which requires a SCU and SCP entity
 /// </summary>
 /// <param name="scu">The SCU client which will perform the operations and queries</param>
 /// <param name="scp">the SCP which will send the results</param>
 public QueryBuilder(DICOMSCU scu, Entity scp)
 {
     _scu = scu;
     _scp = scp;
 }
Exemplo n.º 17
0
 public CMover(DICOMSCU dICOMSCU, Entity callingEntity)
 {
     this._scu          = dICOMSCU;
     this.callingEntity = callingEntity;
     this._scu.DIMSEService.CMoveResponseReceived += new DIMSEService.DIMSEResponseHandler <CMoveResponse>(this.DIMSEService_CMoveResponseReceived);
 }
        private void runButton_Click(object sender, RoutedEventArgs e)
        {
            // Store the details of the daemon (Ae Title , IP , port )
            var daemon = new Entity(DaemonTitleTextBox.Text, DaemonIpTextBox.Text, int.Parse(DaemonPortTextBox.Text));
            // Store the details of the client (Ae Title , port ) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal(AEtitleTextBox.Text, int.Parse(AEportTextBox.Text));
            // Set up a client ( DICOM SCU = Service Class User )
            var    client = new DICOMSCU(local);
            var    storer = client.GetCStorer(daemon);
            ushort msgId  = 1;

            var canPing = client.Ping(daemon);

            if (canPing)
            {
                echoButton.Background = System.Windows.Media.Brushes.LawnGreen;
                progressBar.Value     = 0;
                runButton.IsEnabled   = false;

                if (!Directory.Exists(outputFolderPath))
                {
                    Directory.CreateDirectory(outputFolderPath);
                }

                runButton.IsEnabled = false;

                string dir         = inputFolderPath;
                var    toAnonymize = Enumerable.Empty <string>();
                if (subDirCheckBox.IsChecked == false)
                {
                    toAnonymize = Directory.GetFiles(dir).Where(f => DumpSingleDicomTag(f, "0008,0060") != "fail" & !Path.GetFileName(f).Contains("_ignore"));
                }
                else
                {
                    toAnonymize = Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Where(f => DumpSingleDicomTag(f, "0008,0060") != "fail" & !Path.GetFileName(f).Contains("_ignore"));
                }
                int np = toAnonymize.Count();
                ShowLogMsg("\nNew import process has started.");
                ShowLogMsg("Number of DICOM files for importing: " + np.ToString() + "\n");

                int  count         = 1;
                bool importSuccess = true;
                foreach (var file in toAnonymize)
                {
                    // Reads DICOM object into memory
                    var dcm      = EvilDICOM.Core.DICOMObject.Read(file);
                    var response = storer.SendCStore(dcm, ref msgId);
                    // Write results to console
                    //await Task.Run(() => ShowLogMsg($" DICOM C-Store of {Path.GetFileName(file)} from { local.AeTitle } => { daemon.AeTitle } {(EvilDICOM.Network.Enums.Status)response.Status }"));

                    progressBar.Value      = count * 100 / np;
                    ProgressTextBlock.Text = "Import in progress....";

                    count++;
                }

                if (importSuccess == true)
                {
                    ShowLogMsg("\nImport completed successfully.");
                    ShowLogMsg("");
                    ProgressTextBlock.Text = "Import completed successfully";
                    progressBar.Value      = 100;
                }
                else
                {
                    ShowLogMsg("\nImport completed with Erros.");
                    ShowLogMsg("");
                    ProgressTextBlock.Text = "Import completed with Errors";
                    progressBar.Value      = 100;
                }


                runButton.IsEnabled = true;
            }
            else
            {
                echoButton.Background = System.Windows.Media.Brushes.PaleVioletRed;
                ShowLogMsg("\nNo import is possible. Echo to Daemon failed.");
                ProgressTextBlock.Text = "Echo failed. No Import was done.";
            }
        }
Exemplo n.º 19
0
 public QueryBuider(DICOMSCU scu, Entity scp)
 {
     _scu = scu;
     _scp = scp;
 }
Exemplo n.º 20
0
        static int Execute(MainSettings settings)
        {
            // start by sending mail
            sendMail.Program.send(settings.MAILTO, "MIQA_xBot initiated", "Export to MIQA will begin now.", settings.MAIL_USER, settings.MAIL_DOMAIN, settings.SMTP_SERVER);

            List <CFindImageIOD> iods = new List <CFindImageIOD>();
            Entity daemon             = Entity.CreateLocal(settings.DBDAEMON_AETITLE, settings.DBDAEMON_PORT);

            // define the local service class
            var me  = Entity.CreateLocal(settings.SCU_AETITLE, settings.SCU_PORT);
            var scu = new DICOMSCU(me);

            // define the query builder
            var    qb    = new QueryBuilder(scu, daemon);
            ushort msgId = 1;

            // read the xml file
            string xml   = File.ReadAllText(settings.XporterPath);
            Xports xPort = xml.ParseXML <Xports>();

            // define the recievr
            //Entity reciever = new Entity(xPort.Xporter.AEtitle, getIP(xPort.Xporter.ipstring), xPort.Xporter.port);
            Entity   reciever = new Entity(xPort.Xporter.AEtitle, xPort.Xporter.getIP(), xPort.Xporter.port);
            DICOMSCP scp      = new DICOMSCP(reciever);

            // Query plan
            DataTable plans = new DataTable();

            if (!String.IsNullOrEmpty(xPort.Xporter.SQLstring))
            {
                SqlInterface.Connect(settings);
                plans = xPort.Query(settings.LAG_DAYS);
                SqlInterface.Disconnect();
            }

            // loop through plans
            foreach (DataRow row in plans.Rows)
            {
                var patId   = (string)row["PatientId"];
                var planUID = (string)row["UID"];
                iods.Add(new CFindImageIOD()
                {
                    PatientId = patId, SOPInstanceUID = planUID
                });
                // loop through items and query based on type
                foreach (string item in xPort.Xporter.include.ToList())
                {
                    string itemSqlString = string.Empty;
                    switch (item)
                    {
                    case "planDose":
                        itemSqlString = "select distinct UID = DoseMatrix.DoseUID from DoseMatrix where DoseMatrix.PlanSetupSer = " + (Int64)row["PlanSer"];
                        break;

                    case "fieldDoses":
                        itemSqlString = "select distinct UID = DoseMatrix.DoseUID from DoseMatrix, Radiation where Radiation.PlanSetupSer = " + (Int64)row["PlanSer"] + " and DoseMatrix.RadiationSer = Radiation.RadiationSer";
                        break;

                    case "slices":
                        itemSqlString = "select UID=Slice.SliceUID from Slice, Image, StructureSet, PlanSetup where PlanSetup.PlanSetupSer=" + (Int64)row["PlanSer"] + " and StructureSet.StructureSetSer=PlanSetup.StructureSetSer and Image.ImageSer=StructureSet.ImageSer and Slice.SeriesSer=Image.SeriesSer";
                        break;

                    case "structures":
                        itemSqlString = "select UID=StructureSet.StructureSetUID from PlanSetup, StructureSet where PlanSetup.PlanSetupSer=" + (Int64)row["PlanSer"] + " and StructureSet.StructureSetSer=PlanSetup.StructureSetSer";
                        break;

                    case "images":
                        itemSqlString = "select UID=Slice.SliceUID from Slice, ImageSlice, Radiation where Radiation.PlanSetupSer = " + (Int64)row["PlanSer"] + " and ImageSlice.ImageSer = Radiation.RefImageSer and Slice.SliceSer = ImageSlice.SliceSer";
                        break;

                    case "records":
                        itemSqlString = "select UID=TreatmentRecord.TreatmentRecordUID from TreatmentRecord, RTPlan where RTPlan.PlanSetupSer= " + (Int64)row["PlanSer"] + " and TreatmentRecord.RTPlanSer=RTPlan.RTPlanSer";
                        break;

                    default:
                        itemSqlString = String.Empty;
                        break;
                    }
                    if (!String.IsNullOrEmpty(itemSqlString))
                    {
                        DataTable includeItem = SqlInterface.Query(itemSqlString);
                        foreach (DataRow itemRow in includeItem.Rows)
                        {
                            iods.Add(new CFindImageIOD()
                            {
                                PatientId = patId, SOPInstanceUID = (string)itemRow["UID"]
                            });
                        }
                    }
                }
            }

            if (xPort.Xporter.active)
            {
                Console.WriteLine(iods.Count.ToString());
                // Remove duplicate UIDs
                if (!xPort.Xporter.allowDoublets)
                {
                    iods = ListHandler.Unique(iods);
                }

                Console.WriteLine(iods.Count.ToString());
                foreach (var iod in iods)
                {
                    // Send it
                    scu.SendCMoveImage(daemon, iod, xPort.Xporter.AEtitle, ref msgId);
                    // We need this to pump messages in debugging
                    Console.WriteLine(iod.SOPInstanceUID.ToString());
                }
            }

            // overwrite lastActivity
            if (plans.Rows.Count > 0)
            {
                // Get last date encountered
                DateTime lastPlan = (DateTime)plans.Rows[plans.Rows.Count - 1]["MAXDate"];
                xPort.Xporter.lastActivity = lastPlan.ToString("yyyy-MM-dd");

                // write xml
                using (FileStream fs = new FileStream(settings.XporterPath, FileMode.Create))
                {
                    XmlSerializer _xSer = new XmlSerializer(typeof(Xports));

                    _xSer.Serialize(fs, xPort);
                }
            }
            if (xPort.Xporter.active)
            {
                return(plans.Rows.Count);
            }
            else
            {
                return(0);
            }
        }
Exemplo n.º 21
0
        static void Execute()
        {
            List <CFindImageIOD> iods = new List <CFindImageIOD>();
            // define the DB Deamon entity
            Entity daemon = Entity.CreateLocal(AEtitleDB, portDB);

            // define the local service class
            var me  = Entity.CreateLocal("EvilDICOMC", 50400);
            var scu = new DICOMSCU(me);

            // define the query builder
            var    qb    = new QueryBuilder(scu, daemon);
            ushort msgId = 1;

            // xml Deserialize
            string xml   = File.ReadAllText(Settings.xPorterPath);
            var    xport = xml.ParseXML <xports>();

            // Define the reciever
            Entity   reciever = new Entity(xport.xporter.AEtitle, xport.xporter.ipstring, xport.xporter.port);
            DICOMSCP scp      = new DICOMSCP(reciever);

            // Query plan
            DataTable plans = new DataTable();

            if (!String.IsNullOrEmpty(xport.xporter.SQLstring))
            {
                SqlInterface.Connect();
                plans = xport.Query();
                SqlInterface.Disconnect();
            }

            // loop through plans
            foreach (DataRow row in plans.Rows)
            {
                var patId = ((string)row["PatientId"]);
                // Remove special characters from patId
                byte[] patIdBytes;
                patIdBytes = Encoding.GetEncoding("ISO-8859-8").GetBytes(patId);
                patId      = Encoding.UTF8.GetString(patIdBytes);
                var    ImageUID = (string)row["ImageUID"];
                var    RefUID   = (string)row["RefUID"];
                double MU       = (double)row["MU"];

                iods.Add(new CFindImageIOD()
                {
                    PatientId = patId, SOPInstanceUID = ImageUID
                });
                iods.Add(new CFindImageIOD()
                {
                    PatientId = patId, SOPInstanceUID = RefUID
                });

                if (xport.xporter.active)
                {
                    // Generate linking text file
                    string[] content = { ImageUID, RefUID, MU.ToString(), Settings.DoseCrit, Settings.DistCrit, Settings.DoseThreshold, Settings.LocalDose, Settings.AcceptCrit };
                    File.WriteAllLines(ImageUID + ".dat", content);

                    // SFTP it
                    SFTP.Send(ImageUID + ".dat");

                    // Delte file
                    File.Delete(ImageUID + ".dat");
                }
            }


            // change lastActivity
            if (plans.Rows.Count > 0)
            {
                DateTime lastPlan = (DateTime)plans.Rows[plans.Rows.Count - 1]["DateTime"];
                xport.xporter.lastActivity = lastPlan.ToString("yyyy-MM-dd HH:mm:ss.fff");
                // write xml
                using (FileStream fs = new FileStream(Settings.xPorterPath, FileMode.Create))
                {
                    XmlSerializer _xSer = new XmlSerializer(typeof(xports));

                    _xSer.Serialize(fs, xport);
                }
            }

            // if active send
            if (xport.xporter.active)
            {
                Console.WriteLine(iods.Count.ToString());
                // Remove duplicate UIDs
                if (!xport.xporter.allowDoublets)
                {
                    iods = ListHandler.Unique(iods);
                }

                Console.WriteLine(iods.Count.ToString());
                foreach (var iod in iods)
                {
                    // Send it
                    scu.SendCMoveImage(daemon, iod, xport.xporter.AEtitle, ref msgId);
                    // Add logging

                    // verify file recieved
                    var recieved = SFTP.Verify("RI." + iod.SOPInstanceUID + ".dcm");
                    if (!recieved)
                    {
                        throw new FileNotFoundException("CMove Operation not verified.");
                    }
                }
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// A Query builder constructor which requires a SCU and SCP entity
 /// </summary>
 /// <param name="scu">The SCU client which will perform the operations and queries</param>
 /// <param name="scp">the SCP which will send the results</param>
 public CFinder(DICOMSCU scu, Entity scp)
 {
     _scu = scu;
     _scp = scp;
 }
Exemplo n.º 23
0
 public StorageVerifier(DICOMSCU dICOMSCU, Entity callingEntity)
 {
     this._scu          = dICOMSCU;
     this.callingEntity = callingEntity;
 }
Exemplo n.º 24
0
        static void Execute(vapi.Application app, Entity daemon, DICOMSCU scu, FileWriterSCP scp, string path)
        {
            SelectPlanUI selectPlanUI = new SelectPlanUI(app, daemon, scu, scp, path);

            selectPlanUI.ShowDialog();
        }
Exemplo n.º 25
0
 public CStorer(DICOMSCU dICOMSCU, Entity callingEntity)
 {
     this._scu          = dICOMSCU;
     this.callingEntity = callingEntity;
 }
Exemplo n.º 26
0
        protected override void OnStartup(StartupEventArgs e)
        {
            // Store the details of the daemon (Ae Title , IP , port )
            var daemon = new Entity("VMSDBD1", "192.168.1.11", 5678);
            // Store the details of the client (Ae Title , port ) -> IP address is determined by CreateLocal() method
            var local = Entity.CreateLocal("DICOMEC1", 5681);
            // Set up a client ( DICOM SCU = Service Class User )
            var client = new DICOMSCU(local);
            // Set up a receiver to catch the files as they come in
            var receiver = new DICOMSCP(local);

            // Let the daemon know we can take anything it sends
            receiver.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
            // Set up storage location
            var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var storagePath = Path.Combine(desktopPath, "DICOM Storage");

            Directory.CreateDirectory(storagePath);
            // Set the action when a DICOM files comes in
            receiver.DIMSEService.CStoreService.CStorePayloadAction = (dcm, asc) =>
            {
                var path = Path.Combine(storagePath, dcm.GetSelector().
                                        SOPInstanceUID.Data + ".dcm");
                Console.WriteLine($"Writing file { path }... ");
                dcm.Write(path);
                return(true);
            };
            receiver.ListenForIncomingAssociations(true);

            // Build a finder class to help with C- FIND operations
            var finder  = client.GetCFinder(daemon);
            var studies = finder.FindStudies("US-EC-020");
            var series  = finder.FindSeries(studies);
            // Filter series by modality , then create list of
            //we're not finding any studies - why?
            var    plans = series.Where(s => s.Modality == "RTPLAN").SelectMany(ser => finder.FindImages(ser));
            var    doses = series.Where(s => s.Modality == "RTDOSE").SelectMany(ser => finder.FindImages(ser));
            var    cts   = series.Where(s => s.Modality == "CT").SelectMany(ser => finder.FindImages(ser));
            var    mover = client.GetCMover(daemon);
            ushort msgId = 1;

            foreach (var plan in plans)
            {
                Console.WriteLine($"Sending plan { plan.SOPInstanceUID }... ");
                // Make sure Mobius is on the whitelist of the daemon
                var response = mover.SendCMove(plan, local.AeTitle, ref msgId);
                Console.WriteLine($"DICOM  CMove Results: ");
                Console.WriteLine($"Number of Completed Operations: { response.NumberOfCompletedOps }");
                Console.WriteLine($"Number of Failed Operations: { response.NumberOfFailedOps }");
                Console.WriteLine($"Number of Remaining Operations: { response.NumberOfRemainingOps}");
                Console.WriteLine($"Number of Warning Operations: { response.NumberOfWarningOps}");
            }
            Console.Read();
            // Stop here

            //var myEntity = new Entity("VMSDBD1","192.168.1.11",5678);

            //var scp = new DICOMSCP(myEntity);
            //scp.ListenForIncomingAssociations(keepListenerRunning: true);

            //var en1 = Entity.CreateLocal("EvilDICOM", "666");
            //var scu = new DICOMSCU(en1);


            ////USING EVILDICOM
            ////var localEntity = new Entity("DCMTK")
            //var daemon = new Entity("VarianDaemon", "192.168.1.11", 5678);
            ////var client = new DICOMSCP();
            //var client = new DICOMSCU(Entity.CreateLocal("MyEntity", 9999));

            //var finder = client.GetCFinder(daemon);
            //var studies = finder.FindStudies("PATIENTID");
            //var series = finder.FindSeries(studies);
            ////var series = finder.FindSeries(studies).Where(s=>s.Modality=="REG");

            //var mover = client.GetCMover(daemon);
            //mover.SendCMove(series.First(),daemon.AeTitle)
            //var records = finder.FindRTRecords(series);
            //ecords.First().TreatmentDate

            //UNCOMMENT FOR OUR EXAMPLE PLANCHECKER
            //string[] args = e.Args;
            //base.OnStartup(e);
            //var bs = new AppBootstrapper<MainView>(() => { return VMS.TPS.Common.Model.API.Application.CreateApplication(); });
            ////You can use the following to load a context (for debugging purposes)
            ////args = ContextIO.ReadArgsFromFile(@"C: \Users\cwalker\Desktop\context.txt");
            ////Might disable (uncomment) for plugin mode
            //bs.IsPatientSelectionEnabled = false;
            //bs.Run(args);
        }