Esempio n. 1
0
 public static void MultiFrameProcess(DbStudy study)
 {
     string dcmPath = ADCM.GetStoreString();
     var seriesList = Directory.GetDirectories(Path.Combine(dcmPath, study.study_uid));
     foreach (var sePath in seriesList)
     {
         var filesList = Directory.GetFiles(sePath, "*.dcm");
         if (filesList.Length < 2)
             continue;
         for (int i = 0; i < filesList.Length; i++)
         {
             var dcm = new DicomFile(filesList[i]);
             dcm.Load();
             int frameCount = dcm.DataSet[DicomTags.NumberOfFrames].GetInt16(0, 0);                
             if (frameCount > 1)
             {
                 string newSeriesUID = sePath + "." + i;
                 newSeriesUID = newSeriesUID.Substring(newSeriesUID.LastIndexOf(Path.DirectorySeparatorChar) + 1);
                 string newSeriesPath = Path.Combine(dcmPath, study.study_uid, newSeriesUID);
                 Directory.CreateDirectory(newSeriesPath);
                 string fileName = Path.GetFileName(filesList[i]);
                 string oldPath = filesList[i];
                 string newPath = Path.Combine(newSeriesPath, fileName);
                 File.Move(filesList[i], Path.Combine(newSeriesPath, fileName));
             }
         }                        
     }
     foreach (string sePath in seriesList)
     {
         var filesCount = Directory.GetFiles(sePath);
         if (filesCount.Length < 1)
             Directory.Delete(sePath);
     }
 }
Esempio n. 2
0
    public static void OptiPng(DbStudy study)
    {
        string dcmPath = ADCM.GetStoreString();

        foreach (var ser in study.series)
        {
            string outputPath = Path.Combine(dcmPath, "OUTPUT", study.case_id, study.study_uid, ser.series_uid);
            if (Directory.Exists(outputPath))
            {
                var pngs = Directory.GetFiles(outputPath, "*.png");
                if (pngs == null || pngs.Length < 1)
                {
                    continue;
                }
                foreach (var f in pngs)
                {
                    if (File.Exists(@".\OptiPNG\optipng.exe"))
                    {
                        // Run OPTIPNG with level 7 compression.
                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                        info.FileName    = @".\OptiPNG\optipng.exe";
                        info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                        info.Arguments   = "\"" + f + "\"";

                        // Use Process for the application.
                        using (System.Diagnostics.Process exe = System.Diagnostics.Process.Start(info))
                        {
                            exe.WaitForExit();
                        }
                    }
                }
            }
        }
    }
Esempio n. 3
0
 public static bool ZipSeries(DbStudy study)
 {
     try
     {
         string scpPath    = ADCM.GetStoreString();
         string outputPath = Path.Combine(scpPath, "OUTPUT", study.case_id, study.study_uid);
         if (!Directory.Exists(outputPath))
         {
             throw new Exception("Output path not found: " + outputPath);
         }
         var seriesPaths = Directory.GetDirectories(outputPath);
         foreach (var s in seriesPaths)
         {
             //ReorderImages(s);
             var    seriesUID = s.Substring(s.LastIndexOf(Path.DirectorySeparatorChar) + 1);
             string zipPath   = Path.Combine(outputPath, seriesUID + ".zip");
             using (ZipFile zip = new ZipFile())
             {
                 zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                 zip.AddDirectory(s);
                 zip.Save(zipPath);
             }
             FileInfo zipInfo   = new FileInfo(zipPath);
             double   megabytes = Math.Round((zipInfo.Length / 1024f) / 1024f, 2);
             LOG.Write("Zip created: " + zipInfo.Name + ", " + megabytes + " MB");
             LOG.InsertEvent("Zip created: " + zipInfo.Name + " - " + megabytes + "MB", "IMG", null, study.case_id, study.study_uid, seriesUID);
             System.Threading.Thread.Sleep(500);
         }
         LOG.InsertEvent("Successfully created ZIP files for all series in study", "IMG", null, study.case_id, study.study_uid);
         return(true);
     }
     catch (Exception ex)
     {
         string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
         LOG.Write(errorString);
         LOG.Write(ex.Message);
         LOG.InsertEvent(errorString, "IMG", ex.Message, study.case_id, study.study_uid);
         return(false);
     }
 }
