Пример #1
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);
 }
Пример #2
0
    public static void ClearCaseFiles(DbCase pcase)
    {
        string dcmPath = ADCM.GetStoreString();

        foreach (var st in pcase.study_list)
        {
            string stDir = Path.Combine(dcmPath, st.study_uid);
            if (Directory.Exists(stDir))
            {
                Directory.Delete(stDir, true);
            }
        }
        string outputPath = Path.Combine(dcmPath, "OUTPUT", pcase.case_id);

        if (Directory.Exists(outputPath))
        {
            Directory.Delete(outputPath, true);
        }
    }
Пример #3
0
    private static bool CheckQuotas(DbCase pcase)
    {
        var user     = AOA.GetUserRefreshIfNecessary(pcase.username, pcase.case_id);
        var api_user = AOA.GetUserName(user.access_token);

        if (api_user.quotas.allowed_draft_cases == null || api_user.quotas.allowed_unlisted_cases == null)
        {
            return(true);
        }
        if (api_user.quotas.draft_case_count >= api_user.quotas.allowed_draft_cases)
        {
            return(false);
        }
        if (api_user.quotas.unlisted_case_count >= api_user.quotas.allowed_unlisted_cases)
        {
            return(false);
        }
        return(true);
    }
Пример #4
0
        private int CreateCasesInDb(String title)
        {
            var dbCase = new DbCase
            {
                Title         = title,
                IsClosed      = false,
                CreateOn      = _tenantUtil.DateTimeToUtc(_tenantUtil.DateTimeNow()),
                CreateBy      = _securityContext.CurrentAccount.ID,
                LastModifedOn = _tenantUtil.DateTimeToUtc(_tenantUtil.DateTimeNow()),
                LastModifedBy = _securityContext.CurrentAccount.ID,
                TenantId      = TenantID
            };

            CrmDbContext.Cases.Add(dbCase);

            CrmDbContext.SaveChanges();

            return(dbCase.Id);
        }
