private void DoExport(IBackgroundTaskContext context) { try { int i = 0; int fileCount = _files.Count; foreach (string filename in _files) { string message = String.Format(SR.MessageFormatExportingFiles, i + 1, fileCount); BackgroundTaskProgress progress = new BackgroundTaskProgress(i, fileCount, message); context.ReportProgress(progress); SaveFile(filename); if (_canceled || context.CancelRequested) { _canceled = true; context.Cancel(); return; } i++; } context.Complete(); } catch (Exception e) { context.Error(e); } }
public static void Create(IDesktopWindow desktopWindow, IImageViewer viewer) { IDisplaySet selectedDisplaySet = viewer.SelectedImageBox.DisplaySet; string name = String.Format("{0} - Dynamic TE", selectedDisplaySet.Name); IDisplaySet t2DisplaySet = new DisplaySet(name, ""); double currentSliceLocation = 0.0; BackgroundTask task = new BackgroundTask( delegate(IBackgroundTaskContext context) { int i = 0; foreach (IPresentationImage image in selectedDisplaySet.PresentationImages) { IImageSopProvider imageSopProvider = image as IImageSopProvider; if (imageSopProvider == null) { continue; } ImageSop imageSop = imageSopProvider.ImageSop; Frame frame = imageSopProvider.Frame; if (frame.SliceLocation != currentSliceLocation) { currentSliceLocation = frame.SliceLocation; try { DynamicTePresentationImage t2Image = CreateT2Image(imageSop, frame); t2DisplaySet.PresentationImages.Add(t2Image); } catch (Exception e) { Platform.Log(LogLevel.Error, e); desktopWindow.ShowMessageBox("Unable to create T2 series. Please check the log for details.", MessageBoxActions.Ok); break; } } string message = String.Format("Processing {0} of {1} images", i, selectedDisplaySet.PresentationImages.Count); i++; BackgroundTaskProgress progress = new BackgroundTaskProgress(i, selectedDisplaySet.PresentationImages.Count, message); context.ReportProgress(progress); } }, false); ProgressDialog.Show(task, desktopWindow, true, ProgressBarStyle.Blocks); viewer.LogicalWorkspace.ImageSets[0].DisplaySets.Add(t2DisplaySet); }
protected void RetrieveAnnotationsFromAimService(object[] searchResults) { string errorMsg = null; BackgroundTask task = new BackgroundTask( delegate(IBackgroundTaskContext context) { try { int cnt = 0; BackgroundTaskProgress progress; List <string> tmpAnnotations = new List <string>(); aim_dotnet.DcmModel dcmModel = new aim_dotnet.DcmModel(); foreach (AIMSearchResult result in searchResults) { cnt++; if (result.RetrievedAnnotation == null) { continue; } progress = new BackgroundTaskProgress(cnt, searchResults.Length + 1, "Saving Annotation " + cnt); context.ReportProgress(progress); string tmpFileName = System.IO.Path.GetTempFileName(); dcmModel.WriteAnnotationToFile(result.RetrievedAnnotation, tmpFileName); tmpAnnotations.Add(tmpFileName); } dcmModel = null; if (tmpAnnotations.Count > 0) { progress = new BackgroundTaskProgress(searchResults.Length, searchResults.Length + 1, "Importing Annotations"); context.ReportProgress(progress); this.ImportDicomFiles(tmpAnnotations); } } catch (Exception ex) { errorMsg = ex.Message; Platform.Log(LogLevel.Error, ex, "Failed to import annotation(s)"); } context.Complete(null); }, true); ProgressDialog.Show(task, this.Context.DesktopWindow, true, ProgressBarStyle.Blocks); if (!string.IsNullOrEmpty(errorMsg)) { this.Context.DesktopWindow.ShowMessageBox(errorMsg, MessageBoxActions.Ok); } }
public void Load(string[] files, IDesktopWindow desktop, out bool cancelled) { Platform.CheckForNullReference(files, "files"); _total = 0; _failed = 0; bool userCancelled = false; if (desktop != null) { BackgroundTask task = new BackgroundTask( delegate(IBackgroundTaskContext context) { for (int i = 0; i < files.Length; i++) { LoadSop(files[i]); int percentComplete = (int)(((float)(i + 1) / files.Length) * 100); string message = String.Format(SR.MessageFormatOpeningImages, i, files.Length); BackgroundTaskProgress progress = new BackgroundTaskProgress(percentComplete, message); context.ReportProgress(progress); if (context.CancelRequested) { userCancelled = true; break; } } context.Complete(null); }, true); ProgressDialog.Show(task, desktop, true, ProgressBarStyle.Blocks); cancelled = userCancelled; } else { foreach (string file in files) { LoadSop(file); } cancelled = false; } if (Failed > 0) { throw new LoadSopsException(Total, Failed); } }
private void BackgroundSendAnnotationsToAimService(IBackgroundTaskContext context) { var xmlAnnotations = context.UserState as Dictionary <string, string>; try { if (xmlAnnotations != null && xmlAnnotations.Count > 0) { var progress = new BackgroundTaskProgress(20, string.Format("Sending {0} annotation(s) to AIM data service.", xmlAnnotations.Count)); context.ReportProgress(progress); AIMTCGAService.AIMTCGASubmit.sendAIMTCGAAnnotation(new List <string>(xmlAnnotations.Values).ToArray()); } context.Complete(); } catch (Exception ex) { SaveAnnotationsToQueue(xmlAnnotations, AIMTCGAService.AIMTCGASubmit.ServiceUrl); context.Error(ex); } }
protected void RetrieveAnnotationsFromAimService(object[] searchResults) { string errorMsg = null; if (!AimDataServiceLoginTool.CredentialsValid) { AimDataServiceLoginTool.RequestLogin(); } var task = new BackgroundTask( delegate(IBackgroundTaskContext context) { try { int cnt = 0; BackgroundTaskProgress progress; var xmlFiles = new List <string>(); foreach (AimeAnnotationContainer result in searchResults) { cnt++; if (result.Annotations == null) { continue; } xmlFiles.Add(DownloadAnnotationFromWebService(result.AnnotationContainerUid)); progress = new BackgroundTaskProgress(cnt, searchResults.Length + 1, "Discovering Annotation " + cnt); context.ReportProgress(progress); } if (xmlFiles.Count > 0) { List <string> invalidFiles; List <string> tempDcmFiles = AimManager.ConvertAnnotationsFromXmlToDicomFiles(AimManager.DefaultAimVersion, xmlFiles, context, out invalidFiles); if (tempDcmFiles.Count > 0) { progress = new BackgroundTaskProgress(searchResults.Length, searchResults.Length + 1, "Importing Annotations"); context.ReportProgress(progress); ImportDicomFiles(tempDcmFiles); } } } catch (Exception ex) { // TODO: Smarter handling of invalid credentials/expiring credentials if (ex.Message.Contains("401")) { AimDataServiceLoginTool.Credentials = null; } errorMsg = ex.Message; Platform.Log(LogLevel.Error, ex, "Failed to import annotation(s)"); } context.Complete(null); }, true); ProgressDialog.Show(task, Context.DesktopWindow, true, ProgressBarStyle.Blocks); if (!string.IsNullOrEmpty(errorMsg)) { Context.DesktopWindow.ShowMessageBox(errorMsg, MessageBoxActions.Ok); } }
public void ReportProgress(BackgroundTaskProgress progress) { }
private string DownloadQueryResults(string sourceUrl, IBackgroundTaskContext context) { if (!string.IsNullOrEmpty(sourceUrl)) { string tempZipDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName())); string tempZipFile = tempZipDir + ".zip"; WebClient webClient = null; bool canceled = false; try { webClient = new WebClient(); bool downloadCompleted = false; webClient.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) { if (context != null) { string progressMsg; if (e.BytesReceived < 1000 * 1024) { progressMsg = string.Format("Retrieving images ({0:0.00}KB)", ((float)e.BytesReceived) / 1024); } else { progressMsg = string.Format("Retrieving images ({0:0.00}MB)", ((float)e.BytesReceived) / 1000 / 1024); } BackgroundTaskProgress progress = new BackgroundTaskProgress(1, 3, progressMsg); context.ReportProgress(progress); if (context.CancelRequested) { if (!canceled) { webClient.CancelAsync(); } context.Cancel(); canceled = true; } } }; webClient.DownloadFileCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { downloadCompleted = true; }; webClient.DownloadFileAsync(new Uri(sourceUrl), tempZipFile); //webClient.DownloadFile(sourceUrl, tempZipFile); while (!downloadCompleted) { System.Threading.Thread.Sleep(500); } if (!canceled) { if (context != null) { BackgroundTaskProgress progress = new BackgroundTaskProgress(1, 3, "Processing received images"); context.ReportProgress(progress); if (context.CancelRequested) { context.Cancel(); canceled = true; } } ZipUtil.UnZipFiles(tempZipFile, tempZipDir, "", false, true); try { File.Delete(tempZipFile); } catch (Exception) { } return(tempZipDir); } } finally { if (webClient != null) { webClient.Dispose(); } } } return(null); }
protected void RetrieveStudiesFromNBIA(List <string> studyUids) { string errorMsg = null; BackgroundTask task = new BackgroundTask( delegate(IBackgroundTaskContext context) { if (studyUids.Count == 0) { context.Complete(null); return; } try { BackgroundTaskProgress progress = new BackgroundTaskProgress(0, 3, "Querying for available images"); context.ReportProgress(progress); if (context.CancelRequested) { context.Cancel(); return; } NBIARetrieveByStudyUIDs nbiaRetrieveByStudyUIDs = new NBIARetrieveByStudyUIDs(); string url = nbiaRetrieveByStudyUIDs.retrieveStudyURL(studyUids.ToArray(), SearchSettings.Default.NBIADataServiceUrl); if (!string.IsNullOrEmpty(url)) { progress = new BackgroundTaskProgress(1, 3, "Retrieving images"); context.ReportProgress(progress); if (context.CancelRequested) { context.Cancel(); return; } string downloadedFilesFolder = this.DownloadQueryResults(url, context); if (!string.IsNullOrEmpty(downloadedFilesFolder)) { progress = new BackgroundTaskProgress(2, 3, "Importing images"); context.ReportProgress(progress); if (context.CancelRequested) { context.Cancel(); return; } string[] files = Directory.GetFiles(downloadedFilesFolder, "*.dcm", SearchOption.AllDirectories); if (files.Length > 0) { this.ImportDicomFiles(files); } } } } catch (Exception ex) { errorMsg = ex.Message; Platform.Log(LogLevel.Error, ex, "Failed to retrieve requested study(ies)"); } context.Complete(null); }, true); ProgressDialog.Show(task, this.Context.DesktopWindow, true, ProgressBarStyle.Blocks); if (!string.IsNullOrEmpty(errorMsg)) { this.Context.DesktopWindow.ShowMessageBox(errorMsg, MessageBoxActions.Ok); } }
private void InternalPrint(PrintJob job) { BasicFilmSessionModuleIod basicFilmSessionModuleIod = new BasicFilmSessionModuleIod { NumberOfCopies = job.Copies, MediumType = job.MediumType, FilmDestination = job.FilmDestination }; BasicFilmBoxModuleIod basicFilmBoxModuleIod = new BasicFilmBoxModuleIod { //ImageDisplayFormat = @"STANDARD\1,1", ImageDisplayFormat = ImageDisplayFormat.Standard_1x1, FilmSizeId = job.FilmSize, Illumination = job.Illumination, FilmOrientation = job.FilmOrientation, ReflectedAmbientLight = job.ReflectedAmbientLight, MagnificationType = job.MagnificationType }; IList <ImageBoxPixelModuleIod> imageBoxPixelModuleIods = new List <ImageBoxPixelModuleIod>(); bool userCancelled = false; BackgroundTask task = new BackgroundTask(delegate(IBackgroundTaskContext context) { try { BackgroundTaskProgress progress; ushort num = 1; int percent = 0; new List <string>(); ImageBoxPixelModuleIod item = new ImageBoxPixelModuleIod { ImageBoxPosition = 1 }; BasicGrayscaleImageSequenceIod iod2 = new BasicGrayscaleImageSequenceIod { PhotometricInterpretation = job.MonochormeType }; Size size = this.CalcMaxSize(job.Format, job.Images); Bitmap image = new Bitmap(size.Width, size.Height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); foreach (PreviewTile tile in job.Images) { percent = (int)((((float)(num - 1)) / ((float)job.Images.Count)) * 80f); num = (ushort)(num + 1); progress = new BackgroundTaskProgress(percent, string.Format(SR.CreatingImageBuffer, num, job.Images.Count)); context.ReportProgress(progress); if (tile.ImageData != null) { Platform.Log(LogLevel.Error, "TITLE IMAGEDATA"); Bitmap printImagePixel = tile.GetPrintImagePixel(false); float x = tile.NormalizedRectangle.X * size.Width; float y = tile.NormalizedRectangle.Y * size.Height; float width = tile.NormalizedRectangle.Width * size.Width; float height = tile.NormalizedRectangle.Height * size.Height; g.DrawImage(printImagePixel, x, y, width, height); g.DrawRectangle(Pens.White, x, y, width, height); Rectangle destination = new Rectangle(((int)x) + 2, ((int)y) + 2, ((int)width) - 4, ((int)height) - 4); try { IconCreator.DrawTextOverlay(g, destination, tile.ImageData); } catch (Exception ex) { Platform.Log(LogLevel.Error, " exception: " + ex.ToString()); } printImagePixel.Dispose(); if (context.CancelRequested) { userCancelled = true; break; } } } //clear foreach (PreviewTile tile in job.Images) { ImageSop sop = ((IImageSopProvider)tile.ImageData).ImageSop; string strUID = sop.SopInstanceUid; //获取UID 的 accession try { if (Conn.isOracle()) { string sqlstr = string.Format(" update examrecord set filmprint='{0}' where id=(select AccessionNumber from images where SopInstanceUID='{1}') and modulename='RIS' ", "1", strUID); OracleCommand sqlCmd = new OracleCommand(); sqlCmd.Connection = GlobalData.MainConn.ChangeTypeOracle(); sqlCmd.CommandText = sqlstr; sqlCmd.ExecuteNonQuery(); sqlCmd.Dispose(); } else { string sqlstr = string.Format(" update examrecord set filmprint='{0}' where id=(select AccessionNumber from images where SopInstanceUID='{1}') and modulename='RIS' ", "1", strUID); SqlCommand sqlCmd = new SqlCommand(); sqlCmd.Connection = GlobalData.MainConn.ChangeType(); sqlCmd.CommandText = sqlstr; sqlCmd.ExecuteNonQuery(); sqlCmd.Dispose(); Platform.Log(LogLevel.Error, " sql is " + sqlstr); } } catch (Exception ex) { Platform.Log(LogLevel.Error, "exception is " + ex.ToString()); } //tile.Dispose(); tile.RemoveImage(); } job.Images.Clear(); g.Dispose(); //iod2.AddBitmap(image); Unlock(); RasterImage lRasterImage = null; RasterCodecs lRasterCodecs = new RasterCodecs(); lRasterImage = RasterImageConverter.ConvertFromImage(image, ConvertFromImageOptions.None); lRasterCodecs.Save(lRasterImage, System.Windows.Forms.Application.StartupPath + @"\print.jpg", RasterImageFormat.Tif, 8); string lDicomFile = "1" + DateTime.Now.ToString("HHmmss", DateTimeFormatInfo.InvariantInfo); lRasterCodecs.Save(lRasterImage, System.Windows.Forms.Application.StartupPath + @"\PrintFiles\" + lDicomFile, RasterImageFormat.DicomGray, 16); //image.Save("d:\\test.jpg"); image.Dispose(); lRasterImage.Dispose(); lRasterCodecs.Dispose(); //item.BasicGrayscaleImageSequenceList.Add(iod2); //imageBoxPixelModuleIods.Add(item); if (userCancelled) { Platform.Log(LogLevel.Info, SR.UserCancel); } else { progress = new BackgroundTaskProgress(80, SR.BeginSendImage); context.ReportProgress(progress); PrintDicomFiles(lDicomFile, 1, 1, lDicomFile, job); //BasicGrayscalePrintScu scu = new BasicGrayscalePrintScu(); //scu.Print(job.Printer.AET, job.Printer.CalledAET, job.Printer.Host, job.Printer.Port, basicFilmSessionModuleIod, basicFilmBoxModuleIod, imageBoxPixelModuleIods); //if (scu.ResultStatus == DicomState.Success) //{ // this.UpdateStudyPrintStatus(this.GetStudyInstanceUIDs(job.Images)); // PrintToolComponent.TilesComponent.ResetTiles(); //} //else //{ // this._component.ShowMessageBox(SR.FilmError); //} } } catch (OutOfMemoryException) { Platform.Log(LogLevel.Error, "内存不够"); BackgroundTaskProgress progress2 = new BackgroundTaskProgress(100, SR.OutOfMemory); context.ReportProgress(progress2); this._component.ShowMessageBox(SR.OutOfMemory); } catch (Exception exception) { Platform.Log(LogLevel.Error, exception.Message); BackgroundTaskProgress progress3 = new BackgroundTaskProgress(100, exception.Message); context.ReportProgress(progress3); this._component.ShowMessageBox(SR.PrinterError); } finally { context.Complete(null); } }, true); ProgressDialog.Show(task, this._window, true, ProgressBarStyle.Blocks); }