Esempio n. 4
0
    public static void MultiFrameProcess(DbStudy study)
    {
        string dcmPath    = ADCM.GetStoreString();
        var    seriesList = Directory.GetDirectories(Path.Combine(dcmPath, study.study_uid));

        foreach (var sePath in seriesList)
        {
            var filesList = Directory.GetFiles(sePath, "*.dcm");
            if (filesList.Length < 2)
            {
                continue;
            }
            for (int i = 0; i < filesList.Length; i++)
            {
                var dcm = new DicomFile(filesList[i]);
                dcm.Load();
                int frameCount = dcm.DataSet[DicomTags.NumberOfFrames].GetInt16(0, 0);
                if (frameCount > 1)
                {
                    string newSeriesUID = sePath + "." + i;
                    newSeriesUID = newSeriesUID.Substring(newSeriesUID.LastIndexOf(Path.DirectorySeparatorChar) + 1);
                    string newSeriesPath = Path.Combine(dcmPath, study.study_uid, newSeriesUID);
                    Directory.CreateDirectory(newSeriesPath);
                    string fileName = Path.GetFileName(filesList[i]);
                    string oldPath  = filesList[i];
                    string newPath  = Path.Combine(newSeriesPath, fileName);
                    File.Move(filesList[i], Path.Combine(newSeriesPath, fileName));
                }
            }
        }
        foreach (string sePath in seriesList)
        {
            var filesCount = Directory.GetFiles(sePath);
            if (filesCount.Length < 1)
            {
                Directory.Delete(sePath);
            }
        }
    }
Esempio n. 5
0
    public static bool DownloadStudy(DbStudy study, int retryCount = 0)
    {
        foreach (var se in study.series)
        {
            bool success = DownloadOneSeries(study.study_uid, se.series_uid);
            if (!success)
            {
                return(false);
            }
        }
        return(true);

        //LOG.Write(string.Format("Downloading study [{0}] - {1} ({2})", study.modality, study.description, study.images));
        //LOG.Write("Retry Count: " + retryCount);
        //var node = GetSelectedNode();
        //var cstore = new DicomSCP(node.LocalAe, 104);

        //StudyRootFindScu findScu = new StudyRootFindScu();
        //StudyQueryIod queryMessage = new StudyQueryIod();
        //queryMessage.SetCommonTags();
        //queryMessage.StudyInstanceUid = study.study_uid;
        //IList<StudyQueryIod> results = findScu.Find(node.LocalAe, node.AET, node.IP, node.Port, queryMessage);
        //if (results.Count != 1)
        //    throw new Exception(string.Format("Unable to query study on PACS: [{0}]", study.study_uid));

        //if (!System.IO.Directory.Exists(node.LocalStorage))
        //    System.IO.Directory.CreateDirectory(node.LocalStorage);
        //cstore.Start();
        //while (!cstore.IsRunning)
        //    System.Threading.Thread.Sleep(1000);
        //string singleSeriesOnly = System.Configuration.ConfigurationManager.AppSettings["singleSeries"];

        //MoveScuBase moveScu = new StudyRootMoveScu(node.LocalAe, node.AET, node.IP, node.Port, node.LocalAe);
        //moveScu.ReadTimeout = 600000;
        //moveScu.WriteTimeout = 600000;
        //moveScu.AddStudyInstanceUid(study.study_uid);
        //foreach (var se in study.series)
        //{
        //    moveScu.AddSeriesInstanceUid(se.series_uid);
        //    System.Diagnostics.Debug.WriteLine(se.series_uid);
        //}
        //moveScu.Move();
        //System.Threading.Thread.Sleep(2000);
        //if (moveScu.Status == ScuOperationStatus.AssociationRejected || moveScu.Status == ScuOperationStatus.Canceled ||
        //    moveScu.Status == ScuOperationStatus.ConnectFailed || moveScu.Status == ScuOperationStatus.Failed ||
        //    moveScu.Status == ScuOperationStatus.NetworkError || moveScu.Status == ScuOperationStatus.TimeoutExpired ||
        //    moveScu.Status == ScuOperationStatus.UnexpectedMessage || moveScu.FailureSubOperations != 0)
        //{
        //    if (retryCount > 4)
        //        throw new Exception(string.Format("Failed moving study [{0}] | Status : {1} | Failed Operations: {2}", study.study_uid, moveScu.Status, moveScu.FailureSubOperations));
        //    retryCount += 1;
        //    if (cstore.IsRunning)
        //        cstore.Stop();
        //    DownloadStudy(study, retryCount);
        //}
        //else
        //{
        //    System.Threading.Thread.Sleep(2000);
        //    cstore.Stop();
        //}
        //if (cstore.IsRunning)
        //    cstore.Stop();
        //LOG.InsertEvent("Successfully downloaded study: " + study.description, "DICOM", null, study.case_id, study.study_uid);
        //return true;

        try
        {
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "DICOM", ex.Message, study.case_id, study.study_uid);
            return(false);
        }
    }