Пример #5
0
    public static void ProcessCase(DbCase pcase)
    {
        try
        {
            LOG.Write("Checking user quotas...");
            if (!CheckQuotas(pcase))
            {
                throw new Exception("Quota exceeded");
            }
            LOG.Write("Creating case on Radiopaedia...");
            pcase.r_case_id = AUP.CreateCase(pcase);
            if (string.IsNullOrEmpty(pcase.r_case_id))
                throw new Exception("Unable to create case id, cannot continue");
            LOG.Write("Case created id: " + pcase.r_case_id);

            if (pcase.study_list == null || pcase.study_list.Count < 1)
            {
                pcase.study_list = GetStudiesForCase(pcase.case_id);
                if (pcase.study_list == null || pcase.study_list.Count < 1) { throw new Exception("No studies in case: " + pcase.case_id); }
            }

            foreach (var st in pcase.study_list)
            {
                LOG.InsertEvent("Starting to process case: " + pcase.case_id, "AGENT", null, pcase.case_id);
                LOG.Write("Creating Radiopaedia Study...");
                st.r_study_id = AUP.CreateStudy(st, pcase.username, pcase.r_case_id);
                if (string.IsNullOrEmpty(st.r_study_id)) { throw new Exception("Unable to create study id on Radiopaedia"); }
                LOG.Write("Study ID created: " + st.r_study_id);

                LOG.Write("Study: " + st.description + "[" + st.modality + "]");
                LOG.Write("Downloading...");
                bool downloadComplete = ADCM.DownloadStudy(st, 0);
                if (!downloadComplete)
                {
                    ClearCaseFiles(pcase);
                    throw new Exception("Unable to download study - can't continue");
                }
                LOG.Write("Download finished");
                LOG.Write("Converting DCM to PNG...");
                AIMG.MultiFrameProcess(st);
                bool convertComplete = AIMG.ConvertDcmToPng(st);
                if (!convertComplete)
                {
                    ClearCaseFiles(pcase);
                    throw new Exception("Unable to convert study to PNG");
                }
                LOG.Write("Completed image conversion");

                LOG.Write("Deleting excess images...");
                AIMG.DeleteExcessImages(st);
                LOG.Write("Completed deleting excess images.");

                LOG.Write("Optimizing PNG's for study...");
                AIMG.OptiPng(st);
                LOG.Write("Completed optimization.");

                bool zipComplete = AIMG.ZipSeries(st);
                if (!zipComplete)
                    throw new Exception("Unable to create zips for study");


                string outPath = Path.Combine(ADCM.GetStoreString(), "OUTPUT", pcase.case_id, st.study_uid);
                var zips = Directory.GetFiles(outPath, "*.zip");
                foreach (var z in zips)
                {
                    string fileName = Path.GetFileName(z);                    

                    string[] sizes = { "B", "KB", "MB", "GB" };
                    double len = new FileInfo(z).Length;
                    int order = 0;
                    while (len >= 1024 && ++order < sizes.Length)
                    {
                        len = len / 1024;
                    }

                    LOG.Write(string.Format("Uploading: {2} ({0:0.##} {1})", len, sizes[order], fileName));
                    bool uploadedZip = AUP.UploadZip2(pcase.r_case_id, st.r_study_id, z, pcase.username, pcase.case_id, st.study_uid);       
                    if(!uploadedZip)
                    {
                        try
                        {
                            LOG.Write("Retry maxed out, copying zip to error output");
                            string errorFolder = Path.Combine(@".\Error_uploads\", pcase.case_id);
                            if (!Directory.Exists(errorFolder)) { Directory.CreateDirectory(errorFolder); }
                            string errorPath = Path.Combine(errorFolder, fileName);
                            File.Copy(z, errorPath);
                        }
                        catch
                        {
                            continue;
                        }                                                                        
                    }
                    LOG.Write("Finished uploading");
                }
            }
            LOG.Write("Marking case as completed");
            AUP.MarkCaseComplete(pcase.r_case_id, pcase.username, pcase.case_id);
            SetCaseStatus(pcase, "COMPLETED", "Case fully uploaded: http://radiopaedia.org/cases/" + pcase.r_case_id);
            System.Threading.Thread.Sleep(1000);
            LOG.Write("Finished with case: " + pcase.case_id);
            ClearCaseFiles(pcase);
            LOG.InsertEvent("Finished with case: " + pcase.case_id, "AGENT", null, pcase.case_id);            
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "AGENT", ex.Message, pcase.case_id);
            SetCaseStatus(pcase, "ERROR", ex.Message);
            ClearCaseFiles(pcase);
        }
        finally { GC.Collect(); }        
    }
Пример #6
0
 public static void ClearCaseFiles(DbCase pcase)
 {
     string dcmPath = ADCM.GetStoreString();
     foreach(var st in pcase.study_list)
     {
         string stDir = Path.Combine(dcmPath, st.study_uid);
         if (Directory.Exists(stDir))
             Directory.Delete(stDir, true);
     }
     string outputPath = Path.Combine(dcmPath, "OUTPUT", pcase.case_id);
     if (Directory.Exists(outputPath))
         Directory.Delete(outputPath, true);
 }
Пример #7
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);
 }
Пример #8
0
 private static bool CheckQuotas(DbCase pcase)
 {
     var user = AOA.GetUserRefreshIfNecessary(pcase.username, pcase.case_id);
     var api_user = AOA.GetUserName(user.access_token);
     if(api_user.quotas.allowed_draft_cases == null || api_user.quotas.allowed_unlisted_cases == null) { return true; }
     if (api_user.quotas.draft_case_count >= api_user.quotas.allowed_draft_cases) { return false; }
     if (api_user.quotas.unlisted_case_count >= api_user.quotas.allowed_unlisted_cases) { return false; }
     return true;
 }
