Esempio n. 1
0
    private static List <DbStudy> GetStudiesForCase(string caseid)
    {
        List <DbStudy> studies = new List <DbStudy>();

        APetaPoco.SetConnectionString("cn1");
        var bm = APetaPoco.PpRetrieveList <DbStudy>("Studies", string.Format("[case_id] = '{0}'", caseid));

        if (bm.Success)
        {
            studies = (List <DbStudy>)bm.Data;
            foreach (var s in studies)
            {
                bm = APetaPoco.PpRetrieveList <DbSeries>("Series", string.Format("[case_id] = '{0}' AND [study_uid] = '{1}'", caseid, s.study_uid));
                if (bm.Success)
                {
                    var series = (List <DbSeries>)bm.Data;
                    s.series = series;
                }
            }
            return(studies);
        }
        else
        {
            return(null);
        }
    }
Esempio n. 2
0
 private static void SetCaseStatus(DbCase dcase, string status, string statusMsg)
 {
     dcase.status         = status;
     dcase.status_message = statusMsg;
     APetaPoco.SetConnectionString("cn1");
     var bm = APetaPoco.PpUpdate(dcase);
 }
Esempio n. 3
0
 public static User GetUserRefreshIfNecessary(string username, string caseid)
 {
     try
     {
         APetaPoco.SetConnectionString("cn1");
         var bm = APetaPoco.PpRetrieveOne <User>("Users", "[username] = '" + username + "'");
         if (!bm.Success)
         {
             throw new Exception("Unable to retrieve user details for case: " + username);
         }
         var user = (User)bm.Data;
         if (DateTime.Now > user.expiry_date.Value.AddMinutes(-30))
         {
             RefreshToken(user.refresh_token, caseid);
             bm = APetaPoco.PpRetrieveOne <User>("Users", "[username] = '" + username + "'");
             if (!bm.Success)
             {
                 throw new Exception("Unable to retrieve UPDATED user details for case: " + username);
             }
             user = (User)bm.Data;
         }
         return(user);
     }
     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, caseid);
         return(null);
     }
     finally { GC.Collect(); }
 }
Esempio n. 4
0
        static void Debug()
        {
            //AUP.UploadZip("44186", "47777", @"d:\temp\1.3.12.2.1107.5.1.4.65115.3000001603240736279390001264491.zip", "henryknipe", "20160411091821_henryknipe", "1.3.12.2.1107.5.8.9.13.26.65.26.126.218.77882191");
            APetaPoco.SetConnectionString("cn1");
            var bm    = APetaPoco.PpRetrieveOne <DbCase>("Cases", "[case_id] = '20160607180814_frank'");
            var pcase = (DbCase)bm.Data;

            bm = APetaPoco.PpRetrieveList <DbStudy>("Studies", "[case_id] = '20160607180814_frank'");
            pcase.study_list = (List <DbStudy>)bm.Data;
            foreach (var st in pcase.study_list)
            {
                bm        = APetaPoco.PpRetrieveList <DbSeries>("Series", "[case_id] = '20160607180814_frank' AND [study_uid] = '" + st.study_uid + "'");
                st.series = (List <DbSeries>)bm.Data;
                //ADCM.DownloadStudy(st);
                LOG.Write("Converting DCM to PNG...");
                AIMG.MultiFrameProcess(st);
                bool convertComplete = AIMG.ConvertDcmToPng(st);
                //if (!convertComplete)
                //{
                //    ACASE.ClearCaseFiles(pcase);
                //    throw new Exception("Unable to convert study to PNG");
                //}
                LOG.Write("Completed image conversion");

                LOG.Write("Optimizing PNG's for study...");
                AIMG.OptiPng(st);
                LOG.Write("Completed optimization.");
                //AIMG.ZipSeries(st);
            }
            //ACASE.ProcessCase(pcase);
        }