Esempio n. 6
0
    public static bool ConvertDcmToPng(DbStudy study)
    {
        try
        {
            string dcmPath   = ADCM.GetStoreString();
            string studyPath = Path.Combine(dcmPath, study.study_uid);
            if (!Directory.Exists(studyPath))
            {
                throw new Exception("Study path not found");
            }
            var allSeriesPaths = Directory.GetDirectories(studyPath);
            if (allSeriesPaths.Length < 1)
            {
                throw new Exception("No series subdirectories");
            }

            foreach (var s in allSeriesPaths)
            {
                var dcmFiles = Directory.GetFiles(s, "*.dcm");
                if (dcmFiles.Length < 1)
                {
                    throw new Exception("No DCM files inside series path: " + s);
                }
                DicomFile tempdcm = new DicomFile(dcmFiles[0]);
                tempdcm.Load();
                var seriesName = tempdcm.DataSet[DicomTags.SeriesDescription].GetString(0, null);
                var seriesUID  = s.Substring(s.LastIndexOf(Path.DirectorySeparatorChar) + 1);
                if (string.IsNullOrEmpty(seriesName))
                {
                    seriesName = "Unamed_Series";
                }

                APetaPoco.SetConnectionString("cn1");
                var      bm       = APetaPoco.PpRetrieveOne <DbSeries>("Series", "[case_id] = '" + study.case_id + "' AND [series_uid] = '" + seriesUID + "'");
                DbSeries dbseries = null;
                if (bm.Success)
                {
                    dbseries = (DbSeries)bm.Data;
                }

                string outputPath = Path.Combine(dcmPath, "OUTPUT", study.case_id, study.study_uid, seriesUID);
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }

                //int fileCount = 0;

                for (int k = 0; k < dcmFiles.Length; k++)
                {
                    DicomFile dcmFile = new DicomFile(dcmFiles[k]);
                    dcmFile.Load();
                    int fileCount   = 0;
                    var windowWidth = dcmFile.DataSet[DicomTags.WindowWidth].ToString();
                    if (!string.IsNullOrEmpty(windowWidth))
                    {
                        var tempSplitString = windowWidth.Split('\\');
                        windowWidth = tempSplitString[0];
                    }
                    var windowCenter = dcmFile.DataSet[DicomTags.WindowCenter].ToString();
                    if (!string.IsNullOrEmpty(windowCenter))
                    {
                        var tempSplitString = windowCenter.Split('\\');
                        windowCenter = tempSplitString[0];
                    }
                    var ww = dcmFile.DataSet[DicomTags.WindowWidth].GetFloat32(0, 0);
                    var wc = dcmFile.DataSet[DicomTags.WindowCenter].GetFloat32(0, 0);

                    if (ww == 0 && !string.IsNullOrEmpty(windowWidth))
                    {
                        if (windowWidth.Contains("."))
                        {
                            var tempSplitString = windowWidth.Split('.');
                            ww = int.Parse(tempSplitString[0]);
                        }
                        else
                        {
                            ww = int.Parse(windowWidth);
                        }
                    }
                    if (wc == 0 && !string.IsNullOrEmpty(windowCenter))
                    {
                        if (windowCenter.Contains("."))
                        {
                            var tempSplitString = windowCenter.Split('.');
                            wc = int.Parse(tempSplitString[0]);
                        }
                        else
                        {
                            wc = int.Parse(windowCenter);
                        }
                    }

                    LocalSopDataSource localds = new LocalSopDataSource(dcmFile);
                    if (!localds.IsImage)
                    {
                        continue;
                    }
                    ImageSop sop        = new ImageSop(localds);
                    int      frameCount = sop.Frames.Count;
                    var      fileName   = dcmFile.DataSet[DicomTags.InstanceNumber].GetInt16(0, 0);
                    if (frameCount > 1)
                    {
                        for (int j = 1; j <= frameCount; j++)
                        {
                            GC.Collect();
                            Frame  f       = sop.Frames[j];
                            var    jpgPath = Path.Combine(outputPath, fileName + "." + j + ".png");
                            Bitmap bmp     = null;
                            if (string.IsNullOrEmpty(windowWidth) || string.IsNullOrEmpty(windowCenter))
                            {
                                bmp = DrawDefaultFrame(f);
                            }
                            else
                            {
                                bmp = DrawLutFrame(f, ww, wc);
                            }
                            if (bmp != null)
                            {
                                if (dbseries != null && dbseries.crop_h != null &&
                                    dbseries.crop_w != null &&
                                    dbseries.crop_x != null &&
                                    dbseries.crop_y != null)
                                {
                                    bmp = Crop(bmp, dbseries.crop_x.Value, dbseries.crop_y.Value, dbseries.crop_w.Value, dbseries.crop_h.Value);
                                }
                                SaveImage(bmp, jpgPath);
                            }
                            fileCount += 1;
                            GC.Collect();
                        }
                    }
                    else
                    {
                        GC.Collect();
                        var    jpgPath = Path.Combine(outputPath, fileName + ".png");
                        Frame  f       = sop.Frames[1];
                        Bitmap bmp     = null;
                        if (string.IsNullOrEmpty(windowWidth) || string.IsNullOrEmpty(windowCenter))
                        {
                            bmp = DrawDefaultFrame(f);
                        }
                        else
                        {
                            bmp = DrawLutFrame(f, ww, wc);
                        }
                        if (bmp != null)
                        {
                            if (dbseries != null && dbseries.crop_h != null &&
                                dbseries.crop_w != null &&
                                dbseries.crop_x != null &&
                                dbseries.crop_y != null)
                            {
                                bmp = Crop(bmp, dbseries.crop_x.Value, dbseries.crop_y.Value, dbseries.crop_w.Value, dbseries.crop_h.Value);
                            }
                            SaveImage(bmp, jpgPath);
                        }
                        fileCount += 1;
                        GC.Collect();
                    }
                }
            }
            LOG.InsertEvent("Successfully converted study from DCM to PNG", "IMG", null, study.case_id, study.study_uid);
            return(true);
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "IMG", ex.Message, study.case_id, study.study_uid);
            return(false);
        }
    }