Пример #9
0
    public static void ProcessCase(DbCase pcase)
    {
        try
        {
            LOG.Write("Checking user quotas...");
            if (!CheckQuotas(pcase))
            {
                throw new Exception("Quota exceeded");
            }
            LOG.Write("Creating case on Radiopaedia...");
            pcase.r_case_id = AUP.CreateCase(pcase);
            if (string.IsNullOrEmpty(pcase.r_case_id))
            {
                throw new Exception("Unable to create case id, cannot continue");
            }
            LOG.Write("Case created id: " + pcase.r_case_id);

            if (pcase.study_list == null || pcase.study_list.Count < 1)
            {
                pcase.study_list = GetStudiesForCase(pcase.case_id);
                if (pcase.study_list == null || pcase.study_list.Count < 1)
                {
                    throw new Exception("No studies in case: " + pcase.case_id);
                }
            }

            foreach (var st in pcase.study_list)
            {
                LOG.InsertEvent("Starting to process case: " + pcase.case_id, "AGENT", null, pcase.case_id);
                LOG.Write("Creating Radiopaedia Study...");
                st.r_study_id = AUP.CreateStudy(st, pcase.username, pcase.r_case_id);
                if (string.IsNullOrEmpty(st.r_study_id))
                {
                    throw new Exception("Unable to create study id on Radiopaedia");
                }
                LOG.Write("Study ID created: " + st.r_study_id);

                LOG.Write("Study: " + st.description + "[" + st.modality + "]");
                LOG.Write("Downloading...");
                bool downloadComplete = ADCM.DownloadStudy(st, 0);
                if (!downloadComplete)
                {
                    ClearCaseFiles(pcase);
                    throw new Exception("Unable to download study - can't continue");
                }
                LOG.Write("Download finished");
                LOG.Write("Converting DCM to PNG...");
                AIMG.MultiFrameProcess(st);
                bool convertComplete = AIMG.ConvertDcmToPng(st);
                if (!convertComplete)
                {
                    ClearCaseFiles(pcase);
                    throw new Exception("Unable to convert study to PNG");
                }
                LOG.Write("Completed image conversion");

                LOG.Write("Deleting excess images...");
                AIMG.DeleteExcessImages(st);
                LOG.Write("Completed deleting excess images.");

                LOG.Write("Optimizing PNG's for study...");
                AIMG.OptiPng(st);
                LOG.Write("Completed optimization.");

                bool zipComplete = AIMG.ZipSeries(st);
                if (!zipComplete)
                {
                    throw new Exception("Unable to create zips for study");
                }


                string outPath = Path.Combine(ADCM.GetStoreString(), "OUTPUT", pcase.case_id, st.study_uid);
                var    zips    = Directory.GetFiles(outPath, "*.zip");
                foreach (var z in zips)
                {
                    string fileName = Path.GetFileName(z);

                    string[] sizes = { "B", "KB", "MB", "GB" };
                    double   len   = new FileInfo(z).Length;
                    int      order = 0;
                    while (len >= 1024 && ++order < sizes.Length)
                    {
                        len = len / 1024;
                    }

                    LOG.Write(string.Format("Uploading: {2} ({0:0.##} {1})", len, sizes[order], fileName));
                    bool uploadedZip = AUP.UploadZip2(pcase.r_case_id, st.r_study_id, z, pcase.username, pcase.case_id, st.study_uid);
                    if (!uploadedZip)
                    {
                        try
                        {
                            LOG.Write("Retry maxed out, copying zip to error output");
                            string errorFolder = Path.Combine(@".\Error_uploads\", pcase.case_id);
                            if (!Directory.Exists(errorFolder))
                            {
                                Directory.CreateDirectory(errorFolder);
                            }
                            string errorPath = Path.Combine(errorFolder, fileName);
                            File.Copy(z, errorPath);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    LOG.Write("Finished uploading");
                }
            }
            LOG.Write("Marking case as completed");
            AUP.MarkCaseComplete(pcase.r_case_id, pcase.username, pcase.case_id);
            SetCaseStatus(pcase, "COMPLETED", "Case fully uploaded: http://radiopaedia.org/cases/" + pcase.r_case_id);
            System.Threading.Thread.Sleep(1000);
            LOG.Write("Finished with case: " + pcase.case_id);
            ClearCaseFiles(pcase);
            LOG.InsertEvent("Finished with case: " + pcase.case_id, "AGENT", null, pcase.case_id);
        }
        catch (Exception ex)
        {
            string errorString = "Error at :" + System.Reflection.MethodBase.GetCurrentMethod().Name;
            LOG.Write(errorString);
            LOG.Write(ex.Message);
            LOG.InsertEvent(errorString, "AGENT", ex.Message, pcase.case_id);
            SetCaseStatus(pcase, "ERROR", ex.Message);
            ClearCaseFiles(pcase);
        }
        finally { GC.Collect(); }
    }
Пример #10
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);
     }                        
 }
Пример #11
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);
        }
    }
Пример #12
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;
        }        
    }