Ejemplo n.º 1
0
        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();
        }
Ejemplo n.º 2
0
        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)));
                    }
                }
            }
        }
Ejemplo n.º 3
0
        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);
            }
        }
Ejemplo n.º 4
0
            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 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);
            }
        }
Ejemplo n.º 6
0
        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);
            }
        }
Ejemplo n.º 7
0
        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 static void ReportTaskProgress(IBackgroundTaskContext context, int index, int total, string message)
 {
     if (context != null)
     {
         context.ReportProgress(new BackgroundTaskProgress(index, total, message));
     }
 }
Ejemplo n.º 9
0
        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));
        }
Ejemplo n.º 10
0
            private void ReportProgress(string message, int currentStep)
            {
                if (_taskContext == null)
                {
                    return;
                }

                int percent = Math.Min((int)(currentStep / (float)NumberOfImagesToExport * 100), 100);

                _taskContext.ReportProgress(new BackgroundTaskProgress(percent, message));
            }
Ejemplo n.º 11
0
        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();
                }
            }
        }
Ejemplo n.º 12
0
            private ICollection <string> GetFilesToImport()
            {
                lock (_waitShowProgressLock)
                {
                    try
                    {
                        _taskContext.ReportProgress(new BackgroundTaskProgress(0, SR.MessageEnumeratingFiles));
                        List <string> files = new List <string>();
                        foreach (string file in GetFiles(_paths))
                        {
                            if (_taskContext.CancelRequested)
                            {
                                break;
                            }

                            files.Add(file);

                            if (!_showProgress && files.Count >= 10)
                            {
                                _showProgress = true;
                                Monitor.Pulse(_waitShowProgressLock);
                                Monitor.Wait(_waitShowProgressLock);
                            }
                        }

                        return(files);
                    }
                    finally
                    {
                        if (!_showProgress)
                        {
                            Monitor.Pulse(_waitShowProgressLock);
                            Monitor.Wait(_waitShowProgressLock);
                        }
                    }
                }
            }
Ejemplo n.º 13
0
        public void Update(object sender, PrintScu.ProgressUpdateEventArgs args)
        {
            SendOrPostCallback sendOrPostCallback = null;

            if (Task.CancelRequested)
            {
                Task.ReportProgress(new BackgroundTaskProgress(100, this.Cancel));
                printScu.Cancel();
            }
            else if (args.NumberOfImageBoxesSent == 0)
            {
                Task.ReportProgress(new BackgroundTaskProgress(0, dicomPrintManager.StatusMessage));
            }
            else
            {
                if (args.NumberOfImageBoxesSent == dicomPrintManager.PrintSession.SelectPresentationsCollection.Count)
                {
                    this.Task.ReportProgress(new BackgroundTaskProgress(100, Scuess));
                }
                else
                {
                    if (dicomPrintManager.ProgressDialog.ProgressBarStyle == Macro.Desktop.ProgressBarStyle.Marquee)
                    {
                        if (sendOrPostCallback == null)
                        {
                            sendOrPostCallback = this.ProgressBarStyle;
                        }
                        dicomPrintManager.UISynchronizationContext.Post(sendOrPostCallback, null);
                    }
                    int    index   = args.NumberOfImageBoxesSent - 1;
                    int    total   = dicomPrintManager.PrintSession.SelectPresentationsCollection.Count;
                    string message = string.Format(this.Format, dicomPrintManager.PrintSession.DicomPrinter.Name, args.NumberOfImageBoxesSent, total);
                    Task.ReportProgress(new BackgroundTaskProgress(index, total, message));
                }
            }
        }
        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 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;
                }
            }
        }
Ejemplo n.º 17
0
        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);
            }
        }
Ejemplo n.º 18
0
        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);
            }
        }
Ejemplo n.º 19
0
        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 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);
        }
Ejemplo n.º 21
0
		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);
			}
		}
Ejemplo n.º 22
0
        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;
            }
        }
Ejemplo n.º 23
0
		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;
			}
		}
Ejemplo n.º 24
0
		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 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();
		}