Esempio n. 7
0
    public static void DeleteExcessImages(DbStudy study)
    {
        try
        {
            string dcmPath    = ADCM.GetStoreString();
            string outputPath = Path.Combine(dcmPath, "OUTPUT", study.case_id, study.study_uid);
            if (!Directory.Exists(outputPath))
            {
                throw new Exception("No output path found: " + outputPath);
            }
            foreach (var ser in study.series)
            {
                string serPath = Path.Combine(outputPath, ser.series_uid);
                if (Directory.Exists(serPath))
                {
                    var sortedList = Directory.GetFiles(serPath, "*.png").OrderBy(f => int.Parse(Path.GetFileNameWithoutExtension(f))).ToList();
                    if (sortedList.Count > ser.images)
                    {
                        int start    = 1;
                        int end      = ser.images;
                        int stepping = 1;
                        if (ser.start_image != null && ser.start_image > 0)
                        {
                            start = ser.start_image.Value;
                        }
                        if (ser.end_image != null && ser.end_image > 0)
                        {
                            end = ser.end_image.Value;
                        }
                        if (end > sortedList.Count)
                        {
                            end = sortedList.Count;
                        }
                        if (ser.every_image != null && ser.every_image > 0)
                        {
                            stepping = ser.every_image.Value;
                        }

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

                        LOG.Write(string.Format("Start: {0}| End: {1}| Stepping: {2}", start, end, stepping));

                        for (int i = start - 1; i < end; i += stepping)
                        {
                            //LOG.Write(string.Format("[{0}] Keeping {1}", i, sortedList[i]));
                            keepPaths.Add(sortedList[i]);
                        }

                        foreach (var f in sortedList)
                        {
                            if (!keepPaths.Contains(f))
                            {
                                //LOG.Write(string.Format("Deleting {0}", f));
                                File.Delete(f);
                            }
                        }
                    }
                }
                else
                {
                    LOG.Write("No series path: " + serPath);
                }
            }
        }
        catch (Exception ex)
        {
            LOG.Write(ex.Message);
        }
    }
Esempio n. 8
0
    public static bool DownloadStudy(DbStudy study, int retryCount = 0)
    {
        foreach(var se in study.series)
        {
            bool success = DownloadOneSeries(study.study_uid, se.series_uid);
            if (!success) { return false; }            
        }
        return true;
        //LOG.Write(string.Format("Downloading study [{0}] - {1} ({2})", study.modality, study.description, study.images));
        //LOG.Write("Retry Count: " + retryCount);
        //var node = GetSelectedNode();        
        //var cstore = new DicomSCP(node.LocalAe, 104);

        //StudyRootFindScu findScu = new StudyRootFindScu();
        //StudyQueryIod queryMessage = new StudyQueryIod();
        //queryMessage.SetCommonTags();
        //queryMessage.StudyInstanceUid = study.study_uid;
        //IList<StudyQueryIod> results = findScu.Find(node.LocalAe, node.AET, node.IP, node.Port, queryMessage);
        //if (results.Count != 1)
        //    throw new Exception(string.Format("Unable to query study on PACS: [{0}]", study.study_uid));

        //if (!System.IO.Directory.Exists(node.LocalStorage))
        //    System.IO.Directory.CreateDirectory(node.LocalStorage);
        //cstore.Start();
        //while (!cstore.IsRunning)
        //    System.Threading.Thread.Sleep(1000);
        //string singleSeriesOnly = System.Configuration.ConfigurationManager.AppSettings["singleSeries"];
        
        //MoveScuBase moveScu = new StudyRootMoveScu(node.LocalAe, node.AET, node.IP, node.Port, node.LocalAe);
        //moveScu.ReadTimeout = 600000;
        //moveScu.WriteTimeout = 600000;
        //moveScu.AddStudyInstanceUid(study.study_uid);
        //foreach (var se in study.series)
        //{
        //    moveScu.AddSeriesInstanceUid(se.series_uid);
        //    System.Diagnostics.Debug.WriteLine(se.series_uid);
        //}
        //moveScu.Move();
        //System.Threading.Thread.Sleep(2000);
        //if (moveScu.Status == ScuOperationStatus.AssociationRejected || moveScu.Status == ScuOperationStatus.Canceled ||
        //    moveScu.Status == ScuOperationStatus.ConnectFailed || moveScu.Status == ScuOperationStatus.Failed ||
        //    moveScu.Status == ScuOperationStatus.NetworkError || moveScu.Status == ScuOperationStatus.TimeoutExpired ||
        //    moveScu.Status == ScuOperationStatus.UnexpectedMessage || moveScu.FailureSubOperations != 0)
        //{
        //    if (retryCount > 4)
        //        throw new Exception(string.Format("Failed moving study [{0}] | Status : {1} | Failed Operations: {2}", study.study_uid, moveScu.Status, moveScu.FailureSubOperations));
        //    retryCount += 1;
        //    if (cstore.IsRunning)
        //        cstore.Stop();
        //    DownloadStudy(study, retryCount);
        //}
        //else
        //{
        //    System.Threading.Thread.Sleep(2000);
        //    cstore.Stop();
        //}
        //if (cstore.IsRunning)
        //    cstore.Stop();
        //LOG.InsertEvent("Successfully downloaded study: " + study.description, "DICOM", null, study.case_id, study.study_uid);
        //return true;

        try
        {            
            
        }
        catch (Exception ex)
        {
            
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "DICOM", ex.Message, study.case_id, study.study_uid);
            return false;
        }        
    }                