Esempio n. 5
0
 public static void InsertEvent(string msg, string type, string data = null, string dcase = null, string dstudy = null, string dseries = null)
 {
     try
     {
         Event e = new Event();
         e.Type      = type;
         e.Message   = msg;
         e.TimeStamp = DateTime.Now;
         e.Data      = data;
         if (dcase != null)
         {
             e.InternalId = dcase;
         }
         if (dstudy != null)
         {
             e.StudyUid = dstudy;
         }
         if (dseries != null)
         {
             e.SeriesUid = dseries;
         }
         APetaPoco.SetConnectionString("cn1");
         var bm = APetaPoco.PpInsert(e);
         if (!bm.Success)
         {
             LOG.Write(bm.Message);
         }
     }
     catch (Exception ex)
     {
         string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
         LOG.Write(errorString);
         LOG.Write(ex.Message);
     }
 }
Esempio n. 6
0
 public static void RefreshToken(string refreshToken, string caseid)
 {
     try
     {
         var    api = ACFG.GetSiteApiDetails();
         string responseFromServer = null;
         try
         {
             WebRequest request = WebRequest.Create(api.oauth_url + "token?client_id=" + api.site_id + "&client_secret=" + api.site_secret + "&refresh_token=" + refreshToken + "&grant_type=refresh_token");
             request.Method = "POST";
             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 System.IO.StreamReader(stream))
                 {
                     string errorResponse = reader.ReadToEnd();
                     LOG.InsertEvent("Unable to upload zip", "API", errorResponse, caseid);
                 }
             GC.Collect();
             return;
         }
         var tokenResp = JsonConvert.DeserializeObject <TokenResponse>(responseFromServer);
         if (tokenResp == null || tokenResp == default(TokenResponse))
         {
             throw new Exception("Unable to retrieve valid token response");
         }
         APetaPoco.SetConnectionString("cn1");
         var bm = APetaPoco.PpRetrieveOne <User>("Users", "[refresh_token] = '" + refreshToken + "'");
         if (bm.Success)
         {
             var user = (User)bm.Data;
             user.access_token  = tokenResp.access_token;
             user.refresh_token = tokenResp.refresh_token;
             user.expiry_date   = DateTime.Now.AddSeconds(tokenResp.expires_in - 10);
             bm = APetaPoco.PpUpdate(user);
             if (!bm.Success)
             {
                 throw new Exception("Unable to update user details with new token");
             }
         }
     }
     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, caseid);
     }
     finally { GC.Collect(); }
 }
Esempio n. 7
0
    public static Node GetDebugNode()
    {
        APetaPoco.SetConnectionString("cn1");
        var bm = APetaPoco.PpRetrieveOne <Node>("PACS", "[LocalAe] = 'ANDYPACS3'");

        if (bm.Success)
        {
            return((Node)bm.Data);
        }
        else
        {
            return(null);
        }
    }
Esempio n. 8
0
    public static Node GetSelectedNode()
    {
        APetaPoco.SetConnectionString("cn1");
        var bm = APetaPoco.PpRetrieveOne <Node>("PACS", "[Selected] = 1");

        if (bm.Success)
        {
            return((Node)bm.Data);
        }
        else
        {
            return(null);
        }
    }
Esempio n. 9
0
    public static CFG GetConfigData()
    {
        CFG cfg = new CFG();

        cfg.ConnectionString = ConfigurationManager.ConnectionStrings["cn1"].ToString();
        if (!string.IsNullOrEmpty(cfg.ConnectionString))
        {
            APetaPoco.SetConnectionString("cn1");
            cfg.SiteApi = GetSiteApiDetails();
            var bm = APetaPoco.PpRetrieveList <Node>("PACS");
            if (bm.Success)
            {
                cfg.Nodes = (List <Node>)bm.Data;
            }
        }
        return(cfg);
    }
Esempio n. 10
0
    public static List <DbCase> GetPendingCases()
    {
        APetaPoco.SetConnectionString("cn1");
        var bm = APetaPoco.PpRetrieveList <DbCase>("Cases", "[Status] = 'PENDING'");

        if (bm.Success)
        {
            var list = (List <DbCase>)bm.Data;
            foreach (var c in list)
            {
                c.study_list = GetStudiesForCase(c.case_id);
            }
            return(list);
        }
        else
        {
            return(null);
        }
    }