Ejemplo n.º 26
0
        private void Rename(IBackgroundTaskContext context)
        {
            try
            {
                _tempPath = String.Format(".\\temp\\{0}", Path.GetRandomFileName());
                Directory.CreateDirectory(_tempPath);
                _tempPath = Path.GetFullPath(_tempPath);

                context.ReportProgress(new BackgroundTaskProgress(0, "Renaming Study"));

                int numberOfSops = LocalStudyLoader.Start(new StudyLoaderArgs(this.Context.SelectedStudy.StudyInstanceUid, null));
                if (numberOfSops <= 0)
                {
                    return;
                }

                for (int i = 0; i < numberOfSops; ++i)
                {
                    string message = String.Format("{0} of {1}", i.ToString(), numberOfSops.ToString());
                    Platform.Log(LogLevel.Info, message);

                    Sop sop = LocalStudyLoader.LoadNextSop();
                    ILocalSopDataSource localsource = (ILocalSopDataSource)sop.DataSource;
                    string    progressMessage       = localsource.Filename.ToString();
                    DicomFile file = ((ILocalSopDataSource)sop.DataSource).File;

                    //renamer.Anonymize(file);

                    StudyData originalData = new StudyData();
                    file.DataSet.LoadDicomFields(originalData);

                    originalData.PatientId         = _component.PatientId;
                    originalData.PatientsBirthDate = _component.PatientsBirthDate;
                    originalData.PatientsNameRaw   = _component.PatientsName;
                    originalData.AccessionNumber   = _component.AccessionNumber;
                    originalData.StudyDate         = _component.StudyDate;
                    originalData.StudyDescription  = _component.StudyDescription;

                    file.DataSet.SaveDicomFields(originalData);

                    file.Save(String.Format("{0}\\{1}.dcm", _tempPath, i));

                    int progressPercent = (int)Math.Floor((i + 1) / (float)numberOfSops * 100);
                    //string progressMessage = String.Format(SR.MessageAnonymizingStudy, _tempPath);

                    context.ReportProgress(new BackgroundTaskProgress(progressPercent, progressMessage));

                    // This code deletes the study from the database, so that when it is re-imported the changed fields
                    // will appear
                }


                using (IDataStoreStudyRemover studyRemover = DataAccessLayer.GetIDataStoreStudyRemover())
                {
                    studyRemover.RemoveStudy(this.Context.SelectedStudy.StudyInstanceUid);
                }

                //trigger an import of the Renamed files.
                LocalDataStoreServiceClient client = new LocalDataStoreServiceClient();
                client.Open();
                try
                {
                    FileImportRequest request = new FileImportRequest();
                    request.BadFileBehaviour    = BadFileBehaviour.Move;
                    request.FileImportBehaviour = FileImportBehaviour.Move;
                    List <string> filePaths = new List <string>();
                    filePaths.Add(_tempPath);
                    request.FilePaths = filePaths;
                    request.Recursive = true;
                    client.Import(request);
                    client.Close();

                    //  Need to refresh study list in order for changed values to appear
                    //  This method doesn't work.  Need to manually click 'Search' again
                    //this.Context.RefreshStudyList();
                }
                catch
                {
                    client.Abort();
                    throw;
                }
                //this.Context.RefreshStudyList();
                context.Complete();
            }
            catch (Exception e)
            {
                context.Error(e);
            }
        }
Ejemplo n.º 27
0
        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 InitComposer(IBackgroundTaskContext context)
        {
            const float WGT_SCAN = 10f;
            const float WGT_INIT = 90f;

            List <IPresentationImage> queue = new List <IPresentationImage>();
            int count = 0;
            int total = this.Context.ClipboardItems.Count;

            context.ReportProgress(new BackgroundTaskProgress(0, SR.MessageScanningClipboard));
            foreach (IClipboardItem item in this.Context.ClipboardItems)
            {
                if (item.Item is IPresentationImage)
                {
                    Enqueue(queue, (IPresentationImage)item.Item);
                }
                else if (item.Item is IDisplaySet)
                {
                    Enqueue(queue, (IDisplaySet)item.Item);
                }
                else if (item.Item is IImageSet)
                {
                    Enqueue(queue, (IImageSet)item.Item);
                }

                count++;
                if (context.CancelRequested)
                {
                    break;
                }

                context.ReportProgress(new BackgroundTaskProgress((int)(WGT_SCAN * count / total), SR.MessageScanningClipboard));
            }

            if (!context.CancelRequested)
            {
                StudyComposerComponent composer = new StudyComposerComponent();
                total = queue.Count;
                for (int n = 0; n < queue.Count; n++)
                {
                    if (context.CancelRequested)
                    {
                        break;
                    }

                    IPresentationImage image = queue[n];
                    context.ReportProgress(new BackgroundTaskProgress((int)(WGT_SCAN + WGT_INIT * n / total), SR.MessageReadingImages));
                    composer.InsertImage(image);
                }

                if (!context.CancelRequested)
                {
                    context.ReportProgress(new BackgroundTaskProgress(100, SR.Done));
                    _composer = composer;
                    context.Complete(null);
                }
            }

            if (context.CancelRequested)
            {
                context.Cancel();
            }
        }
Ejemplo n.º 29
0
 private void BackgroundTaskReportStatus(IBackgroundTaskContext Context, string message, int percent)
 {
     _statusMessage = message;
     Context.ReportProgress(new BackgroundTaskProgress(percent, _statusMessage));
 }
Ejemplo n.º 30
0
        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 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);
			}
		}
Ejemplo n.º 32
0
		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();
				}
			}
		}