Esempio n. 9
0
 public static void InsertNewCase(HttpContext context)
 {
     string caseId = "";
     var bm = new BoolMessage();
     bm.Data = null;        
     try
     {
         var upCasePackage = AF.GetObjectFromJSON<UploadPackage>(context);
         if (upCasePackage == null || upCasePackage == default(UploadPackage))
         {
             throw new Exception("Unable to parse incoming package");
         }
         APetaPoco.SetConnectionString("cn1");            
         caseId = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + upCasePackage.username;
         var dCase = new DbCase();
         dCase.age = upCasePackage.case_details.age;
         dCase.body = upCasePackage.case_details.body;
         dCase.case_id = caseId;
         dCase.date = DateTime.Now;
         dCase.diagnostic_certainty_id = upCasePackage.case_details.diagnostic_certainty_id;
         dCase.presentation = upCasePackage.case_details.presentation;
         dCase.status = "PENDING";
         dCase.status_message = "Inserted via Uploader UI";
         dCase.suitable_for_quiz = upCasePackage.case_details.suitable_for_quiz;
         dCase.system_id = upCasePackage.case_details.system_id;
         dCase.title = upCasePackage.case_details.title;
         dCase.username = upCasePackage.username;
         bm = APetaPoco.PpInsert(dCase);
         if (!bm.Success) { throw new Exception("Unable to insert case"); }
         foreach (var st in upCasePackage.studies)
         {
             var dcmSt = ADCM.GetStudyFromStudyUid(st.study_uid);
             var dSt = new DbStudy();                
             dSt.caption = st.caption;
             dSt.case_id = caseId;
             DateTime dt;
             bool dtp = DateTime.TryParseExact(st.date, "dd/MM/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
             if (dtp) { dSt.date = dt; }
             if(dcmSt != null && dcmSt != default(Study))
             {
                 dSt.patient_dob = dcmSt.PatientDob;
                 dSt.patient_id = dcmSt.PatientId;
                 dSt.patient_name = dcmSt.PatientSurname.ToUpper() + ", " + dcmSt.PatientFirstname;
             }
             dSt.description = st.description;
             dSt.findings = st.findings;
             dSt.images = st.images;
             dSt.modality = st.modality;
             dSt.position = st.position;
             dSt.study_uid = st.study_uid;                
             bm = APetaPoco.PpInsert(dSt);
             if (!bm.Success) { throw new Exception("Unable to insert study"); }
             foreach (var se in st.series)
             {
                 var dSe = new DbSeries();
                 dSe.case_id = caseId;
                 dSe.description = se.description;
                 dSe.images = se.images;
                 dSe.series_uid = se.series_uid;
                 dSe.study_uid = st.study_uid;
                 dSe.crop_h = se.crop_h;
                 dSe.crop_w = se.crop_w;
                 dSe.crop_x = se.crop_x;
                 dSe.crop_y = se.crop_y;
                 dSe.window_wc = se.window_wc;
                 dSe.window_ww = se.window_ww;
                 dSe.end_image = se.end_image;
                 dSe.every_image = se.every_image;
                 dSe.start_image = se.start_image;
                 bm = APetaPoco.PpInsert(dSe);
                 if (!bm.Success) { throw new Exception("Unable to insert series"); }
             }
         }
         InsertEvent("Successfully inserted case into database:\n" + caseId, "WEB", Newtonsoft.Json.JsonConvert.SerializeObject(dCase), dCase.case_id);
         bm.Success = true;
         bm.Data = null;
         bm.Message = "Successfully inserted case into database";
         AF.BoolMessageRespond(context, bm);
     }
     catch (System.Threading.ThreadAbortException) { return; }
     catch (Exception ex)
     {
         if (!string.IsNullOrEmpty(caseId)) { ClearAllInDbWithCaseId(caseId); }            
         AF.ExceptionRespond(context, ex);
     }                        
 }
Esempio n. 10
0
    public static bool ConvertDcmToPng(DbStudy study)
    {        
        try
        {
            string dcmPath = ADCM.GetStoreString();
            string studyPath = Path.Combine(dcmPath, study.study_uid);
            if (!Directory.Exists(studyPath))
                throw new Exception("Study path not found");
            var allSeriesPaths = Directory.GetDirectories(studyPath);
            if (allSeriesPaths.Length < 1)
                throw new Exception("No series subdirectories");

            foreach (var s in allSeriesPaths)
            {
                var dcmFiles = Directory.GetFiles(s, "*.dcm");
                if (dcmFiles.Length < 1)
                    throw new Exception("No DCM files inside series path: " + s);
                DicomFile tempdcm = new DicomFile(dcmFiles[0]);
                tempdcm.Load();
                var seriesName = tempdcm.DataSet[DicomTags.SeriesDescription].GetString(0, null);
                var seriesUID = s.Substring(s.LastIndexOf(Path.DirectorySeparatorChar) + 1);
                if (string.IsNullOrEmpty(seriesName))
                    seriesName = "Unamed_Series";

                APetaPoco.SetConnectionString("cn1");
                var bm = APetaPoco.PpRetrieveOne<DbSeries>("Series", "[case_id] = '" + study.case_id + "' AND [series_uid] = '" + seriesUID + "'");
                DbSeries dbseries = null;
                if (bm.Success) { dbseries = (DbSeries)bm.Data; }

                string outputPath = Path.Combine(dcmPath, "OUTPUT", study.case_id, study.study_uid, seriesUID);
                if (!Directory.Exists(outputPath))
                    Directory.CreateDirectory(outputPath);

                //int fileCount = 0;

                for (int k = 0; k < dcmFiles.Length; k++)
                {
                    DicomFile dcmFile = new DicomFile(dcmFiles[k]);
                    dcmFile.Load();
                    int fileCount = 0;
                    var windowWidth = dcmFile.DataSet[DicomTags.WindowWidth].ToString();
                    if (!string.IsNullOrEmpty(windowWidth))
                    {
                        var tempSplitString = windowWidth.Split('\\');
                        windowWidth = tempSplitString[0];
                    }
                    var windowCenter = dcmFile.DataSet[DicomTags.WindowCenter].ToString();
                    if (!string.IsNullOrEmpty(windowCenter))
                    {
                        var tempSplitString = windowCenter.Split('\\');
                        windowCenter = tempSplitString[0];
                    }
                    var ww = dcmFile.DataSet[DicomTags.WindowWidth].GetFloat32(0, 0);
                    var wc = dcmFile.DataSet[DicomTags.WindowCenter].GetFloat32(0, 0);

                    if (ww == 0 && !string.IsNullOrEmpty(windowWidth))
                    {
                        if (windowWidth.Contains("."))
                        {
                            var tempSplitString = windowWidth.Split('.');
                            ww = int.Parse(tempSplitString[0]);
                        }
                        else
                        {
                            ww = int.Parse(windowWidth);
                        }

                    }
                    if (wc == 0 && !string.IsNullOrEmpty(windowCenter))
                    {
                        if (windowCenter.Contains("."))
                        {
                            var tempSplitString = windowCenter.Split('.');
                            wc = int.Parse(tempSplitString[0]);
                        }
                        else
                        {
                            wc = int.Parse(windowCenter);
                        }

                    }

                    LocalSopDataSource localds = new LocalSopDataSource(dcmFile);
                    if (!localds.IsImage) { continue; }
                    ImageSop sop = new ImageSop(localds);
                    int frameCount = sop.Frames.Count;
                    var fileName = dcmFile.DataSet[DicomTags.InstanceNumber].GetInt16(0, 0);
                    if (frameCount > 1)
                    {
                        for (int j = 1; j <= frameCount; j++)
                        {
                            GC.Collect();
                            Frame f = sop.Frames[j];
                            var jpgPath = Path.Combine(outputPath, fileName + "." + j + ".png");
                            Bitmap bmp = null;
                            if (string.IsNullOrEmpty(windowWidth) || string.IsNullOrEmpty(windowCenter))
                            {
                                bmp = DrawDefaultFrame(f);
                            }
                            else
                            {
                                bmp = DrawLutFrame(f, ww, wc);
                            }
                            if (bmp != null)
                            {
                                if(dbseries != null && dbseries.crop_h != null
                                    && dbseries.crop_w != null
                                    && dbseries.crop_x != null
                                    && dbseries.crop_y != null)
                                {
                                    bmp = Crop(bmp, dbseries.crop_x.Value, dbseries.crop_y.Value, dbseries.crop_w.Value, dbseries.crop_h.Value);
                                }
                                SaveImage(bmp, jpgPath);
                            }
                            fileCount += 1;
                            GC.Collect();
                        }
                    }
                    else
                    {
                        GC.Collect();
                        var jpgPath = Path.Combine(outputPath, fileName + ".png");
                        Frame f = sop.Frames[1];
                        Bitmap bmp = null;
                        if (string.IsNullOrEmpty(windowWidth) || string.IsNullOrEmpty(windowCenter))
                        {
                            bmp = DrawDefaultFrame(f);
                        }
                        else
                        {
                            bmp = DrawLutFrame(f, ww, wc);
                        }
                        if (bmp != null)
                        {
                            if (dbseries != null && dbseries.crop_h != null
                                    && dbseries.crop_w != null
                                    && dbseries.crop_x != null
                                    && dbseries.crop_y != null)
                            {
                                bmp = Crop(bmp, dbseries.crop_x.Value, dbseries.crop_y.Value, dbseries.crop_w.Value, dbseries.crop_h.Value);
                            }
                            SaveImage(bmp, jpgPath);
                        }
                        fileCount += 1;
                        GC.Collect();
                    }
                }
            }
            LOG.InsertEvent("Successfully converted study from DCM to PNG", "IMG", null, study.case_id, study.study_uid);
            return true;
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "IMG", ex.Message, study.case_id, study.study_uid);
            return false;
        }
        
    }       
