Exemple #1
0
 public async Task Start()
 {
     _listenTask = Task.Run(() =>
     {
         _listener = _listener ?? new DICOMSCP(_entity);
         _listener.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
         _listener.DIMSEService.CStoreService.CStorePayloadAction = (dcm, asc) =>
         {
             if (!_tokenSource.Token.IsCancellationRequested)
             {
                 var id      = dcm.GetSelector().PatientID.Data;
                 string path = OrganizeByPatientId?
                               Path.Combine(_storagePath, id, dcm.GetSelector().SOPInstanceUID.Data + ".dcm"):
                               Path.Combine(_storagePath, dcm.GetSelector().SOPInstanceUID.Data + ".dcm");
                 var dir = Path.GetDirectoryName(path);
                 System.IO.Directory.CreateDirectory(dir);
                 dcm.Write(path);
                 return(true);
             }
             return(false);
         };
         _listener.ListenForIncomingAssociations(true);
     }, _tokenSource.Token);
     await _listenTask;
 }
Exemple #2
0
        public void SendImage(ImageResult ir, DICOMSCP reciever)
        {
            AutoResetEvent ar    = new AutoResetEvent(false);
            var            query = new CMoveIOD()
            {
                QueryLevel     = QueryLevel.IMAGE,
                PatientId      = ir.PatientId,
                SOPInstanceUID = ir.SopInstanceUid
            };

            if (ir.SeriesUid != null)
            {
                query.SeriesInstanceUID = ir.SeriesUid;
            }

            if (!reciever.IsListening)
            {
                reciever.ListenForIncomingAssociations(true);
            }

            ManualResetEvent mr = new ManualResetEvent(false);
            var cr = new EvilDICOM.Network.Services.DIMSEService.DIMSEResponseHandler <CMoveResponse>((res, asc) =>
            {
                if (!(res.Status == (ushort)Status.PENDING))
                {
                    mr.Set();
                }
            });

            _scu.DIMSEService.CMoveResponseReceived += cr;
            _scu.SendMessage(new CMoveRequest(query, reciever.ApplicationEntity.AeTitle), _scp);
            mr.WaitOne();
            _scu.DIMSEService.CMoveResponseReceived -= cr;
        }
Exemple #3
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
        }
        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);
                }
            }
        }
Exemple #5
0
        static void Main(string[] args)
        {
            var scp = new DICOMSCP(Entity.CreateLocal("SCP", 9999));

            new ConsoleLogger(scp.Logger);
            scp.SupportedAbstractSyntaxes = AbstractSyntax.ALL_RADIOTHERAPY_STORAGE;
            scp.DIMSEService.CStoreService.CStorePayloadAction = (dcm, asc) =>
            {
                return(true);
            };
            scp.ListenForIncomingAssociations(true);
            Console.Read();
        }
Exemple #6
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();
        }
Exemple #7
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);
            }
        }
Exemple #8
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.");
                    }
                }
            }
        }
Exemple #9
0
        public void SendImage(ImageResult ir, DICOMSCP reciever)
        {
            AutoResetEvent ar = new AutoResetEvent(false);
            var query = new CMoveIOD()
            {
                QueryLevel = QueryLevel.IMAGE,
                PatientId = ir.PatientId,
                SOPInstanceUID = ir.SopInstanceUid
            };
            if (ir.SeriesUid != null) { query.SeriesInstanceUID = ir.SeriesUid; }

            if (!reciever.IsListening) { reciever.ListenForIncomingAssociations(true); }

            ManualResetEvent mr = new ManualResetEvent(false);
            var cr = new EvilDICOM.Network.Services.DIMSEService.DIMSEResponseHandler<CMoveResponse>((res, asc) =>
            {
                if (!(res.Status == (ushort)Status.PENDING))
                {
                    mr.Set();
                }
            });

            _scu.DIMSEService.CMoveResponseReceived += cr;
            _scu.SendMessage(new CMoveRequest(query, reciever.ApplicationEntity.AeTitle), _scp);
            mr.WaitOne();
            _scu.DIMSEService.CMoveResponseReceived -= cr;
        }
Exemple #10
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);
        }