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 async ValueTask Handle(IBackgroundTaskContext context) { if (context.BackgroundTask is not ReadBackgroundTask readBackgroundTask) { return; } try { var physicalDrives = await physicalDriveManager.GetPhysicalDrives(); var commandHelper = new CommandHelper(); var readCommand = new ReadCommand(loggerFactory.CreateLogger <ReadCommand>(), commandHelper, physicalDrives, readBackgroundTask.SourcePath, readBackgroundTask.DestinationPath); readCommand.DataProcessed += async(_, args) => { await progressHubConnection.UpdateProgress(new Progress { Title = readBackgroundTask.Title, IsComplete = false, PercentComplete = args.PercentComplete, BytesProcessed = args.BytesProcessed, BytesRemaining = args.BytesRemaining, BytesTotal = args.BytesTotal, MillisecondsElapsed = args.PercentComplete > 0 ? (long)args.TimeElapsed.TotalMilliseconds : new long?(), MillisecondsRemaining = args.PercentComplete > 0 ? (long)args.TimeRemaining.TotalMilliseconds : new long?(), MillisecondsTotal = args.PercentComplete > 0 ? (long)args.TimeTotal.TotalMilliseconds : new long?() }, context.Token); }; var result = await readCommand.Execute(context.Token); await progressHubConnection.UpdateProgress(new Progress { Title = readBackgroundTask.Title, IsComplete = true, HasError = result.IsFaulted, ErrorMessage = result.IsFaulted ? result.Error.Message : null, PercentComplete = 100 }, context.Token); } catch (Exception e) { await progressHubConnection.UpdateProgress(new Progress { Title = readBackgroundTask.Title, IsComplete = true, HasError = true, ErrorMessage = e.Message, PercentComplete = 100 }, context.Token); } }
private void Process(IBackgroundTaskContext context) { try { _taskContext = context; ICollection <string> files = GetFilesToImport(); if (files.Count > 0 && !_taskContext.CancelRequested) { ConvertFiles(files); ImportFiles(); } } catch (Exception e) { Platform.Log(LogLevel.Error, e); _error = e; } if (_taskContext.CancelRequested) { _taskContext.Cancel(); } else { _taskContext.Complete(); } }
private static void ReportTaskProgress(IBackgroundTaskContext context, int index, int total, string message) { if (context != null) { context.ReportProgress(new BackgroundTaskProgress(index, total, message)); } }
private void DoMoveFolderAsync(IBackgroundTaskContext context) { var list = context.UserState as SortableResultList <ScanResultEntry>; int entryCount = list.Count; int counter = 0; foreach (ScanResultEntry entry in list) { if (context.CancelRequested) { break; } DirectoryInfo dir = new DirectoryInfo(entry.Path); if (dir.Exists) { string path = System.IO.Path.Combine(folderBrowserDialog1.SelectedPath, dir.Name); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } DirectoryUtility.Move(entry.Path, path); counter++; context.ReportProgress(new BackgroundTaskProgress(counter * 100 / entryCount, String.Empty)); } } }
public async ValueTask Handle(IBackgroundTaskContext context) { if (context.BackgroundTask is not PhysicalDriveInfoBackgroundTask infoBackgroundTask) { return; } var physicalDrives = await physicalDriveManager.GetPhysicalDrives(); var commandHelper = new CommandHelper(); var logger = loggerFactory.CreateLogger <InfoCommand>(); var infoCommand = new InfoCommand(logger, commandHelper, physicalDrives, infoBackgroundTask.Path); infoCommand.DiskInfoRead += async(_, args) => { await resultHubConnection.SendInfoResult(args.MediaInfo.ToViewModel()); }; var result = await infoCommand.Execute(context.Token); if (result.IsFaulted) { await errorHubConnection.UpdateError(result.Error.Message, context.Token); } }
private void UpdateProgressBar(IBackgroundTaskContext context) { //TODO (CR Sept 2010): just use a timer, and all this could be done on the UI thread. while (!context.CancelRequested) { // if we didn't get a SynchronizationContext from the thread that calls .Draw(), then we can't update the progress bar SynchronizationContext synchronizationContext = _synchronizationContext; if (synchronizationContext == null) { break; } Box box = new Box(); synchronizationContext.Send(s => { if (this.ParentPresentationImage != null) { ((Box)s).Value = this.ParentPresentationImage.Visible; this.Draw(); } }, box); if (context.CancelRequested || !box.Value) { break; } Thread.Sleep(_animationTick); } }
public async ValueTask Handle(IBackgroundTaskContext context) { if (context.BackgroundTask is not ImageFileVerifyBackgroundTask verifyBackgroundTask) { return; } try { var commandHelper = new CommandHelper(); var verifyCommand = new VerifyCommand(loggerFactory.CreateLogger <VerifyCommand>(), commandHelper, Enumerable.Empty <IPhysicalDrive>(), verifyBackgroundTask.SourcePath, verifyBackgroundTask.DestinationPath); verifyCommand.DataProcessed += async(_, args) => { await progressHubContext.SendProgress(new Progress { Title = verifyBackgroundTask.Title, IsComplete = false, PercentComplete = args.PercentComplete, BytesProcessed = args.BytesProcessed, BytesRemaining = args.BytesRemaining, BytesTotal = args.BytesTotal, MillisecondsElapsed = args.PercentComplete > 0 ? (long)args.TimeElapsed.TotalMilliseconds : new long?(), MillisecondsRemaining = args.PercentComplete > 0 ? (long)args.TimeRemaining.TotalMilliseconds : new long?(), MillisecondsTotal = args.PercentComplete > 0 ? (long)args.TimeTotal.TotalMilliseconds : new long?() }, context.Token); }; var result = await verifyCommand.Execute(context.Token); await progressHubContext.SendProgress(new Progress { Title = verifyBackgroundTask.Title, IsComplete = true, HasError = result.IsFaulted, ErrorMessage = result.IsFaulted ? result.Error.Message : null, PercentComplete = 100 }, context.Token); } catch (Exception e) { await progressHubContext.SendProgress(new Progress { Title = verifyBackgroundTask.Title, IsComplete = true, HasError = true, ErrorMessage = e.Message, PercentComplete = 100 }, context.Token); } }
private void UpdateProgress(IBackgroundTaskContext context, string status, int batch, int lineCount) { int importedRows = Math.Min(batch * _batchSize, lineCount); float percentage = (lineCount == 0) ? 0 : 100 * ((float)importedRows) / (float)lineCount; string message = string.Format("{0} - processed {1} rows.", status, importedRows); context.ReportProgress(new BackgroundTaskProgress((int)percentage, message)); }
private void ExportImages(IBackgroundTaskContext context, ref List <IPresentationImage> imagesToDispose) { ExportImageParams exportParams = new ExportImageParams(); exportParams.Scale = Scale; exportParams.ExportOption = _exportOption; exportParams.DisplayRectangle = _clipboardItem.DisplayRectangle; exportParams.SizeMode = SizeMode; exportParams.OutputSize = new Size(Width, Height); exportParams.BackgroundColor = BackgroundColor; using (Avi.VideoStreamWriter writer = new Avi.VideoStreamWriter(_selectedCodec)) { if (!UseDefaultQuality) { writer.Quality = _quality; } for (int i = 0; i < NumberOfImages; ++i) { if (context != null && context.CancelRequested) { break; } if (context != null) { int number = i + 1; string message = String.Format(SR.MessageFormatExportingFrame, number, NumberOfImages); ReportProgress(context, message, number); } IPresentationImage image = ImageExporter.ClonePresentationImage(DisplaySet.PresentationImages[i]); imagesToDispose.Add(image); using (Bitmap bitmap = ImageExporter.DrawToBitmap(image, exportParams)) { if (!writer.IsOpen) { //many codecs (like DivX) expect width and/or height to be divisible by 4. int width = NormalizeDimension(bitmap.Width); int height = NormalizeDimension(bitmap.Height); writer.Width = width; writer.Height = height; writer.FrameRate = this.FrameRate; writer.Open(this.FilePath); } writer.AddBitmap(bitmap); } } } }
private void DoImport(IBackgroundTaskContext context) { int lineCount = 0; int batch = 0; try { lineCount = PrescanFile(); using (StreamReader reader = File.OpenText(_filename)) { // treat as csv List <string> lines = null; while ((lines = ReadLines(reader, _batchSize)).Count > 0) { if (context.CancelRequested) { break; } try { Platform.GetService <IImportService>( delegate(IImportService service) { service.ImportCsv(new ImportCsvRequest(_importType, lines)); }); } catch (FaultException <ImportException> e) { // unwrap the fault exception throw e.Detail; } UpdateProgress(context, "Importing", batch++, lineCount); } } if (context.CancelRequested) { UpdateProgress(context, "Cancelled", batch, lineCount); context.Cancel(); } else { UpdateProgress(context, "Completed", batch, lineCount); context.Complete(null); } } catch (Exception e) { UpdateProgress(context, "Error", batch, lineCount); context.Error(e); } }
private void ReportProgress(IBackgroundTaskContext context, string message, int currentStep) { if (context == null) { return; } int percent = Math.Min((int)(currentStep / (float)NumberOfImages * 100), 100); context.ReportProgress(new BackgroundTaskProgress(percent, message)); }
private void DoPrint(IBackgroundTaskContext context) { try { if (_selectPresentationsInformations == null || _selectPresentationsInformations.Count == 0) { return; } Thread.Sleep(20); BackgroundTaskReportStatus(context, "Dicom打印开始", 0); Thread.Sleep(10); BackgroundTaskReportStatus(context, "开始处理图像...", 0); Thread.Sleep(10); //UISynchronizationContext.Send(DoImageProcess, null); DoImageProcess(null); if (_selectPresentationsInformations.Count == 0) { BackgroundTaskReportStatus(context, "处理图像处理结果为0", 0); return; } BackgroundTaskReportStatus(context, "开始向打印机发送图像", 0); Thread.Sleep(10); PrintScu scu = new PrintScu(); DicomPrintProgressUpdate progressUpdate = new DicomPrintProgressUpdate(); progressUpdate.dicomPrintManager = this; progressUpdate.printScu = scu; progressUpdate.Task = context; scu.ProgressUpdated += progressUpdate.Update; _dicomPrintSession = new DicomPrintSession(DicomPrinter, new SelectPresentationsInformationsCollection(_selectPresentationsInformations)); PrintScu.FilmSession filmSession = DicomPrintSession.GetFilmSession(_dicomPrintSession.SelectPresentationsCollection, _dicomPrintSession.DicomPrinter.Config); DicomState dicomState = scu.Print("MacroAETile", _dicomPrintSession.DicomPrinter.AETitle, _dicomPrintSession.DicomPrinter.Host, _dicomPrintSession.DicomPrinter.Port, filmSession); scu.Join(); if (dicomState == DicomState.Success) { //UpDicomPrintStatus(context); if (_dicomPrintComponent != null) { UISynchronizationContext.Send(_dicomPrintComponent.PrintedDeleteImage, this); } } } catch (Exception e) { Platform.Log(LogLevel.Debug, e); BackgroundTaskReportStatus(context, e.Message, 100); } if (_studyInstanceUid != null) { _studyInstanceUid.Clear(); _studyInstanceUid = null; } GC.Collect(); }
private void StartScaning(IBackgroundTaskContext context) { FolderScanner owner = context.UserState as FolderScanner; DirectoryInfo dir = new DirectoryInfo(owner.Path); int dirCount = 0; if (dir.Exists) { context.ReportProgress(new BackgroundTaskProgress(0, "Starting..")); DirectoryInfo[] subDirs = dir.GetDirectories(); _foldersCount = subDirs.Length; string path = dir.FullName.TrimEnd(new[] { System.IO.Path.DirectorySeparatorChar }); string[] dirs = path.Split(new [] { System.IO.Path.DirectorySeparatorChar }); string partitionFolder = dirs.Length >= 2 ? dirs[dirs.Length - 2] : string.Empty; ServerEntityKey partitionKey = GetPartitionKey(partitionFolder); if (partitionKey == null) { context.ReportProgress(new BackgroundTaskProgress(100, "Folder does not match a partition...")); return; } foreach (DirectoryInfo subDir in subDirs) { if (context.CancelRequested) { break; } try { var result = ProcessDir(subDir, partitionKey); ScanResultSet.Results.Add(result); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { dirCount++; context.ReportProgress(new BackgroundTaskProgress(dirCount * 100 / _foldersCount, String.Format("Scanning {0}", subDir.FullName))); } } } }
private void Go(IBackgroundTaskContext context) { string studyUid = DicomUid.GenerateUid().UID; string seriesUid = DicomUid.GenerateUid().UID; PixelAspectRatioChanger changer = new PixelAspectRatioChanger { IncreasePixelDimensions = _component.IncreasePixelDimensions, NewAspectRatio = new PixelAspectRatio(_component.AspectRatioRow, _component.AspectRatioColumn), RemoveCalibration = _component.RemoveCalibration }; int i = 0; context.ReportProgress(new BackgroundTaskProgress(i, _dicomFileNames.Count, "Exporting ...")); try { foreach (string originalFile in _dicomFileNames) { var file = new DicomFile(originalFile); file.Load(DicomReadOptions.None); string sopInstanceUid = DicomUid.GenerateUid().UID; file.DataSet[DicomTags.StudyInstanceUid].SetStringValue(studyUid); file.DataSet[DicomTags.SeriesInstanceUid].SetStringValue(seriesUid); file.DataSet[DicomTags.SopInstanceUid].SetStringValue(sopInstanceUid); changer.ChangeAspectRatio(file); string outputFileName = Path.Combine(_outputDirectory, String.Format("{0}.dcm", sopInstanceUid)); file.Save(outputFileName); if (context.CancelRequested) { context.Cancel(); return; } context.ReportProgress(new BackgroundTaskProgress(++i, _dicomFileNames.Count + 1, "Exporting ...")); } } catch (Exception e) { context.Error(e); return; } context.Complete(); }
private void LoadVolume(IBackgroundTaskContext context) { try { ProgressTask mainTask = new ProgressTask(); mainTask.AddSubTask("BUILD", 90); mainTask.AddSubTask("LAYOUT", 10); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, string.Format(SR.MessageInitializingMpr, mainTask.Progress))); BackgroundTaskParams @params = (BackgroundTaskParams)context.UserState; Volume volume = Volume.Create(@params.Frames, delegate(int i, int count) { if (context.CancelRequested) { throw new BackgroundTaskCancelledException(); } if (i == 0) { mainTask["BUILD"].AddSubTask("", count); } mainTask["BUILD"][""].Increment(); string message = string.Format(SR.MessageBuildingMprVolumeProgress, mainTask.Progress, i + 1, count, mainTask["BUILD"].Progress); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, message)); }); mainTask["BUILD"].MarkComplete(); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, string.Format(SR.MessagePerformingMprWorkspaceLayout, mainTask.Progress))); //call layout here b/c it could take a while @params.SynchronizationContext.Send(delegate { _viewer = new MprViewerComponent(volume); _viewer.Layout(); }, null); mainTask["LAYOUT"].MarkComplete(); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, string.Format(SR.MessageDone, mainTask.Progress))); context.Complete(); } catch (BackgroundTaskCancelledException) { context.Cancel(); } catch (Exception ex) { context.Error(ex); } }
private static void LoadWorker(IBackgroundTaskContext context) { State state = context.UserState as State; if (state == null) { context.Cancel(); return; } context.ReportProgress(new BackgroundTaskProgress(0, 1000, SR.MessageLoading)); if (context.CancelRequested) { context.Cancel(); return; } List <string> fileList = new List <string>(); try { foreach (string path in state.Paths) { fileList.AddRange(EnumerateFiles(path, state.Recursive)); } } catch (Exception ex) { context.Error(ex); return; } for (int n = 0; n < fileList.Count; n++) { context.ReportProgress(new BackgroundTaskProgress(n, fileList.Count, SR.MessageLoading)); if (context.CancelRequested) { context.Cancel(); return; } state.SynchronizationContext.Send(i => state.Component.Load(fileList[(int)i]), n); } if (context.CancelRequested) { context.Cancel(); return; } context.Complete(); }
private VolumeData LoadVolume(IBackgroundTaskContext context) { // TODO (CR Apr 2013): Ideally, loading and unloading could be done with minimal locking; this way, // Unload actually has to wait for Load to finish and vice versa. I think a quicker way would be to // have a _loading field - have this method set it inside the lock, then proceed to do the load, // then set the _volume field when done. Have Unload check _loading and just return, otherwise set _volume to null. // Basically, you don't need to lock the entire load operation - you only need to guarantee that multiple loads // can't occur at once, and that Unload actually unloads it. // wait for synchronized access lock (_syncVolumeDataLock) { _largeObjectData.Lock(); try { // if the data is now available, return it immediately // (i.e. we were blocked because we were already reading the data) if (_volume != null) { return(_volume); } // load the volume data if (context == null) { _volume = VolumeData.Create(_frames); } else { _volume = VolumeData.Create(_frames, (n, count) => context.ReportProgress(new BackgroundTaskProgress(n, count, SR.MessageFusionInProgress))); } // update our stats _largeObjectData.BytesHeldCount = 2 * _volume.SizeInVoxels; _largeObjectData.LargeObjectCount = 1; _largeObjectData.UpdateLastAccessTime(); // regenerating the volume data takes a few seconds _largeObjectData.RegenerationCost = LargeObjectContainerData.PresetComputedData; // register with memory manager MemoryManager.Add(this); return(_volume); } finally { _largeObjectData.Unlock(); } } }
private void ChangeToSyntax(IBackgroundTaskContext context) { var study = (StudyTableItem)context.UserState; try { _tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ClearCanvas"); _tempPath = System.IO.Path.Combine(_tempPath, "Compression"); _tempPath = System.IO.Path.Combine(_tempPath, Path.GetRandomFileName()); string message = String.Format("Changing transfer syntax to: {0}", _syntax); context.ReportProgress(new BackgroundTaskProgress(0, message)); var loader = study.Server.GetService <IStudyLoader>(); int numberOfSops = loader.Start(new StudyLoaderArgs(study.StudyInstanceUid, null)); if (numberOfSops <= 0) { return; } for (int i = 0; i < numberOfSops; ++i) { Sop sop = loader.LoadNextSop(); if (sop != null) { if (sop.DataSource is ILocalSopDataSource) { string filename = Path.Combine(_tempPath, string.Format("{0}.dcm", i)); DicomFile file = ((ILocalSopDataSource)sop.DataSource).File; file.ChangeTransferSyntax(_syntax); file.Save(filename); } } int progressPercent = (int)Math.Floor((i + 1) / (float)numberOfSops * 100); context.ReportProgress(new BackgroundTaskProgress(progressPercent, message)); } //trigger an import of the anonymized files. var client = new DicomFileImportBridge(); client.ImportFileList(new List <string> { _tempPath }, BadFileBehaviourEnum.Move, FileImportBehaviourEnum.Move); context.Complete(); } catch (Exception e) { context.Error(e); } }
private void Complete() { if (IsAsynchronous) { ItemsToExport.ForEach(delegate(IClipboardItem item) { item.Unlock(); }); } _progressComponentShelf = null; //notify the owner that we're done. _exportComponent.OnMultipleImageExportComplete(_error); _error = null; _taskContext = null; }
private void ExportImages(IBackgroundTaskContext context) { List <IPresentationImage> imagesToDispose = new List <IPresentationImage>(); EventResult result = EventResult.Success; AuditedInstances exportedInstances = new AuditedInstances(); foreach (IPresentationImage image in this.DisplaySet.PresentationImages) { IImageSopProvider sopProv = image as IImageSopProvider; if (sopProv != null) { exportedInstances.AddInstance(sopProv.ImageSop.PatientId, sopProv.ImageSop.PatientsName, sopProv.ImageSop.StudyInstanceUid, this.FilePath); } } try { ReportProgress(context, SR.MessageCreatingVideo, 0); ExportImages(context, ref imagesToDispose); if (context != null) { if (context.CancelRequested) { ReportProgress(context, SR.MessageCancelled, NumberOfImages); context.Cancel(); } else { ReportProgress(context, SR.MessageExportComplete, NumberOfImages); context.Complete(); } } } catch (Exception e) { _error = e; result = EventResult.SeriousFailure; Platform.Log(LogLevel.Error, e); } finally { AuditHelper.LogExportStudies(exportedInstances, EventSource.CurrentUser, result); imagesToDispose.ForEach(delegate(IPresentationImage image) { image.Dispose(); }); } }
public async ValueTask Handle(IBackgroundTaskContext context) { if (context.BackgroundTask is not BlankBackgroundTask blankBackgroundTask) { return; } try { await progressHubContext.SendProgress(new Progress { Title = blankBackgroundTask.Title, IsComplete = false, PercentComplete = 50, }, context.Token); var commandHelper = new CommandHelper(); var blankCommand = new BlankCommand(loggerFactory.CreateLogger <BlankCommand>(), commandHelper, blankBackgroundTask.Path, blankBackgroundTask.CompatibleSize ? Convert.ToInt64(blankBackgroundTask.Size * 0.95) : blankBackgroundTask.Size); var result = await blankCommand.Execute(context.Token); await Task.Delay(1000, context.Token); await progressHubContext.SendProgress(new Progress { Title = blankBackgroundTask.Title, IsComplete = true, HasError = result.IsFaulted, ErrorMessage = result.IsFaulted ? result.Error.Message : null, PercentComplete = 100 }, context.Token); } catch (Exception e) { await progressHubContext.SendProgress(new Progress { Title = blankBackgroundTask.Title, IsComplete = true, HasError = true, ErrorMessage = e.Message, PercentComplete = 100 }, context.Token); } }
private void UpDicomPrintStatus(IBackgroundTaskContext context) { try { BackgroundTaskReportStatus(context, "更新打印状态", 100); Thread.Sleep(10); string str = Path.Combine(Environment.CurrentDirectory, "PrintStatus.dll"); if (!File.Exists(str)) { this.BackgroundTaskReportStatus(context, "执行更新的DLL不存在", 100); Thread.Sleep(10); return; } Assembly assembly = Assembly.LoadFile(str); Type type = assembly.GetType("PrintStatus.StudyKeyList"); object list = Activator.CreateInstance(typeof(List <>).MakeGenericType(new Type[] { type }), (object[])null); MethodInfo listAdd = list.GetType().GetMethod("Add", BindingFlags.Public | BindingFlags.Instance); foreach (string studyInstanceUid in _studyInstanceUid) { object studyKeyList = assembly.CreateInstance("PrintStatus.StudyKeyList"); MethodInfo setSpecialNeeds = studyKeyList.GetType().GetMethod("set_Special_needs", BindingFlags.Public | BindingFlags.Instance); MethodInfo setStudyInstanceUid = studyKeyList.GetType().GetMethod("set_Study_instance_uid", BindingFlags.Public | BindingFlags.Instance); setSpecialNeeds.Invoke(studyKeyList, new object[] { "已打印" }); setStudyInstanceUid.Invoke(studyKeyList, new object[] { studyInstanceUid }); listAdd.Invoke(list, new object[] { studyKeyList }); } object study = assembly.CreateInstance("PrintStatus.Study"); bool flag = (bool)(study.GetType().GetMethod("UpdateStudySpecial_needs", BindingFlags.Public | BindingFlags.Instance).Invoke(study, new object[] { list })); if (flag) { BackgroundTaskReportStatus(context, "更新打印状态成功", 100); Thread.Sleep(10); } else { BackgroundTaskReportStatus(context, "更新打印状态失败", 100); Thread.Sleep(10); } } catch (Exception exception) { BackgroundTaskReportStatus(context, "更新打印状态失败:" + exception.Message, 100); Thread.Sleep(10); } }
public async ValueTask Handle(IBackgroundTaskContext context) { if (context.BackgroundTask is not OptimizeBackgroundTask optimizeBackgroundTask) { return; } try { await progressHubContext.SendProgress(new Progress { Title = optimizeBackgroundTask.Title, IsComplete = false, PercentComplete = 50, }, context.Token); var commandHelper = new CommandHelper(); var optimizeCommand = new OptimizeCommand(loggerFactory.CreateLogger <OptimizeCommand>(), commandHelper, optimizeBackgroundTask.Path); var result = await optimizeCommand.Execute(context.Token); await Task.Delay(1000, context.Token); await progressHubContext.SendProgress(new Progress { Title = optimizeBackgroundTask.Title, IsComplete = true, HasError = result.IsFaulted, ErrorMessage = result.IsFaulted ? result.Error.Message : null, PercentComplete = 100 }, context.Token); } catch (Exception e) { await progressHubContext.SendProgress(new Progress { Title = optimizeBackgroundTask.Title, IsComplete = true, HasError = true, ErrorMessage = e.Message, PercentComplete = 100 }, context.Token); } }
public async ValueTask Handle(IBackgroundTaskContext context) { var physicalDrives = await physicalDriveManager.GetPhysicalDrives(); var commandHelper = new CommandHelper(); var listCommand = new ListCommand(loggerFactory.CreateLogger <ListCommand>(), commandHelper, physicalDrives); listCommand.ListRead += async(_, args) => { await resultHubConnection.SendListResult(args.MediaInfos.Select(x => x.ToViewModel()).ToList()); }; var result = await listCommand.Execute(context.Token); if (result.IsFaulted) { await errorHubConnection.UpdateError(result.Error.Message, context.Token); } }
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); } }
private static void LoadWorker(IBackgroundTaskContext context) { State state = context.UserState as State; if (state == null) { context.Cancel(); return; } context.ReportProgress(new BackgroundTaskProgress(0, 1000, SR.MessageLoading)); if (context.CancelRequested) { context.Cancel(); return; } List<string> fileList = new List<string>(); foreach (string path in state.Paths) fileList.AddRange(EnumerateFiles(path, state.Recursive)); for (int n = 0; n < fileList.Count; n++) { context.ReportProgress(new BackgroundTaskProgress(n, fileList.Count, SR.MessageLoading)); if (context.CancelRequested) { context.Cancel(); return; } state.SynchronizationContext.Send(delegate { state.Component.Load(fileList[n]); }, null); } if (context.CancelRequested) { context.Cancel(); return; } context.Complete(); }
private void Export(IBackgroundTaskContext context) { EventResult result = EventResult.Success; AuditedInstances exportedInstances = GetInstancesForAudit(ItemsToExport, this._exportComponent.ExportFilePath); try { _taskContext = context; Export(); } catch (Exception e) { _error = e; result = EventResult.SeriousFailure; Platform.Log(LogLevel.Error, e); } finally { AuditHelper.LogExportStudies(exportedInstances, EventSource.CurrentUser, result); _imagesToDispose.ForEach(delegate(IPresentationImage image) { image.Dispose(); }); } }
private async ValueTask ShowSaveDialogWorkItem(IBackgroundTaskContext context) { if (!HybridSupport.IsElectronActive) { return; } if (context.BackgroundTask is not ShowDialogBackgroundTask showDialogBackgroundTask) { return; } var browserWindow = Electron.WindowManager.BrowserWindows.FirstOrDefault(); if (browserWindow == null) { return; } var path = await Electron.Dialog.ShowSaveDialogAsync(browserWindow, new SaveDialogOptions { Title = showDialogBackgroundTask.Title, Filters = showDialogBackgroundTask.FileFilters.Select(x => new FileFilter { Name = x.Name, Extensions = x.Extensions.ToArray() }).ToArray(), DefaultPath = showDialogBackgroundTask.Path }); await showDialogResultContext.Clients.All.SendAsync("ShowDialogResult", new ShowDialogResult { Id = showDialogBackgroundTask.Id, IsSuccess = !string.IsNullOrWhiteSpace(path), Paths = new [] { path } }, context.Token); }
private void Run(IBackgroundTaskContext context) { SopGenerator[] generatorArray = _generator.ToArray(); int completedDayStudies = 0; DateTime currentDay = _startDate; int currentStudiesPerDay = currentDay.DayOfWeek == DayOfWeek.Saturday || currentDay.DayOfWeek == DayOfWeek.Sunday ? _studiesPerDay * _percentWeekend / 100 : _studiesPerDay; _completedStudies = 0; while (_completedStudies < _totalStudies - 1) { InsertStudy(generatorArray[_rand.Next(1, generatorArray.Length)], currentDay); completedDayStudies++; _completedStudies++; if (completedDayStudies > currentStudiesPerDay) { currentDay = currentDay.AddDays(1); currentStudiesPerDay = currentDay.DayOfWeek == DayOfWeek.Saturday || currentDay.DayOfWeek == DayOfWeek.Sunday ? _studiesPerDay * _percentWeekend / 100 : _studiesPerDay; completedDayStudies = 0; } if ((_completedStudies % 10) == 0) { context.ReportProgress(new BackgroundTaskProgress(_completedStudies, _totalStudies, "Studies Created")); } if (context.CancelRequested) { return; } } }
private VolumeData LoadVolume(IBackgroundTaskContext context) { // wait for synchronized access lock (_syncVolumeDataLock) { // if the data is now available, return it immediately // (i.e. we were blocked because we were already reading the data) if (_volume != null) { return(_volume); } // load the volume data if (context == null) { _volume = VolumeData.Create(_frames); } else { _volume = VolumeData.Create(_frames, (n, count) => context.ReportProgress(new BackgroundTaskProgress(n, count, SR.MessageFusionInProgress))); } // update our stats _largeObjectData.BytesHeldCount = 2 * _volume.SizeInVoxels; _largeObjectData.LargeObjectCount = 1; _largeObjectData.UpdateLastAccessTime(); // regenerating the volume data is easy when the source frames are already in memory! _largeObjectData.RegenerationCost = RegenerationCost.Low; // register with memory manager MemoryManager.Add(this); return(_volume); } }
private void ChangeToSyntax(IBackgroundTaskContext context) { var study = (StudyTableItem)context.UserState; try { _tempPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ClearCanvas"); _tempPath = System.IO.Path.Combine(_tempPath, "Compression"); _tempPath = System.IO.Path.Combine(_tempPath, Path.GetRandomFileName()); string message = String.Format("Changing transfer syntax to: {0}", _syntax); context.ReportProgress(new BackgroundTaskProgress(0, message)); var loader = study.Server.GetService<IStudyLoader>(); int numberOfSops = loader.Start(new StudyLoaderArgs(study.StudyInstanceUid, null, StudyLoaderOptions.Default)); if (numberOfSops <= 0) return; for (int i = 0; i < numberOfSops; ++i) { Sop sop = loader.LoadNextSop(); if (sop != null) { if (sop.DataSource is ILocalSopDataSource) { string filename = Path.Combine(_tempPath, string.Format("{0}.dcm", i)); DicomFile file = ((ILocalSopDataSource)sop.DataSource).File; file.ChangeTransferSyntax(_syntax); file.Save(filename); } } int progressPercent = (int)Math.Floor((i + 1) / (float)numberOfSops * 100); context.ReportProgress(new BackgroundTaskProgress(progressPercent, message)); } //trigger an import of the anonymized files. var client = new DicomFileImportBridge(); client.ImportFileList(new List<string> {_tempPath}, BadFileBehaviourEnum.Move, FileImportBehaviourEnum.Move); context.Complete(); } catch(Exception e) { context.Error(e); } }
private void UpdateProgressBar(IBackgroundTaskContext context) { //TODO (CR Sept 2010): just use a timer, and all this could be done on the UI thread. while (!context.CancelRequested) { // if we didn't get a SynchronizationContext from the thread that calls .Draw(), then we can't update the progress bar SynchronizationContext synchronizationContext = _synchronizationContext; if (synchronizationContext == null) break; Box box = new Box(); synchronizationContext.Send(s => { if (this.ParentPresentationImage != null) { ((Box) s).Value = this.ParentPresentationImage.Visible; this.Draw(); } }, box); if (context.CancelRequested || !box.Value) break; Thread.Sleep(_animationTick); } }
private void Anonymize(IBackgroundTaskContext context) { //TODO (Marmot) This probably should be its own WorkItem type and have it done in the background there. var study = (StudyTableItem) context.UserState; var anonymizedInstances = new AuditedInstances(); try { context.ReportProgress(new BackgroundTaskProgress(0, SR.MessageAnonymizingStudy)); var loader = study.Server.GetService<IStudyLoader>(); int numberOfSops = loader.Start(new StudyLoaderArgs(study.StudyInstanceUid, null)); if (numberOfSops <= 0) return; var anonymizer = new DicomAnonymizer {StudyDataPrototype = _component.AnonymizedData}; if (_component.PreserveSeriesData) { //The default anonymizer removes the series data, so we just clone the original. anonymizer.AnonymizeSeriesDataDelegate = original => original.Clone(); } // Setup the ImportFilesUtility to perform the import var configuration = DicomServer.GetConfiguration(); // setup auditing information var result = EventResult.Success; string patientsSex = null; for (int i = 0; i < numberOfSops; ++i) { using (var sop = loader.LoadNextSop()) { if (sop != null && (_component.KeepReportsAndAttachments || !IsReportOrAttachmentSopClass(sop.SopClassUid))) { //preserve the patient sex. if (patientsSex == null) anonymizer.StudyDataPrototype.PatientsSex = patientsSex = sop.PatientsSex ?? ""; var localSopDataSource = sop.DataSource as ILocalSopDataSource; if (localSopDataSource != null) { string filename = string.Format("{0}.dcm", i); DicomFile file = (localSopDataSource).File; // make sure we anonymize a new instance, not the same instance that the Sop cache holds!! file = new DicomFile(filename, file.MetaInfo.Copy(), file.DataSet.Copy()); anonymizer.Anonymize(file); // TODO (CR Jun 2012): Importing each file separately? Platform.GetService((IPublishFiles w) => w.PublishLocal(new List<DicomFile> {file})); string studyInstanceUid = file.DataSet[DicomTags.StudyInstanceUid].ToString(); string patientId = file.DataSet[DicomTags.PatientId].ToString(); string patientsName = file.DataSet[DicomTags.PatientsName].ToString(); anonymizedInstances.AddInstance(patientId, patientsName, studyInstanceUid); var progressPercent = (int)Math.Floor((i + 1) / (float)numberOfSops * 100); var progressMessage = String.Format(SR.MessageAnonymizingStudy, file.MediaStorageSopInstanceUid); context.ReportProgress(new BackgroundTaskProgress(progressPercent, progressMessage)); } } } } AuditHelper.LogCreateInstances(new[]{configuration.AETitle}, anonymizedInstances, EventSource.CurrentUser, result); context.Complete(); } catch (Exception e) { AuditHelper.LogCreateInstances(new[] { string.Empty }, anonymizedInstances, EventSource.CurrentUser, EventResult.MajorFailure); context.Error(e); } }
private VolumeData LoadVolume(IBackgroundTaskContext context) { // wait for synchronized access lock (_syncVolumeDataLock) { // if the data is now available, return it immediately // (i.e. we were blocked because we were already reading the data) if (_volume != null) return _volume; // load the volume data if (context == null) _volume = VolumeData.Create(_frames); else _volume = VolumeData.Create(_frames, (n, count) => context.ReportProgress(new BackgroundTaskProgress(n, count, SR.MessageFusionInProgress))); // update our stats _largeObjectData.BytesHeldCount = 2*_volume.SizeInVoxels; _largeObjectData.LargeObjectCount = 1; _largeObjectData.UpdateLastAccessTime(); // regenerating the volume data is easy when the source frames are already in memory! _largeObjectData.RegenerationCost = RegenerationCost.Low; // register with memory manager MemoryManager.Add(this); return _volume; } }
private void Run(IBackgroundTaskContext context) { SopGenerator[] generatorArray = _generator.ToArray(); int completedDayStudies = 0; DateTime currentDay = _startDate; int currentStudiesPerDay = currentDay.DayOfWeek == DayOfWeek.Saturday || currentDay.DayOfWeek == DayOfWeek.Sunday ? _studiesPerDay*_percentWeekend/100 : _studiesPerDay; _completedStudies = 0; while (_completedStudies < _totalStudies-1) { InsertStudy(generatorArray[_rand.Next(1,generatorArray.Length)],currentDay); completedDayStudies++; _completedStudies++; if (completedDayStudies > currentStudiesPerDay) { currentDay = currentDay.AddDays(1); currentStudiesPerDay = currentDay.DayOfWeek == DayOfWeek.Saturday || currentDay.DayOfWeek == DayOfWeek.Sunday ? _studiesPerDay * _percentWeekend / 100 : _studiesPerDay; completedDayStudies = 0; } if ((_completedStudies % 10) == 0) context.ReportProgress(new BackgroundTaskProgress(_completedStudies, _totalStudies, "Studies Created")); if (context.CancelRequested) return; } }
private VolumeData LoadVolume(IBackgroundTaskContext context) { // TODO (CR Apr 2013): Ideally, loading and unloading could be done with minimal locking; this way, // Unload actually has to wait for Load to finish and vice versa. I think a quicker way would be to // have a _loading field - have this method set it inside the lock, then proceed to do the load, // then set the _volume field when done. Have Unload check _loading and just return, otherwise set _volume to null. // Basically, you don't need to lock the entire load operation - you only need to guarantee that multiple loads // can't occur at once, and that Unload actually unloads it. // wait for synchronized access lock (_syncVolumeDataLock) { _largeObjectData.Lock(); try { // if the data is now available, return it immediately // (i.e. we were blocked because we were already reading the data) if (_volume != null) return _volume; // load the volume data if (context == null) _volume = VolumeData.Create(_frames); else _volume = VolumeData.Create(_frames, (n, count) => context.ReportProgress(new BackgroundTaskProgress(n, count, SR.MessageFusionInProgress))); // update our stats _largeObjectData.BytesHeldCount = 2*_volume.SizeInVoxels; _largeObjectData.LargeObjectCount = 1; _largeObjectData.UpdateLastAccessTime(); // regenerating the volume data takes a few seconds _largeObjectData.RegenerationCost = LargeObjectContainerData.PresetComputedData; // register with memory manager MemoryManager.Add(this); return _volume; } finally { _largeObjectData.Unlock(); } } }
private void LoadVolume(IBackgroundTaskContext context) { try { ProgressTask mainTask = new ProgressTask(); mainTask.AddSubTask("BUILD", 90); mainTask.AddSubTask("LAYOUT", 10); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, string.Format(SR.MessageInitializingMpr, mainTask.Progress))); BackgroundTaskParams @params = (BackgroundTaskParams) context.UserState; Volume volume = Volume.Create(@params.Frames, delegate(int i, int count) { if (context.CancelRequested) throw new BackgroundTaskCancelledException(); if (i == 0) mainTask["BUILD"].AddSubTask("", count); mainTask["BUILD"][""].Increment(); string message = string.Format(SR.MessageBuildingMprVolumeProgress, mainTask.Progress, i + 1, count, mainTask["BUILD"].Progress); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, message)); }); mainTask["BUILD"].MarkComplete(); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, string.Format(SR.MessagePerformingMprWorkspaceLayout, mainTask.Progress))); //call layout here b/c it could take a while @params.SynchronizationContext.Send(delegate { _viewer = new MprViewerComponent(volume); _viewer.Layout(); }, null); mainTask["LAYOUT"].MarkComplete(); context.ReportProgress(new BackgroundTaskProgress(mainTask.IntPercent, string.Format(SR.MessageDone, mainTask.Progress))); context.Complete(); } catch (BackgroundTaskCancelledException) { context.Cancel(); } catch (Exception ex) { context.Error(ex); } }
private void Process(IBackgroundTaskContext context) { try { _taskContext = context; ICollection<string> files = GetFilesToImport(); if (files.Count > 0 && !_taskContext.CancelRequested) { ConvertFiles(files); ImportFiles(); } } catch(Exception e) { Platform.Log(LogLevel.Error, e); _error = e; } if (_taskContext.CancelRequested) _taskContext.Cancel(); else _taskContext.Complete(); }
private void DoMoveFolderAsync(IBackgroundTaskContext context) { var list = context.UserState as SortableResultList<ScanResultEntry>; int entryCount = list.Count; int counter = 0; foreach (ScanResultEntry entry in list) { if (context.CancelRequested) break; DirectoryInfo dir = new DirectoryInfo(entry.Path); if (dir.Exists) { string path = System.IO.Path.Combine(folderBrowserDialog1.SelectedPath, dir.Name); if (!Directory.Exists(path)) Directory.CreateDirectory(path); DirectoryUtility.Move(entry.Path, path); counter++; context.ReportProgress(new BackgroundTaskProgress(counter*100/entryCount, String.Empty)); } } }
private void Complete() { if (IsAsynchronous) ItemsToExport.ForEach(delegate(IClipboardItem item) { item.Unlock(); }); _progressComponentShelf = null; //notify the owner that we're done. _exportComponent.OnMultipleImageExportComplete(_error); _error = null; _taskContext = null; }
private void StartScaning(IBackgroundTaskContext context) { FolderScanner owner = context.UserState as FolderScanner; DirectoryInfo dir = new DirectoryInfo(owner.Path); int dirCount = 0; if (dir.Exists) { context.ReportProgress(new BackgroundTaskProgress(0, "Starting..")); DirectoryInfo[] subDirs = dir.GetDirectories(); _foldersCount = subDirs.Length; string path = dir.FullName.TrimEnd(new[] {System.IO.Path.DirectorySeparatorChar}); string[] dirs = path.Split(new [] { System.IO.Path.DirectorySeparatorChar }); string partitionFolder = dirs.Length >= 2 ? dirs[dirs.Length - 2] : string.Empty; ServerEntityKey partitionKey = GetPartitionKey(partitionFolder); if (partitionKey==null) { context.ReportProgress(new BackgroundTaskProgress(100, "Folder does not match a partition...")); return; } foreach (DirectoryInfo subDir in subDirs) { if (context.CancelRequested) { break; } try { var result = ProcessDir(subDir, partitionKey); ScanResultSet.Results.Add(result); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { dirCount++; context.ReportProgress(new BackgroundTaskProgress(dirCount * 100 / _foldersCount, String.Format("Scanning {0}", subDir.FullName))); } } } }