Esempio n. 11
0
 public static bool ZipSeries(DbStudy study)
 {
     try
     {
         string scpPath = ADCM.GetStoreString();
         string outputPath = Path.Combine(scpPath, "OUTPUT", study.case_id, study.study_uid);
         if (!Directory.Exists(outputPath))
             throw new Exception("Output path not found: " + outputPath);
         var seriesPaths = Directory.GetDirectories(outputPath);
         foreach (var s in seriesPaths)
         {
             //ReorderImages(s);
             var seriesUID = s.Substring(s.LastIndexOf(Path.DirectorySeparatorChar) + 1);
             string zipPath = Path.Combine(outputPath, seriesUID + ".zip");
             using (ZipFile zip = new ZipFile())
             {
                 zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                 zip.AddDirectory(s);
                 zip.Save(zipPath);
             }
             FileInfo zipInfo = new FileInfo(zipPath);
             double megabytes = Math.Round((zipInfo.Length / 1024f) / 1024f, 2);
             LOG.Write("Zip created: " + zipInfo.Name + ", " + megabytes + " MB");
             LOG.InsertEvent("Zip created: " + zipInfo.Name + " - " + megabytes + "MB", "IMG", null, study.case_id, study.study_uid, seriesUID);
             System.Threading.Thread.Sleep(500);
         }
         LOG.InsertEvent("Successfully created ZIP files for all series in study", "IMG", null, study.case_id, study.study_uid);
         return true;
     }
     catch (Exception ex)
     {
         string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
         LOG.Write(errorString);
         LOG.Write(ex.Message);
         LOG.InsertEvent(errorString, "IMG", ex.Message, study.case_id, study.study_uid);
         return false;
     }        
 }
