public static bool MarkCaseComplete(string RcaseId, string username, string DbCaseId) { try { var user = AOA.GetUserRefreshIfNecessary(username, DbCaseId); var api = ACFG.GetSiteApiDetails(); WebRequest request = WebRequest.Create(api.cases_url + RcaseId + "/mark_upload_finished"); request.Method = "PUT"; //request.ContentType = "application/json"; request.Headers.Add("Authorization", "Bearer " + user.access_token); WebResponse response = request.GetResponse(); var dataStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); if (string.IsNullOrEmpty(responseFromServer)) { throw new Exception("Unable to get response from server when marking case complete"); } reader.Close(); dataStream.Close(); response.Close(); var respObj = JsonConvert.DeserializeObject <CaseResponse>(responseFromServer); LOG.InsertEvent("Successfully marked study as completed on Radiopaedia", "API", responseFromServer, DbCaseId); return(true); } 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, DbCaseId); return(false); } }
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(); } }
public static bool UploadZip2(string RcaseId, string studyId, string zipPath, string username, string DbCaseId, string stydyUid) { var api = ACFG.GetSiteApiDetails(); var user = AOA.GetUserRefreshIfNecessary(username, DbCaseId); // Build request var request = (HttpWebRequest)WebRequest.Create(api.cases_url + RcaseId + "/studies/" + studyId + "/images"); request.Method = WebRequestMethods.Http.Post; request.AllowWriteStreamBuffering = false; request.ContentType = "application/zip"; request.Timeout = 60 * 60 * 1000; request.ReadWriteTimeout = 60 * 60 * 1000; string fileName = Path.GetFileName(zipPath); request.Headers["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", fileName); request.Headers.Add("Authorization", "Bearer " + user.access_token); try { // Open source file using (var fileStream = File.OpenRead(zipPath)) { // Set content length based on source file length request.ContentLength = fileStream.Length; // Get the request stream with the default timeout using (var requestStream = request.GetRequestStream()) { // Upload the file with no timeout fileStream.CopyTo(requestStream); } } using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) using (var reader = new StreamReader(responseStream)) { var respObj = JsonConvert.DeserializeObject <UploadResponse>(reader.ReadToEnd()); LOG.Write("Uploaded Filename: " + respObj.filename); LOG.InsertEvent("Successfully uploaded ZIP", "API", reader.ReadToEnd(), DbCaseId, stydyUid); } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.Timeout) { //LogError(ex, "Timeout while uploading '{0}'", fileName); LOG.InsertEvent("Timeout While uploading: " + zipPath, "API", ex.Message, DbCaseId, stydyUid); LOG.Write("Timeout Uploading"); LOG.Write(ex.Message); } else { LOG.InsertEvent("Error While uploading: " + zipPath, "API", ex.Message, DbCaseId, stydyUid); LOG.Write("Error Uploading"); LOG.Write(ex.Message); } return(false); } return(true); }
public static bool UploadZip(string RcaseId, string studyId, string zipPath, string username, string DbCaseId, string stydyUid) { try { var fi = new FileInfo(zipPath); byte[] data = File.ReadAllBytes(zipPath); string responseFromServer = null; try { var api = ACFG.GetSiteApiDetails(); var user = AOA.GetUserRefreshIfNecessary(username, DbCaseId); //WebRequest request = WebRequest.Create(api.cases_url + RcaseId + "/studies/" + studyId + "/images"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(api.cases_url + RcaseId + "/studies/" + studyId + "/images"); request.ContentType = "application/zip"; request.Method = "POST"; request.ServicePoint.Expect100Continue = true; request.Timeout = 60 * 60 * 1000; request.Method = "POST"; request.ContentType = "application/zip"; 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 upload zip: " + fi.Name, "API", errorResponse, DbCaseId, stydyUid); } return(false); } var respObj = JsonConvert.DeserializeObject <UploadResponse>(responseFromServer); LOG.Write("Uploaded Filename: " + respObj.filename); LOG.InsertEvent("Successfully uploaded ZIP", "API", responseFromServer, DbCaseId, stydyUid); return(true); } 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, DbCaseId, stydyUid); return(false); } finally { GC.Collect(); } }
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(); } }
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); } }
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); } }
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(); } }
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); } }
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); } }
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(); } }