public byte[] ComputeHash(Stream stream, IProgressReporter progressReporter, ProgressOperation operation) { // Throwing exception, if hash algorithm was disposed if (_isDisposed) { throw new ObjectDisposedException(nameof(Algorithm)); } // Shortcut, if length of stream is less than size of one package if (stream.Length <= 4096) { Debug.WriteLine("Stream.Length is less than 4096 bytes, computing of hash will be performed through standart method ComputeHash(Stream)"); return(ComputeHash(stream)); } // ... stream.Seek(0, SeekOrigin.Begin); progressReporter?.OnProgressChanged(operation, stream.Position, stream.Length); // ... var interval = 0; var buffer = new byte[4096]; // ... while (true) { var length = stream.Read(buffer, 0, buffer.Length); if (length < buffer.Length || stream.Position == stream.Length) { // End of stream, performing TransformFinalBlock Algorithm.TransformFinalBlock(buffer, 0, length); progressReporter?.OnProgressChanged(operation, stream.Length, stream.Length); return(Algorithm.Hash); } else { // Regular block transform Algorithm.TransformBlock(buffer, 0, buffer.Length, null, 0); } // If IProgressReporter has been specified if (progressReporter == null) { continue; } // Cancelling operation, if requested if (progressReporter.CancellationPending) { return(null); } // Reporting about progress each 250 kylobytes if (++interval > 60) { interval = 0; progressReporter.OnProgressChanged(operation, stream.Position, stream.Length); } } }
private void DeleteSelectedBlob() { Dialog.ConfirmYesOrNo("Are you sure you want ot delete blob " + (Grid.SelectedItem as CloudBlob).Name + "?", () => { var operation = new ProgressOperation() { Message = "Deleting blob ".ToConsoleString() + (Grid.SelectedItem as CloudBlob).Name.ToConsoleString(ConsoleColor.Yellow), State = OperationState.InProgress }; Application.MessagePump.QueueAsyncAction((Grid.SelectedItem as CloudBlob).DeleteAsync(), (tp) => { if (tp.Exception != null) { operation.State = OperationState.Failed; operation.Details = tp.Exception.ToString().ToConsoleString(); operation.Message = "Failed to delete blob ".ToConsoleString() + (Grid.SelectedItem as CloudBlob).Name.ToConsoleString(ConsoleColor.Yellow); } else { operation.State = OperationState.Completed; operation.Message = "Finished deleting blob ".ToConsoleString() + (Grid.SelectedItem as CloudBlob).Name.ToConsoleString(ConsoleColor.Yellow); } if (Application != null && PageStack.CurrentPage == this) { PageStack.TryRefresh(); } }); }); }
public static DialogResult ExecuteWithProgress(string title, ProgressOperation operation, ISynchronizeInvoke synchronizeInvoke, IWin32Window owner) { using (ProgressDialog progress = new ProgressDialog()) { progress.Text = title; MultipartAsyncOperation async = new MultipartAsyncOperation(synchronizeInvoke); async.AddProgressOperation(operation, new ProgressCategory(null, null), 100); progress.ProgressProvider = async; async.Start(); DialogResult result; if (!async.IsDone) { result = progress.ShowDialog(owner); } else { result = progress.DialogResult; } if (result == DialogResult.Cancel) { throw new OperationCancelledException(); } else if (result == DialogResult.Abort) { throw async.Exception; } else { return(result); } } }
private void OpenSelectedBlob() { var blob = Grid.SelectedItem as CloudBlob; var tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), GetFileName(blob)); var operation = new ProgressOperation() { State = OperationState.InProgress, Message = "Downloading blob ".ToConsoleString() + blob.Uri.ToString().ToConsoleString(ConsoleColor.Cyan) }; ProgressOperationManager.Operations.Add(operation); Application.MessagePump.QueueAsyncAction(blob.DownloadToFileAsync(tempFile, FileMode.OpenOrCreate), (t) => { if (t.Exception != null) { operation.State = OperationState.Failed; operation.Message = "Failed to delete blob ".ToConsoleString() + blob.Uri.ToString().ToConsoleString(ConsoleColor.Cyan); operation.Details = t.Exception.ToString().ToConsoleString(); } else { operation.State = OperationState.Completed; operation.Message = "Fiinished downloading blob ".ToConsoleString() + blob.Uri.ToString().ToConsoleString(ConsoleColor.Cyan); operation.Details = "The downloaded file is located here: ".ToConsoleString() + tempFile.ToConsoleString(ConsoleColor.Cyan); Process.Start(tempFile); } }); }
public void Start() { if (!CanStart) { return; } IsActive = true; IsSuccessful = false; IsCanceled = false; IsFailed = false; Task.Run(async() => { // Create cancellation token source _cancellationTokenSource = new CancellationTokenSource(); // Create progress operation ProgressOperation = ProgressManager.CreateOperation(); try { // If download option is not set - get the best download option if (DownloadOption == null) { DownloadOption = await _downloadService.GetBestDownloadOptionAsync(Video.Id, Format); } await _downloadService.DownloadVideoAsync(DownloadOption, FilePath, ProgressOperation, _cancellationTokenSource.Token); if (_settingsService.ShouldInjectTags) { await _taggingService.InjectTagsAsync(Video, Format, FilePath, _cancellationTokenSource.Token); } if (SubtitleOption != null && SubtitleOption.ClosedCaptionTrackInfos.Any()) { await _downloadService.DownloadSubtitleAsync(SubtitleOption, FilePath); } IsSuccessful = true; } catch (OperationCanceledException) { IsCanceled = true; } catch (Exception ex) { IsFailed = true; FailReason = ex.Message; } finally { IsActive = false; _cancellationTokenSource.Dispose(); ProgressOperation.Dispose(); } }); }
public ProgressWorker(ProgressOperation method, ProgressCategory category, ProgressOperationCompleted completedMethod, int progressSize, int progressTotal, IProgressHost progress) { WorkerMethod = method; _category = category; CompletedMethod = completedMethod; ProgressSize = progressSize; ParentProgress = progress; TotalProgressTicks = progressTotal; }
public void Start() { if (!CanStart) { return; } IsActive = true; IsSuccessful = false; IsCanceled = false; IsFailed = false; Task.Run(async() => { // Create cancellation token source _cancellationTokenSource = new CancellationTokenSource(); // Create progress operation ProgressOperation = ProgressManager.CreateOperation(); try { // daca nu sunt setate obtiuni de descarcare se foloseste setarea de baza // descarca video if (DownloadOption == null) { DownloadOption = await _downloadService.GetBestDownloadOptionAsync(Video.Id, Format); } await _downloadService.DownloadVideoAsync(DownloadOption, FilePath, ProgressOperation, _cancellationTokenSource.Token); if (_settingsService.ShouldInjectTags) { await _taggingService.InjectTagsAsync(Video, Format, FilePath, _cancellationTokenSource.Token); } IsSuccessful = true; } catch (OperationCanceledException) { IsCanceled = true; } catch (Exception ex) { IsFailed = true; FailReason = ex.Message; } finally { IsActive = false; _cancellationTokenSource.Dispose(); ProgressOperation.Dispose(); } }); }
} // static public ProgressWindow MakeProgressWindow(ProgressOperation operation) { ProgressWindow win = new ProgressWindow(); win.AutoClose = false; win.Show(); return(win); }
} // private void Cancel() { if (this._operation != null) { ProgressOperation op = this._operation; this.Operation = null; op.Cancel(); } }
/// <summary> /// Runs an operation asynchronously, with optional progress bar. /// </summary> /// <param name="operation"></param> /// <param name="showProgressWindow"></param> /// <returns></returns> static public async Task RunOperationAsync(ProgressOperation operation) { try { await Task.Run((Action)operation.Run); } catch (Exception e) { Log(e.ToString()); } finally { operation.Dispose(); } } // RunOperationAsync()
public void WatchProgress( ProgressOperation op ) { this.operation = op; if ( op != null ) { this.operation.ProgressChanged += this.OnProgress; this.UpdateDisplay( op.ProgressInformation ); } }
public void ProgressOperation_Report_Disposed_Test() { // Create operation var operation = new ProgressOperation(); // Report completion operation.Dispose(); // It shouldn't be possible to report progress anymore Assert.Throws <InvalidOperationException>(() => operation.Report(0.5)); }
private void ProgressComplete() { if ( this.autoClose ) { if ( this.operation != null ) { this.operation.ProgressChanged -= this.OnProgress; this.operation = null; } this.Close(); } }
private void UploadBlob() { Dialog.ShowTextInput("Choose file".ToConsoleString(), (f) => { var operation = new ProgressOperation() { Message = "Uploading file ".ToConsoleString() + f.ToConsoleString(), State = OperationState.Scheduled }; ProgressOperationManager.Operations.Add(operation); if (File.Exists(f.ToString()) == false) { operation.State = OperationState.Failed; operation.Message = "File not found - ".ToConsoleString() + f; } else { Dialog.ShowTextInput("Enter blob prefix".ToConsoleString(), (pre) => { var blobPath = System.IO.Path.Combine(pre.ToString(), System.IO.Path.GetFileName(f.ToString())); var blob = container.GetBlockBlobReference(blobPath); Application.MessagePump.QueueAsyncAction(blob.UploadFromFileAsync(f.ToString(), FileMode.Open), (t) => { if (t.Exception != null) { operation.State = OperationState.Failed; operation.Message = operation.Message = "Failed to upload file ".ToConsoleString() + f.ToConsoleString(); operation.Details = t.Exception.ToString().ToConsoleString(); } else { operation.State = OperationState.Completed; operation.Message = operation.Message = "Finished uploading file ".ToConsoleString() + f.ToConsoleString(); if (Application != null && PageStack.CurrentPage == this) { PageStack.TryRefresh(); } } }); }, () => { operation.State = OperationState.CompletedWithWarnings; operation.Message = "Cancelled uploading file ".ToConsoleString() + f.ToConsoleString(); }); } }); }
public void Start() { if (!CanStart) { return; } Task.Run(async() => { // Create cancellation token source _cancellationTokenSource = new CancellationTokenSource(); // Create progress operation ProgressOperation = ProgressManager.CreateOperation(); try { IsSuccessful = false; IsCanceled = false; IsFailed = false; IsActive = true; // If download option is not set - get the best download option if (DownloadOption == null) { DownloadOption = await _downloadService.GetBestDownloadOptionAsync(Video.Id, Format); } // Download await _downloadService.DownloadVideoAsync(DownloadOption, FilePath, ProgressOperation, _cancellationTokenSource.Token); IsSuccessful = true; } catch (OperationCanceledException) { IsCanceled = true; } catch (Exception ex) { IsFailed = true; FailReason = ex.Message; } finally { IsActive = false; _cancellationTokenSource.Dispose(); ProgressOperation.Dispose(); } }); }
public void ProgressOperation_Dispose_Test() { // Create operation var operation = new ProgressOperation(); // Assert initial state Assert.That(operation.IsCompleted, Is.False); // Report completion operation.Dispose(); // Assert final state Assert.That(operation.IsCompleted, Is.True); }
public void ProgressOperation_Report_Test() { // Create operation var operation = new ProgressOperation(); // Assert initial state Assert.That(operation.Progress, Is.Zero); // Report new progress const double newProgress = 0.5; operation.Report(newProgress); // Assert final state Assert.That(operation.Progress, Is.EqualTo(newProgress)); }
/// <summary> /// Adds a new ProgressOperation to the list of work to perform and assigns the operation /// the number of ticks that it should take up in the overall operation. /// </summary> /// <param name="operation">the progress-compatible method that will do some work</param> /// <param name="completed">method called when the operation is completed</param> /// <param name="tickSize">an arbitrary number that should reflect the percentage of the work that will be done by this operation. /// Note: longer running operations should have a larger tick count than fast executing operations.</param> public void AddProgressOperation(ProgressOperation operation, ProgressCategory category, ProgressOperationCompleted completed, int tickSize) { // if a category is being specified then the connected UI should know that // it can and should show categories if (category != null) showCategories = true; //wrap the operation with a ProgressWorker that can manage its execution ProgressWorker worker = new ProgressWorker(operation, category, completed, tickSize, 100, this); //add the worker to the list workers.Add(worker); //add the ticks assigned to this task to the overall tick count totalProgressTicks += tickSize; }
public void ProgressOperation_NotifyPropertyChanged_Test() { // Create operation var operation = new ProgressOperation(); // Subscribe to event var eventTriggerCount = 0; operation.PropertyChanged += (sender, args) => eventTriggerCount++; // Invoke changes operation.Report(0.1); operation.Report(0.3); operation.Dispose(); // Assert that the event was triggered accordingly Assert.That(eventTriggerCount, Is.GreaterThanOrEqualTo(3)); }
/// <summary> /// Adds a new ProgressOperation to the list of work to perform and assigns the operation /// the number of ticks that it should take up in the overall operation. /// </summary> /// <param name="operation">the progress-compatible method that will do some work</param> /// <param name="completed">method called when the operation is completed</param> /// <param name="tickSize">an arbitrary number that should reflect the percentage of the work that will be done by this operation. /// Note: longer running operations should have a larger tick count than fast executing operations.</param> public void AddProgressOperation(ProgressOperation operation, ProgressCategory category, ProgressOperationCompleted completed, int tickSize) { // if a category is being specified then the connected UI should know that // it can and should show categories if (category != null) { showCategories = true; } //wrap the operation with a ProgressWorker that can manage its execution ProgressWorker worker = new ProgressWorker(operation, category, completed, tickSize, 100, this); //add the worker to the list workers.Add(worker); //add the ticks assigned to this task to the overall tick count totalProgressTicks += tickSize; }
public int Progress(ref uint pdwCookie, int fInProgress, string pwszLabel, uint nComplete, uint nTotal) { ProgressCallCount++; LastPwdCookie = pdwCookie; LastfInProgress = fInProgress; LastLabel = pwszLabel; LastnComplete = nComplete; LastnTotal = nTotal; if (pdwCookie == 0) { pdwCookie = cookieToReturn; } ProgressOperation?.Invoke(); return(0); // success }
private void BeginDeleteSelectedEntityIfExists() { if (Grid.SelectedItem == null) { return; } var rowKey = (Grid.SelectedItem as ITableEntity).RowKey; Dialog.ConfirmYesOrNo("Are you sure you want to delete entity ".ToConsoleString() + rowKey.ToConsoleString(ConsoleColor.Yellow) + "?", () => { var entityToDelete = Grid.SelectedItem as ITableEntity; ProgressOperation operation = new ProgressOperation() { State = OperationState.InProgress, Message = "Deleting entity ".ToConsoleString() + rowKey.ToConsoleString(Application.Theme.H1Color) + " from table " + table.Name, }; ProgressOperationManager.Operations.Add(operation); var applicationRef = Application; Application.QueueAsyncAction(table.ExecuteAsync(TableOperation.Delete(entityToDelete)), (t) => { if (t.Exception != null) { operation.Message = "Failed to delete entity ".ToConsoleString(ConsoleColor.Red) + rowKey.ToConsoleString(applicationRef.Theme.H1Color) + " from table " + table.Name; operation.Details = t.Exception.ToString().ToConsoleString(); operation.State = OperationState.Failed; } else { operation.Message = "Finished deleting entity ".ToConsoleString() + rowKey.ToConsoleString(applicationRef.Theme.H1Color) + " from table " + table.Name; operation.State = OperationState.Completed; } Grid.NoVisibleColumnsMessage = "Loading..."; Grid.DataSource.ClearCachedData(); Grid.Refresh(); }); }); }
public virtual bool Send() { if (!Program2.SiteOptions.NetworkEnabled) { return(false); } progress = ProgressScreen.RegisterOperation(); try { // If security is turned on, We need to have an Index from the server in order to proceed if (secure && Community.SymmetricIndex == null) { Hello hello = new Hello(Callback_Hello, null); return(hello.Send()); } else { if (ISend()) { return(true); } else { progress.Complete(); return(false); } } } catch { progress.Complete(); return(false); } }
public static DialogResult ExecuteWithProgress(string title, ProgressOperation operation, ISynchronizeInvoke synchronizeInvoke, IWin32Window owner) { using (ProgressDialog progress = new ProgressDialog()) { progress.Text = title; MultipartAsyncOperation async = new MultipartAsyncOperation(synchronizeInvoke); async.AddProgressOperation(operation, new ProgressCategory(null, null), 100); progress.ProgressProvider = async; async.Start(); DialogResult result; if (!async.IsDone) result = progress.ShowDialog(owner); else result = progress.DialogResult; if (result == DialogResult.Cancel) throw new OperationCancelledException(); else if (result == DialogResult.Abort) throw async.Exception; else return result; } }
public ProgressVM(ProgressOperation operation) { this.Operation = operation; } //
public ProgressWorker(ProgressOperation method, int progressSize, int progressTotal, IProgressHost progress) : this(method, null, null, progressSize, progressTotal, progress) { }
public ProgressWorker(ProgressOperation method, ProgressOperationCompleted completedMethod, int progressSize, int progressTotal, IProgressHost progress) : this(method, null, completedMethod, progressSize, progressTotal, progress) { }
public void MarkAsCompleted() { _cancellationTokenSource.Dispose(); ProgressOperation.Dispose(); IsCompleted = true; }
/// <summary> /// Adds a new ProgressOperation to the list of work to perform and assigns the operation /// the number of ticks that it should take up in the overall operation. /// </summary> /// <param name="operation">the progress-compatible method that will do some work</param> /// <param name="tickSize">an arbitrary number that should reflect the percentage of the work that will be done by this operation. /// Note: longer running operations should have a larger tick count than fast executing operations.</param> public void AddProgressOperation(ProgressOperation operation, ProgressCategory progressCategory, int tickSize) { AddProgressOperation(operation, progressCategory, null, tickSize); }
/// <summary> /// Adds a new ProgressOperation to the list of work to perform and assigns the operation /// the number of ticks that it should take up in the overall operation. /// </summary> /// <param name="operation">the progress-compatible method that will do some work</param> /// <param name="tickSize">an arbitrary number that should reflect the percentage of the work that will be done by this operation. /// Note: longer running operations should have a larger tick count than fast executing operations.</param> public void AddProgressOperation(ProgressOperation operation, int tickSize) { AddProgressOperation(operation, null, null, tickSize); }
/// <summary> /// Adds a new ProgressOperation to the list of work to perform and assigns the operation /// the number of ticks that it should take up in the overall operation. /// </summary> /// <param name="operation">the progress-compatible method that will do some work</param> /// <param name="completed">method called when the operation is completed</param> /// <param name="tickSize">an arbitrary number that should reflect the percentage of the work that will be done by this operation. /// Note: longer running operations should have a larger tick count than fast executing operations.</param> public void AddProgressOperation(ProgressOperation operation, ProgressOperationCompleted completed, int tickSize) { AddProgressOperation(operation, null, completed, tickSize); }
public static DialogResult ExecuteWithProgress(string title, ProgressOperation operation, Control control) { return ExecuteWithProgress(title, operation, control, control.FindForm()); }
public ProgressWorker(ProgressOperation method, ProgressCategory category, int progressSize, int progressTotal, IProgressHost progress) : this(method, category, null, progressSize, progressTotal, progress) { }
public static DialogResult ExecuteWithProgress(string title, ProgressOperation operation, Control control) { return(ExecuteWithProgress(title, operation, control, control.FindForm())); }