Esempio n. 12
0
    public static void OptiPng(DbStudy study)
    {
        string dcmPath = ADCM.GetStoreString();
        foreach(var ser in study.series)
        {
            string outputPath = Path.Combine(dcmPath, "OUTPUT", study.case_id, study.study_uid, ser.series_uid);
            if (Directory.Exists(outputPath))
            {
                var pngs = Directory.GetFiles(outputPath, "*.png");
                if(pngs == null || pngs.Length < 1) { continue; }
                foreach (var f in pngs)
                {
                    if (File.Exists(@".\OptiPNG\optipng.exe"))
                    {
                        // Run OPTIPNG with level 7 compression.
                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                        info.FileName = @".\OptiPNG\optipng.exe";
                        info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                        info.Arguments = "\"" + f + "\"";

                        // Use Process for the application.
                        using (System.Diagnostics.Process exe = System.Diagnostics.Process.Start(info))
                        {
                            exe.WaitForExit();
                        }
                    }
                }
            }
        }                      
    }
Esempio n. 13
0
    public static void DeleteExcessImages(DbStudy study)
    {
        try
        {
            string dcmPath = ADCM.GetStoreString();
            string outputPath = Path.Combine(dcmPath, "OUTPUT", study.case_id, study.study_uid);
            if (!Directory.Exists(outputPath)) { throw new Exception("No output path found: " + outputPath); }
            foreach (var ser in study.series)
            {
                string serPath = Path.Combine(outputPath, ser.series_uid);
                if (Directory.Exists(serPath))
                {
                    var sortedList = Directory.GetFiles(serPath, "*.png").OrderBy(f => int.Parse(Path.GetFileNameWithoutExtension(f))).ToList();
                    if (sortedList.Count > ser.images)
                    {
                        int start = 1;
                        int end = ser.images;
                        int stepping = 1;
                        if (ser.start_image != null && ser.start_image > 0)
                            start = ser.start_image.Value;
                        if (ser.end_image != null && ser.end_image > 0)
                            end = ser.end_image.Value;
                        if (end > sortedList.Count)
                            end = sortedList.Count;
                        if (ser.every_image != null && ser.every_image > 0)
                            stepping = ser.every_image.Value;                        

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

                        LOG.Write(string.Format("Start: {0}| End: {1}| Stepping: {2}", start, end, stepping));

                        for (int i = start - 1; i < end; i += stepping)
                        {
                            //LOG.Write(string.Format("[{0}] Keeping {1}", i, sortedList[i]));
                            keepPaths.Add(sortedList[i]);
                        }

                        foreach (var f in sortedList)
                        {
                            if (!keepPaths.Contains(f))
                            {
                                //LOG.Write(string.Format("Deleting {0}", f));
                                File.Delete(f);
                            }
                        }
                    }
                }
                else
                {
                    LOG.Write("No series path: " + serPath);
                }
            }
        }
        catch(Exception ex)
        {
            LOG.Write(ex.Message);
        }
        
    }