Esempio n. 11
0
    private static DbStudy GetStudy(string condition)
    {
        APetaPoco.SetConnectionString("cn1");
        var bm = APetaPoco.PpRetrieveOne <DbStudy>("Studies", condition);

        if (!bm.Success)
        {
            throw new Exception("Unable to get Study based on condition: " + condition);
        }
        var dbs = (DbStudy)bm.Data;

        bm = APetaPoco.PpRetrieveList <DbSeries>("Series", condition);
        if (bm.Success)
        {
            var series = (List <DbSeries>)bm.Data;
            dbs.series = series;
        }

        return(dbs);
    }
Esempio n. 12
0
    public static ApiClient GetSiteApiDetails()
    {
        APetaPoco.SetConnectionString("cn1");
        var bm = APetaPoco.PpRetrieveCustomQuery <ApiClient>("SELECT TOP 1 * FROM [ApiClient]");

        if (bm.Success)
        {
            var list = (List <ApiClient>)bm.Data;
            if (list != null && list.Count > 0)
            {
                return(list[0]);
            }
            else
            {
                return(null);
            }
        }
        else
        {
            return(null);
        }
    }
Esempio n. 13
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. 14
0
    public static BoolMessage CheckIfOnlySelected(Node node)
    {
        var rbm = new BoolMessage();

        rbm.Data = null;
        try
        {
            APetaPoco.SetConnectionString("cn1");
            var  bm = APetaPoco.PpRetrieveOne <Node>("PACS", "[Selected] = 1");
            Node currentSelectedNode = null;
            if (bm.Success)
            {
                currentSelectedNode = (Node)bm.Data;
            }
            else
            {
                return(bm);
            }
            if (currentSelectedNode == null || currentSelectedNode == default(Node))
            {
                if (node.Selected)
                {
                    rbm.Success = true;
                }
                else
                {
                    throw new Exception("There's no selected node in the database");
                }
            }
            else
            {
                if (node.Selected)
                {
                    if (node.Id == currentSelectedNode.Id)
                    {
                        rbm.Success = true;
                    }
                    else
                    {
                        currentSelectedNode.Selected = false;
                        bm = APetaPoco.PpUpdate(currentSelectedNode);
                        if (bm.Success)
                        {
                            rbm.Success = true;
                        }
                        else
                        {
                            return(bm);
                        }
                    }
                }
                else
                {
                    if (currentSelectedNode.Id != node.Id)
                    {
                        rbm.Success = true;
                    }
                    else
                    {
                        throw new Exception("Can't unselect the only selected node in database");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            rbm.Success = false;
            rbm.Message = ex.Message;
        }
        return(rbm);
    }
Esempio n. 15
0
    public static string CreateCase(DbCase dbcase)
    {
        try
        {
            var ucase = new UploadCase();
            ucase.age  = dbcase.age;
            ucase.body = dbcase.body;
            ucase.diagnostic_certainty_id = dbcase.diagnostic_certainty_id;
            ucase.presentation            = dbcase.presentation;
            ucase.suitable_for_quiz       = dbcase.suitable_for_quiz;
            ucase.system_id = dbcase.system_id;
            ucase.title     = dbcase.title;
            string postData = JsonConvert.SerializeObject(ucase);
            byte[] data     = System.Text.Encoding.UTF8.GetBytes(postData);

            var api  = ACFG.GetSiteApiDetails();
            var user = AOA.GetUserRefreshIfNecessary(dbcase.username, dbcase.case_id);


            string responseFromServer = null;
            try
            {
                WebRequest request = WebRequest.Create(api.cases_url);
                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();
                if (string.IsNullOrEmpty(responseFromServer))
                {
                    throw new Exception("Unable to get response from server when creating case");
                }
                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 case on Radiopedia server", "API", errorResponse, dbcase.case_id);
                    }
                return(null);
            }


            var respObj = JsonConvert.DeserializeObject <CaseResponse>(responseFromServer);
            dbcase.r_case_id = respObj.id;
            APetaPoco.SetConnectionString("cn1");
            var bm = APetaPoco.PpUpdate(dbcase);
            if (!bm.Success)
            {
                throw new Exception("Unable to update Case in database");
            }
            LOG.InsertEvent("Successfully created Case on Radiopaedia:\n" + respObj.id, "API", responseFromServer, dbcase.case_id);
            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, dbcase.case_id);
            return(null);
        }
    }
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(); }
    }