Esempio n. 14
0
 private static List<DbSeries> GetDbSeriesForDbStudy(DbStudy study)
 {
     APetaPoco.SetConnectionString("cn1");
     var bm = APetaPoco.PpRetrieveList<DbSeries>("Series", string.Format("[study_uid] = '{0}' AND [case_id] = '{1}'", study.study_uid, study.case_id));
     if (!bm.Success) { return null; }
     return (List<DbSeries>)bm.Data;
 }
Esempio n. 15
0
    public static string CreateStudy(DbStudy dbstudy, string username, string caseId)
    {
        try
        {
            var ustudy = new StudyUpload();
            ustudy.modality = GetModality(dbstudy.modality);
            ustudy.caption  = dbstudy.caption;
            ustudy.findings = dbstudy.findings;
            ustudy.position = dbstudy.position;
            string postData = JsonConvert.SerializeObject(ustudy);
            byte[] data     = System.Text.Encoding.UTF8.GetBytes(postData);

            string responseFromServer = null;
            try
            {
                var        api     = ACFG.GetSiteApiDetails();
                var        user    = AOA.GetUserRefreshIfNecessary(username, caseId);
                WebRequest request = WebRequest.Create(api.cases_url + caseId + "/studies");
                request.Method      = "POST";
                request.ContentType = "application/json";
                request.Headers.Add("Authorization", "Bearer " + user.access_token);

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                WebResponse            response   = request.GetResponse();
                var                    dataStream = response.GetResponseStream();
                System.IO.StreamReader reader     = new System.IO.StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        string errorResponse = reader.ReadToEnd();
                        LOG.InsertEvent("Unable to create new study on Radiopedia server", "API", errorResponse, dbstudy.case_id, dbstudy.study_uid);
                    }
                return(null);
            }
            catch (Exception ex)
            {
                string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
                LOG.Write(errorString);
                LOG.Write(ex.Message);
                LOG.InsertEvent(errorString, "API", ex.Message, dbstudy.case_id, dbstudy.study_uid);
                return(null);
            }

            var respObj = JsonConvert.DeserializeObject <StudyResponse>(responseFromServer);
            dbstudy.r_study_id = respObj.id;
            APetaPoco.SetConnectionString("cn1");
            var bm = APetaPoco.PpUpdate(dbstudy);
            if (!bm.Success)
            {
                throw new Exception("Unable to update Study in database");
            }
            LOG.InsertEvent("Successfully created new study:\n" + respObj.id, "API", responseFromServer, dbstudy.case_id, dbstudy.study_uid);
            return(respObj.id);
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "API", ex.Message, dbstudy.case_id, dbstudy.study_uid);
            return(null);
        }
        finally { GC.Collect(); }
    }
Esempio n. 16
0
    public static string CreateStudy(DbStudy dbstudy, string username, string caseId)
    {       
        try
        {
            var ustudy = new StudyUpload();
            ustudy.modality = GetModality(dbstudy.modality);
            ustudy.caption = dbstudy.caption;
            ustudy.findings = dbstudy.findings;
            ustudy.position = dbstudy.position;
            string postData = JsonConvert.SerializeObject(ustudy);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(postData);

            string responseFromServer = null;
            try
            {
                var api = ACFG.GetSiteApiDetails();
                var user = AOA.GetUserRefreshIfNecessary(username, caseId);
                WebRequest request = WebRequest.Create(api.cases_url + caseId + "/studies");
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Headers.Add("Authorization", "Bearer " + user.access_token);

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                WebResponse response = request.GetResponse();
                var dataStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    string errorResponse = reader.ReadToEnd();
                    LOG.InsertEvent("Unable to create new study on Radiopedia server", "API", errorResponse, dbstudy.case_id, dbstudy.study_uid);
                }
                return null;
            }
            catch (Exception ex)
            {
                string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
                LOG.Write(errorString);
                LOG.Write(ex.Message);
                LOG.InsertEvent(errorString, "API", ex.Message, dbstudy.case_id, dbstudy.study_uid);
                return null;
            }

            var respObj = JsonConvert.DeserializeObject<StudyResponse>(responseFromServer);
            dbstudy.r_study_id = respObj.id;
            APetaPoco.SetConnectionString("cn1");
            var bm = APetaPoco.PpUpdate(dbstudy);
            if (!bm.Success)
                throw new Exception("Unable to update Study in database");
            LOG.InsertEvent("Successfully created new study:\n" + respObj.id, "API", responseFromServer, dbstudy.case_id, dbstudy.study_uid);
            return respObj.id;
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "API", ex.Message, dbstudy.case_id, dbstudy.study_uid);
            return null;
        }
        finally { GC.Collect(); }
    }