Horizon – Blame information for rev 31

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 1 using System;
2 using System.Collections.Concurrent;
3 using System.Collections.Generic;
4 using System.ComponentModel;
5 using System.Data.SQLite;
6 using System.Diagnostics;
7 using System.Drawing;
8 using System.IO;
12 office 9 using System.IO.Ports;
1 office 10 using System.Linq;
12 office 11 using System.Net.Sockets;
1 office 12 using System.Security.Cryptography;
12 office 13 using System.Text;
1 office 14 using System.Threading;
15 using System.Threading.Tasks;
16 using System.Windows.Forms;
17 using Horizon.Database;
18 using Horizon.Utilities;
19 using Microsoft.WindowsAPICodePack.Dialogs;
12 office 20 using Mono.Zeroconf;
21 using Mono.Zeroconf.Providers.Bonjour;
22 using Newtonsoft.Json;
5 office 23 using Org.BouncyCastle.Crypto;
12 office 24 using Org.BouncyCastle.Utilities.Net;
1 office 25 using Serilog;
12 office 26 using WatsonTcp;
1 office 27  
28 namespace Horizon.Snapshots
29 {
30 public partial class SnapshotManagerForm : Form
31 {
32 #region Static Fields and Constants
33  
34 private static ScheduledContinuation _searchTextBoxChangedContinuation;
35  
36 #endregion
37  
38 #region Private Delegates, Events, Enums, Properties, Indexers and Fields
39  
40 private readonly MainForm _mainForm;
41  
42 private readonly SnapshotDatabase _snapshotDatabase;
43  
44 private HexViewForm _hexViewForm;
45  
27 office 46 private SnapshotNoteForm _snapshotNoteForm;
1 office 47  
48 private SnapshotPreviewForm _snapshotPreviewForm;
49  
50 private readonly object _mouseMoveLock = new object();
51  
52 private readonly CancellationTokenSource _cancellationTokenSource;
53  
54 private readonly CancellationToken _cancellationToken;
55  
56 private readonly CancellationTokenSource _localCancellationTokenSource;
57  
58 private readonly CancellationToken _localCancellationToken;
59  
12 office 60 private readonly Mono.Zeroconf.ServiceBrowser _horizonServiceBrowser;
61  
62 private IResolvableService _resolvedService;
63  
64 private readonly ConcurrentDictionary<string, Service> _discoveredHorizonNetworkShares;
31 office 65 private readonly ConcurrentDictionary<string, CancellationTokenSource> _serviceTransferCancellationTokenSources;
12 office 66  
1 office 67 #endregion
68  
69 #region Constructors, Destructors and Finalizers
70  
5 office 71 private SnapshotManagerForm()
1 office 72 {
73 InitializeComponent();
74  
75 dataGridView1.Columns["TimeColumn"].ValueType = typeof(DateTime);
76  
77 _searchTextBoxChangedContinuation = new ScheduledContinuation();
78  
79 _localCancellationTokenSource = new CancellationTokenSource();
80 _localCancellationToken = _localCancellationTokenSource.Token;
12 office 81  
82 _discoveredHorizonNetworkShares = new ConcurrentDictionary<string, Service>();
31 office 83 _serviceTransferCancellationTokenSources = new ConcurrentDictionary<string, CancellationTokenSource>();
12 office 84 _horizonServiceBrowser = new Mono.Zeroconf.ServiceBrowser();
85 _horizonServiceBrowser.ServiceAdded += OnHorizonServiceBrowserOnServiceAdded;
31 office 86 _horizonServiceBrowser.ServiceRemoved += OnHorizonServiceBrowserOnServiceRemoved;
1 office 87 }
88  
89 public SnapshotManagerForm(MainForm mainForm, SnapshotDatabase snapshotDatabase,
90 CancellationToken cancellationToken) : this()
91 {
92 _mainForm = mainForm;
93 _snapshotDatabase = snapshotDatabase;
94 _snapshotDatabase.SnapshotCreate += SnapshotManager_SnapshotCreate;
23 office 95 _snapshotDatabase.SnapshotTransferReceived += _snapshotDatabase_SnapshotTransferReceived;
1 office 96  
97 _cancellationTokenSource =
98 CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken, cancellationToken);
99 _cancellationToken = _cancellationTokenSource.Token;
100 }
101  
102 /// <summary>
103 /// Clean up any resources being used.
104 /// </summary>
105 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
106 protected override void Dispose(bool disposing)
107 {
108 if (disposing && components != null)
109 {
110 components.Dispose();
111 }
112  
113 _snapshotDatabase.SnapshotCreate -= SnapshotManager_SnapshotCreate;
23 office 114 _snapshotDatabase.SnapshotTransferReceived -= _snapshotDatabase_SnapshotTransferReceived;
1 office 115  
31 office 116 _horizonServiceBrowser.ServiceRemoved -= OnHorizonServiceBrowserOnServiceRemoved;
12 office 117 _horizonServiceBrowser.ServiceAdded -= OnHorizonServiceBrowserOnServiceAdded;
118 _horizonServiceBrowser.Dispose();
1 office 119 _localCancellationTokenSource.Cancel();
120  
121 base.Dispose(disposing);
122 }
123  
124 #endregion
125  
126 #region Event Handlers
12 office 127 private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
128 {
129 }
130  
131 private void contextMenuStrip1_Opened(object sender, EventArgs e)
132 {
133 }
134  
1 office 135 private void DataGridView1_MouseDown(object sender, MouseEventArgs e)
136 {
137 var dataGridView = (DataGridView)sender;
138  
139 var index = dataGridView.HitTest(e.X, e.Y).RowIndex;
140  
141 if (index == -1)
142 {
143 base.OnMouseDown(e);
144 return;
145 }
146  
147 if (!dataGridView.SelectedRows.Contains(dataGridView.Rows[index]))
148 {
149 base.OnMouseDown(e);
150 }
151 }
152  
153 private async void DataGridView1_MouseMove(object sender, MouseEventArgs e)
154 {
155 var dataGridView = (DataGridView)sender;
156  
157 // Only accept dragging with left mouse button.
158 switch (e.Button)
159 {
160 case MouseButtons.Left:
161  
162 if (!Monitor.TryEnter(_mouseMoveLock))
163 {
164 break;
165 }
166  
167 try
168 {
169 var index = dataGridView.HitTest(e.X, e.Y).RowIndex;
170  
171 if (index == -1)
172 {
173 base.OnMouseMove(e);
174 return;
175 }
176  
177 var rows = GetSelectedDataGridViewRows(dataGridView);
178  
179 var count = rows.Count;
180  
181 if (count == 0)
182 {
183 base.OnMouseMove(e);
184 break;
185 }
186  
187 toolStripProgressBar1.Minimum = 0;
188 toolStripProgressBar1.Maximum = count;
189  
190 var virtualFileDataObject = new VirtualFileDataObject.VirtualFileDataObject();
191 var fileDescriptors =
192 new List<VirtualFileDataObject.VirtualFileDataObject.FileDescriptor>(count);
193  
194 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
195 {
196 if (_cancellationToken.IsCancellationRequested)
197 {
198 return;
199 }
200  
201 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
202 {
203 Log.Error(rowProgressFailure.Exception, "Unable to retrieve data for row.");
204  
205 toolStripStatusLabel1.Text =
206 $"Could not read file data {rowProgress.Row.Cells["NameColumn"].Value}...";
207 toolStripProgressBar1.Value = rowProgress.Index + 1;
208  
209 statusStrip1.Update();
210  
211 return;
212 }
213  
214 if (rowProgress is DataGridViewRowProgressSuccessRetrieveFileStream
215 rowProgressSuccessRetrieveFileStream)
216 {
217 toolStripStatusLabel1.Text =
218 $"Got {rowProgress.Row.Cells["NameColumn"].Value} file stream...";
219 toolStripProgressBar1.Value = rowProgress.Index + 1;
220  
221 statusStrip1.Update();
222  
223 var hash = (string)rowProgressSuccessRetrieveFileStream.Row.Cells["HashColumn"].Value;
224 var name = (string)rowProgressSuccessRetrieveFileStream.Row.Cells["NameColumn"].Value;
225  
226 var fileDescriptor = new VirtualFileDataObject.VirtualFileDataObject.FileDescriptor
227 {
228 Name = name,
229 StreamContents = stream =>
230 {
231 rowProgressSuccessRetrieveFileStream.MemoryStream.Seek(0, SeekOrigin.Begin);
232  
233 rowProgressSuccessRetrieveFileStream.MemoryStream.CopyTo(stream);
234 }
235 };
236  
237 fileDescriptors.Add(fileDescriptor);
238 }
239 });
240  
3 office 241 await Task.Run(() => RetrieveFileStream(rows, progress, _cancellationToken), _cancellationToken);
1 office 242  
3 office 243 if (_cancellationToken.IsCancellationRequested)
1 office 244 {
245 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
246 toolStripStatusLabel1.Text = "Done.";
247 }
248  
249 virtualFileDataObject.SetData(fileDescriptors);
250  
251 dataGridView1.DoDragDrop(virtualFileDataObject, DragDropEffects.Copy);
252 }
253 finally
254 {
255 Monitor.Exit(_mouseMoveLock);
256 }
257  
258 break;
259 }
260 }
261  
3 office 262 private async Task RetrieveFileStream(IReadOnlyList<DataGridViewRow> rows,
1 office 263 IProgress<DataGridViewRowProgress> progress,
264 CancellationToken cancellationToken)
265 {
266 var count = rows.Count;
267  
268 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
269 {
270 try
271 {
27 office 272 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 273  
27 office 274 var fileStream = await _snapshotDatabase.RetrieveFileStreamAsync(hash, cancellationToken);
275  
1 office 276 progress.Report(new DataGridViewRowProgressSuccessRetrieveFileStream(rows[i], i, fileStream));
277 }
278 catch (Exception exception)
279 {
280 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
281 }
282 }
283 }
284  
285 private void SnapshotManagerForm_Resize(object sender, EventArgs e)
286 {
27 office 287 if (_snapshotPreviewForm is { Visible: true })
1 office 288 {
289 _snapshotPreviewForm.WindowState = WindowState;
290 }
291 }
292  
293 private void OpenInExplorerToolStripMenuItem_Click(object sender, EventArgs e)
294 {
295 var row = GetSelectedDataGridViewRows(dataGridView1).FirstOrDefault();
296 if (row == null)
297 {
298 return;
299 }
300  
301 Process.Start("explorer.exe", $"/select, \"{(string)row.Cells["PathColumn"].Value}\"");
302 }
303  
27 office 304 private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
1 office 305 {
306 var dataGridView = (DataGridView)sender;
307  
308 var row = GetSelectedDataGridViewRows(dataGridView).FirstOrDefault();
309 if (row == null)
310 {
311 return;
312 }
313  
314 var hash = (string)row.Cells["HashColumn"].Value;
315  
27 office 316 if (_snapshotPreviewForm is { Visible: true })
1 office 317 {
27 office 318 _snapshotPreviewForm.Close();
1 office 319 }
320  
27 office 321 _snapshotPreviewForm = new SnapshotPreviewForm(this, hash, _snapshotDatabase, _cancellationToken);
322 _snapshotPreviewForm.Owner = this;
323 _snapshotPreviewForm.Closing += SnapshotPreviewForm_Closing;
324 _snapshotPreviewForm.Show();
1 office 325 }
326  
327 private void SnapshotPreviewForm_Closing(object sender, CancelEventArgs e)
328 {
27 office 329 if (_snapshotPreviewForm is { Visible: false })
1 office 330 {
331 return;
332 }
333  
27 office 334 _snapshotPreviewForm.Closing -= SnapshotPreviewForm_Closing;
1 office 335 _snapshotPreviewForm.Dispose();
336 }
337  
338 private async void NoneToolStripMenuItem_Click(object sender, EventArgs e)
339 {
340 var rows = GetSelectedDataGridViewRows(dataGridView1);
341  
342 var count = rows.Count;
343  
344 toolStripProgressBar1.Minimum = 0;
345 toolStripProgressBar1.Maximum = count;
346  
347 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
348 {
349 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
350 {
351 Log.Error(rowProgressFailure.Exception, "Failed to remove color from row.");
352  
353 toolStripStatusLabel1.Text =
354 $"Could not remove color from {rowProgress.Row.Cells["NameColumn"].Value}...";
355 toolStripProgressBar1.Value = rowProgress.Index + 1;
356  
357 statusStrip1.Update();
358  
359 return;
360 }
361  
362 rowProgress.Row.DefaultCellStyle.BackColor = Color.Empty;
363  
364 toolStripStatusLabel1.Text =
365 $"Removed color from {rowProgress.Row.Cells["NameColumn"].Value}...";
366 toolStripProgressBar1.Value = rowProgress.Index + 1;
367  
368 statusStrip1.Update();
369 });
370  
371 await Task.Run(() => RemoveColorFiles(rows, progress, _cancellationToken), _cancellationToken);
372  
3 office 373 if (_cancellationToken.IsCancellationRequested)
1 office 374 {
375 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
376 toolStripStatusLabel1.Text = "Done.";
377 }
378 }
379  
380 private async void ColorToolStripMenuItem_Click(object sender, EventArgs e)
381 {
382 var toolStripMenuItem = (ToolStripMenuItem)sender;
383 var color = toolStripMenuItem.BackColor;
384  
385 var rows = GetSelectedDataGridViewRows(dataGridView1);
386  
387 var count = rows.Count;
388  
389 toolStripProgressBar1.Minimum = 0;
390 toolStripProgressBar1.Maximum = count;
391  
392 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
393 {
394 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
395 {
396 Log.Error(rowProgressFailure.Exception, "Unable to color row.");
397  
398 toolStripStatusLabel1.Text =
399 $"Could not color {rowProgress.Row.Cells["NameColumn"].Value}...";
400 toolStripProgressBar1.Value = rowProgress.Index + 1;
401  
402 statusStrip1.Update();
403  
404 return;
405 }
406  
407 rowProgress.Row.DefaultCellStyle.BackColor = color;
408  
409 toolStripStatusLabel1.Text =
410 $"Colored {rowProgress.Row.Cells["NameColumn"].Value}...";
411 toolStripProgressBar1.Value = rowProgress.Index + 1;
412  
413 statusStrip1.Update();
414 });
415  
416 await Task.Run(() => ColorFiles(rows, color, progress, _cancellationToken), _cancellationToken);
417  
3 office 418 if (_cancellationToken.IsCancellationRequested)
1 office 419 {
420 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
421 toolStripStatusLabel1.Text = "Done.";
422 }
423 }
424  
425 private async void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
426 {
427 var rows = GetSelectedDataGridViewRows(dataGridView1);
428  
429 var count = rows.Count;
430  
431 toolStripProgressBar1.Minimum = 0;
432 toolStripProgressBar1.Maximum = count;
433  
434 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
435 {
436 if (_cancellationToken.IsCancellationRequested)
437 {
438 return;
439 }
440  
441 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
442 {
443 Log.Error(rowProgressFailure.Exception, "Unable to delete row.");
444  
445 toolStripStatusLabel1.Text =
446 $"Could not remove {rowProgress.Row.Cells["NameColumn"].Value}...";
447 toolStripProgressBar1.Value = rowProgress.Index + 1;
448  
449 statusStrip1.Update();
450  
451 return;
452 }
453  
454 toolStripStatusLabel1.Text =
455 $"Removed {rowProgress.Row.Cells["NameColumn"].Value}...";
456 toolStripProgressBar1.Value = rowProgress.Index + 1;
457  
458 statusStrip1.Update();
459  
460 dataGridView1.Rows.Remove(rowProgress.Row);
461 });
462  
463 await Task.Run(() => DeleteFiles(rows, progress, _cancellationToken), _cancellationToken);
464  
3 office 465 if (_cancellationToken.IsCancellationRequested)
1 office 466 {
467 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
468 toolStripStatusLabel1.Text = "Done.";
469 }
470 }
471  
472 private async void DeleteFastToolStripMenuItem_Click(object sender, EventArgs e)
473 {
474 var rows = GetSelectedDataGridViewRows(dataGridView1);
475  
476 try
477 {
478 await DeleteFilesFast(rows, _cancellationToken);
479  
480 foreach (var row in rows)
481 {
482 dataGridView1.Rows.Remove(row);
483 }
484 }
485 catch (Exception exception)
486 {
487 Log.Error(exception, "Unable to remove rows.");
488 }
489 }
490  
491 private void SnapshotManager_SnapshotCreate(object sender, SnapshotCreateEventArgs e)
492 {
493 switch (e)
494 {
495 case SnapshotCreateSuccessEventArgs snapshotCreateSuccessEventArgs:
496 dataGridView1.InvokeIfRequired(dataGridView =>
497 {
498 var index = dataGridView.Rows.Add();
499  
500 dataGridView.Rows[index].Cells["TimeColumn"].Value =
501 DateTime.Parse(snapshotCreateSuccessEventArgs.Time);
502 dataGridView.Rows[index].Cells["NameColumn"].Value = snapshotCreateSuccessEventArgs.Name;
503 dataGridView.Rows[index].Cells["PathColumn"].Value = snapshotCreateSuccessEventArgs.Path;
504 dataGridView.Rows[index].Cells["HashColumn"].Value = snapshotCreateSuccessEventArgs.Hash;
505 dataGridView.Rows[index].DefaultCellStyle.BackColor = snapshotCreateSuccessEventArgs.Color;
506  
23 office 507 dataGridView.Rows[index].Selected = true;
1 office 508 dataGridView.Sort(dataGridView.Columns["TimeColumn"], ListSortDirection.Descending);
509 });
510 break;
511 case SnapshotCreateFailureEventArgs snapshotCreateFailure:
512 Log.Warning(snapshotCreateFailure.Exception, "Could not create snapshot.");
513 break;
514 }
515 }
516  
23 office 517  
518 private void _snapshotDatabase_SnapshotTransferReceived(object sender, SnapshotCreateEventArgs e)
519 {
520 switch (e)
521 {
522 case SnapshotCreateSuccessEventArgs snapshotCreateSuccessEventArgs:
523 dataGridView1.InvokeIfRequired(dataGridView =>
524 {
525 var index = dataGridView.Rows.Add();
526  
527 dataGridView.Rows[index].Cells["TimeColumn"].Value =
528 DateTime.Parse(snapshotCreateSuccessEventArgs.Time);
529 dataGridView.Rows[index].Cells["NameColumn"].Value = snapshotCreateSuccessEventArgs.Name;
530 dataGridView.Rows[index].Cells["PathColumn"].Value = snapshotCreateSuccessEventArgs.Path;
531 dataGridView.Rows[index].Cells["HashColumn"].Value = snapshotCreateSuccessEventArgs.Hash;
532 dataGridView.Rows[index].DefaultCellStyle.BackColor = snapshotCreateSuccessEventArgs.Color;
533  
534 dataGridView.Rows[index].Selected = true;
535 dataGridView.Sort(dataGridView.Columns["TimeColumn"], ListSortDirection.Descending);
536 });
537 break;
538 case SnapshotCreateFailureEventArgs snapshotCreateFailure:
539 Log.Warning(snapshotCreateFailure.Exception, "Could not create snapshot.");
540 break;
541 }
542 }
543  
1 office 544 private void RevertToThisToolStripMenuItem_Click(object sender, EventArgs e)
545 {
546 _mainForm.InvokeIfRequired(async form =>
547 {
548 var fileSystemWatchers = new List<FileSystemWatcherState>();
549 var watchPaths = new HashSet<string>();
550 // Temporary disable all filesystem watchers that are watching the selected file directory.
551 foreach (var row in GetSelectedDataGridViewRows(dataGridView1))
552 {
553 var path = (string)row.Cells["PathColumn"].Value;
554  
555 foreach (var fileSystemWatcher in form.FileSystemWatchers)
556 {
557 if (!path.IsPathEqual(fileSystemWatcher.Path) &&
558 !path.IsSubPathOf(fileSystemWatcher.Path))
559 {
560 continue;
561 }
562  
563 if (watchPaths.Contains(fileSystemWatcher.Path))
564 {
565 continue;
566 }
567  
568 fileSystemWatchers.Add(new FileSystemWatcherState(fileSystemWatcher));
569  
570 fileSystemWatcher.EnableRaisingEvents = false;
571  
572 watchPaths.Add(fileSystemWatcher.Path);
573 }
574 }
575  
576 try
577 {
578 var rows = GetSelectedDataGridViewRows(dataGridView1);
579  
580 var count = rows.Count;
581  
582 toolStripProgressBar1.Minimum = 0;
583 toolStripProgressBar1.Maximum = count;
584  
585 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
586 {
587 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
588 {
589 Log.Error(rowProgressFailure.Exception, "Could not revert to snapshot.");
590  
591 toolStripStatusLabel1.Text =
592 $"Could not revert {rowProgress.Row.Cells["NameColumn"].Value}...";
593 toolStripProgressBar1.Value = rowProgress.Index + 1;
594  
595 statusStrip1.Update();
596  
597 return;
598 }
599  
600 toolStripStatusLabel1.Text =
601 $"Reverted {rowProgress.Row.Cells["NameColumn"].Value}...";
602 toolStripProgressBar1.Value = rowProgress.Index + 1;
603  
604 statusStrip1.Update();
605 });
606  
607 await Task.Run(() => RevertFile(rows, progress, _cancellationToken), _cancellationToken);
608  
3 office 609 if (_cancellationToken.IsCancellationRequested)
1 office 610 {
611 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
612 toolStripStatusLabel1.Text = "Done.";
613 }
614 }
615 catch (Exception exception)
616 {
617 Log.Error(exception, "Could not update data grid view.");
618 }
619 finally
620 {
621 // Restore initial state.
622 foreach (var fileSystemWatcherState in fileSystemWatchers)
623 {
624 foreach (var fileSystemWatcher in form.FileSystemWatchers)
625 {
626 if (fileSystemWatcherState.FileSystemWatcher == fileSystemWatcher)
627 {
628 fileSystemWatcher.EnableRaisingEvents = fileSystemWatcherState.State;
629 }
630 }
631 }
632 }
633 });
634 }
635  
636 private async void SnapshotManagerForm_Load(object sender, EventArgs e)
637 {
12 office 638 // Start browsing for network services.
639 _horizonServiceBrowser.Browse("_horizon._tcp", "local");
640  
27 office 641 int count;
642 try
643 {
644 count = (int)await _snapshotDatabase.CountSnapshotsAsync(_cancellationToken);
645 }
646 catch (Exception exception)
647 {
648 Log.Error(exception, "Could not count snapshots.");
649 return;
650 }
651  
652 if (count == 0)
653 {
654 return;
655 }
656  
12 office 657 // Load snapshots.
1 office 658 toolStripProgressBar1.Minimum = 0;
27 office 659 toolStripProgressBar1.Maximum = count;
1 office 660  
661 var snapshotQueue = new ConcurrentQueue<Snapshot>();
662  
5 office 663 void IdleHandler(object idleHandlerSender, EventArgs idleHandlerArgs)
1 office 664 {
665 try
666 {
5 office 667 if (snapshotQueue.IsEmpty)
1 office 668 {
669 Application.Idle -= IdleHandler;
670  
671 dataGridView1.Sort(dataGridView1.Columns["TimeColumn"], ListSortDirection.Descending);
672 toolStripStatusLabel1.Text = "Done.";
5 office 673 }
1 office 674  
5 office 675 if (!snapshotQueue.TryDequeue(out var snapshot))
676 {
1 office 677 return;
678 }
679  
680 var index = dataGridView1.Rows.Add();
681  
682 dataGridView1.Rows[index].Cells["TimeColumn"].Value = DateTime.Parse(snapshot.Time);
683 dataGridView1.Rows[index].Cells["NameColumn"].Value = snapshot.Name;
684 dataGridView1.Rows[index].Cells["PathColumn"].Value = snapshot.Path;
685 dataGridView1.Rows[index].Cells["HashColumn"].Value = snapshot.Hash;
686 dataGridView1.Rows[index].DefaultCellStyle.BackColor = snapshot.Color;
687  
688 toolStripStatusLabel1.Text = $"Loaded {snapshot.Name}...";
689  
690 toolStripProgressBar1.Increment(1);
691  
692 statusStrip1.Update();
693 }
694 catch (Exception exception)
695 {
696 Log.Error(exception, "Could not update data grid view.");
697 }
698 }
5 office 699  
1 office 700 try
701 {
11 office 702 await foreach (var snapshot in _snapshotDatabase.LoadSnapshotsAsync(_cancellationToken).WithCancellation(_cancellationToken))
1 office 703 {
704 snapshotQueue.Enqueue(snapshot);
705 }
706  
5 office 707 Application.Idle += IdleHandler;
1 office 708 }
709 catch (Exception exception)
710 {
711 Application.Idle -= IdleHandler;
712  
713 Log.Error(exception, "Unable to load snapshots.");
714 }
715 }
716  
31 office 717 private void OnHorizonServiceBrowserOnServiceRemoved(object o, Mono.Zeroconf.ServiceBrowseEventArgs args)
718 {
719 _resolvedService = args.Service;
720  
721 Log.Information($"Service lost: {_resolvedService.Name}");
722  
723 this.InvokeIfRequired(form =>
724 {
725 var list = new List<ToolStripMenuItem>();
726 foreach(var item in form.shareToToolStripMenuItem.DropDownItems.OfType<ToolStripMenuItem>())
727 {
728 if(string.Equals((string)item.Tag, _resolvedService.Name, StringComparison.Ordinal))
729 {
730 list.Add(item);
731 }
732 }
733  
734 foreach (var item in list)
735 {
736 form.shareToToolStripMenuItem.DropDownItems.Remove(item);
737 }
738  
739 list = new List<ToolStripMenuItem>();
740 foreach (var item in form.cancelSharingWithToolStripMenuItem.DropDownItems.OfType<ToolStripMenuItem>())
741 {
742 if (string.Equals((string)item.Tag, _resolvedService.Name, StringComparison.Ordinal))
743 {
744 list.Add(item);
745 }
746 }
747  
748 foreach (var item in list)
749 {
750 form.cancelSharingWithToolStripMenuItem.DropDownItems.Remove(item);
751 }
752 });
753  
754 }
755  
12 office 756 private void OnHorizonServiceBrowserOnServiceAdded(object o, Mono.Zeroconf.ServiceBrowseEventArgs args)
757 {
758 _resolvedService = args.Service;
759  
30 office 760 Log.Information($"Found Service: {_resolvedService.Name}");
12 office 761  
762 _resolvedService.Resolved += OnServiceOnResolved;
763  
764 _resolvedService.Resolve();
765  
766 _resolvedService.Resolved -= OnServiceOnResolved;
767 }
768  
769 private void OnServiceOnResolved(object o, ServiceResolvedEventArgs args)
770 {
771 var service = (Service) args.Service;
772  
30 office 773 Log.Information($"Resolved Service: {service.FullName} - {service.HostEntry.AddressList[0]}:{service.UPort} ({service.TxtRecord.Count} TXT record entries)");
12 office 774  
14 office 775 // Do not add discovered services more than once.
776 if (!_discoveredHorizonNetworkShares.TryAdd(service.Name, service))
777 {
778 return;
779 }
12 office 780  
781 var discoveredServiceMenuItem = new ToolStripMenuItem(service.Name, null, OnShareWithNodeClicked);
782 discoveredServiceMenuItem.Tag = service;
783  
31 office 784 var cancelServiceMenuItem = new ToolStripMenuItem(service.Name, null, OnCancelShareWithClicked);
785 cancelServiceMenuItem.Tag = service;
786  
21 office 787 this.InvokeIfRequired(form =>
788 {
789 form.shareToToolStripMenuItem.DropDownItems.Add(discoveredServiceMenuItem);
31 office 790 form.cancelSharingWithToolStripMenuItem.DropDownItems.Add(discoveredServiceMenuItem);
21 office 791 });
12 office 792 }
793  
31 office 794 private void OnCancelShareWithClicked(object sender, EventArgs e)
795 {
796 var toolStripMenuItem = (ToolStripMenuItem)sender;
797  
798 var service = (Service)toolStripMenuItem.Tag;
799  
800 if (_serviceTransferCancellationTokenSources.TryGetValue(service.Name, out var cancellationTokenSource))
801 {
802 cancellationTokenSource.Cancel();
803 }
804 }
805  
12 office 806 private async void OnShareWithNodeClicked(object sender, EventArgs e)
807 {
808 var toolStripMenuItem = (ToolStripMenuItem)sender;
809  
810 var service = (Service)toolStripMenuItem.Tag;
811  
31 office 812 // cancel any previous transfers
813 if (_serviceTransferCancellationTokenSources.TryGetValue(service.Name, out var transferCancellationTokenSource))
814 {
815 transferCancellationTokenSource.Cancel();
816 }
817  
818 transferCancellationTokenSource = new CancellationTokenSource();
819 _serviceTransferCancellationTokenSources.TryAdd(service.Name, transferCancellationTokenSource);
820  
12 office 821 var rows = GetSelectedDataGridViewRows(dataGridView1);
822  
823 var count = rows.Count;
824  
825 toolStripProgressBar1.Minimum = 0;
826 toolStripProgressBar1.Maximum = count;
827  
828 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
829 {
830 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
831 {
832 Log.Error(rowProgressFailure.Exception, "Unable to transfer data.");
833  
834 toolStripStatusLabel1.Text =
835 $"Could not transfer {rowProgress.Row.Cells["NameColumn"].Value}...";
836 toolStripProgressBar1.Value = rowProgress.Index + 1;
837  
838 statusStrip1.Update();
839  
840 return;
841 }
842  
843 toolStripStatusLabel1.Text =
844 $"Transferred {rowProgress.Row.Cells["NameColumn"].Value}...";
845 toolStripProgressBar1.Value = rowProgress.Index + 1;
846  
847 statusStrip1.Update();
848 });
849  
31 office 850 // pass the combined cancellation token source
851 using var combinedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(new[] { _cancellationToken, transferCancellationTokenSource.Token });
852 var combinedCancellationToken = combinedCancellationTokenSource.Token;
12 office 853  
31 office 854 await Task.Run(() => TransferFiles(rows, service, progress, combinedCancellationToken), combinedCancellationToken);
855  
12 office 856 if (_cancellationToken.IsCancellationRequested)
857 {
858 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
859 toolStripStatusLabel1.Text = "Done.";
860 }
861 }
862  
1 office 863 private void SnapshotManagerForm_Closing(object sender, FormClosingEventArgs e)
864 {
865 _cancellationTokenSource.Cancel();
866  
27 office 867 if (_snapshotPreviewForm is { Visible: true })
1 office 868 {
869 _snapshotPreviewForm.Close();
870 }
871  
27 office 872 if (_hexViewForm is { Visible: true })
1 office 873 {
874 _hexViewForm.Close();
875 }
876 }
877  
878 private void DataGridView1_DragEnter(object sender, DragEventArgs e)
879 {
880 if (e.Data.GetDataPresent(DataFormats.FileDrop))
881 {
882 e.Effect = DragDropEffects.Copy;
883 return;
884 }
885  
886 e.Effect = DragDropEffects.None;
887 }
888  
7 office 889 private void CreateSnapshots(IReadOnlyList<string> files, Bitmap screenCapture, TrackedFolders.TrackedFolders trackedFolders, IProgress<CreateSnapshotProgress> progress, CancellationToken cancellationToken)
5 office 890 {
891 Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = 512 }, async file =>
892 {
893 var color = Color.Empty;
894 if (_mainForm.TrackedFolders.TryGet(file, out var folder))
895 {
896 color = folder.Color;
897 }
898  
899 var fileInfo = File.GetAttributes(file);
900 if (fileInfo.HasFlag(FileAttributes.Directory))
901 {
902 foreach (var directoryFile in Directory.GetFiles(file, "*.*", SearchOption.AllDirectories))
903 {
904 var name = Path.GetFileName(directoryFile);
905 var path = Path.Combine(Path.GetDirectoryName(directoryFile), name);
906  
907 try
908 {
27 office 909 await _snapshotDatabase.CreateSnapshotAsync(name, path, screenCapture, color, _cancellationToken);
5 office 910  
911 progress.Report(new CreateSnapshotProgressSuccess(file));
912 }
913 catch (Exception exception)
914 {
915 progress.Report(new CreateSnapshotProgressFailure(file, exception));
916 }
917 }
918  
919 return;
920 }
921  
922 var fileName = Path.GetFileName(file);
27 office 923  
5 office 924 var pathName = Path.Combine(Path.GetDirectoryName(file), fileName);
925  
926 try
927 {
11 office 928 await _snapshotDatabase.CreateSnapshotAsync(fileName, pathName, screenCapture, color,
5 office 929 _cancellationToken);
930  
931 progress.Report(new CreateSnapshotProgressSuccess(file));
932 }
933 catch (Exception exception)
934 {
935 progress.Report(new CreateSnapshotProgressFailure(file, exception));
936 }
937 });
938 }
1 office 939 private async void DataGridView1_DragDrop(object sender, DragEventArgs e)
940 {
941 if (!e.Data.GetDataPresent(DataFormats.FileDrop))
942 {
943 return;
944 }
945  
946 var files = (string[])e.Data.GetData(DataFormats.FileDrop);
947  
948 toolStripProgressBar1.Minimum = 0;
949 toolStripProgressBar1.Maximum = files.Length;
950 toolStripStatusLabel1.Text = "Snapshotting files...";
951  
952 var screenCapture = ScreenCapture.Capture((CaptureMode)_mainForm.Configuration.CaptureMode);
5 office 953  
954 var progress = new Progress<CreateSnapshotProgress>(createSnapshotProgress =>
1 office 955 {
5 office 956 switch (createSnapshotProgress)
957 {
958 case CreateSnapshotProgressSuccess createSnapshotProgressSuccess:
959 toolStripStatusLabel1.Text = $"Snapshot taken of {createSnapshotProgressSuccess.File}.";
960 break;
961 case CreateSnapshotProgressFailure createSnapshotProgressFailure:
962 if (createSnapshotProgressFailure.Exception is SQLiteException { ResultCode: SQLiteErrorCode.Constraint })
963 {
964 toolStripStatusLabel1.Text = $"Snapshot of file {createSnapshotProgressFailure.File} already exists.";
965 break;
966 }
967  
968 toolStripStatusLabel1.Text = $"Could not snapshot file {createSnapshotProgressFailure.File}";
969 Log.Warning(createSnapshotProgressFailure.Exception, $"Could not snapshot file {createSnapshotProgressFailure.File}");
970 break;
971 }
972  
973 toolStripProgressBar1.Increment(1);
974 statusStrip1.Update();
975 });
976  
11 office 977 await Task.Factory.StartNew( () =>
5 office 978 {
7 office 979 CreateSnapshots(files, screenCapture, _mainForm.TrackedFolders, progress, _cancellationToken);
5 office 980 }, _cancellationToken);
1 office 981 }
982  
983 private async void FileToolStripMenuItem_Click(object sender, EventArgs e)
984 {
985 var dialog = new CommonOpenFileDialog();
986 if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
987 {
988 var screenCapture = ScreenCapture.Capture((CaptureMode)_mainForm.Configuration.CaptureMode);
989  
990 var fileName = Path.GetFileName(dialog.FileName);
991 var directory = Path.GetDirectoryName(dialog.FileName);
992 var pathName = Path.Combine(directory, fileName);
993  
994 var color = Color.Empty;
995 if (_mainForm.TrackedFolders.TryGet(directory, out var folder))
996 {
997 color = folder.Color;
998 }
999  
1000 try
1001 {
11 office 1002 await _snapshotDatabase.CreateSnapshotAsync(fileName, pathName, screenCapture, color,
1 office 1003 _cancellationToken);
1004 }
1005 catch (SQLiteException exception)
1006 {
1007 if (exception.ResultCode == SQLiteErrorCode.Constraint)
1008 {
1009 Log.Information(exception, "Snapshot already exists.");
1010 }
1011 }
1012 catch (Exception exception)
1013 {
1014 Log.Warning(exception, "Could not create snapshot.");
1015 }
1016 }
1017 }
1018  
1019 private async void DirectoryToolStripMenuItem_Click(object sender, EventArgs e)
1020 {
1021 var dialog = new CommonOpenFileDialog { IsFolderPicker = true };
1022 if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
1023 {
1024 var screenCapture = ScreenCapture.Capture((CaptureMode)_mainForm.Configuration.CaptureMode);
1025 foreach (var directoryFile in Directory.GetFiles(dialog.FileName, "*.*", SearchOption.AllDirectories))
1026 {
1027 var name = Path.GetFileName(directoryFile);
1028 var directory = Path.GetDirectoryName(directoryFile);
1029 var path = Path.Combine(directory, name);
1030  
1031 var color = Color.Empty;
1032 if (_mainForm.TrackedFolders.TryGet(directory, out var folder))
1033 {
1034 color = folder.Color;
1035 }
1036  
1037 try
1038 {
11 office 1039 await _snapshotDatabase.CreateSnapshotAsync(name, path, screenCapture, color, _cancellationToken);
1 office 1040 }
1041 catch (SQLiteException exception)
1042 {
1043 if (exception.ResultCode == SQLiteErrorCode.Constraint)
1044 {
1045 Log.Information(exception, "Snapshot already exists.");
1046 }
1047 }
1048 catch (Exception exception)
1049 {
1050 Log.Warning(exception, "Could not create snapshot.");
1051 }
1052 }
1053 }
1054 }
1055  
1056 private async void RelocateToolStripMenuItem_Click(object sender, EventArgs e)
1057 {
1058 var commonOpenFileDialog = new CommonOpenFileDialog
1059 {
1060 InitialDirectory = _mainForm.Configuration.LastFolder,
1061 IsFolderPicker = true
1062 };
1063  
1064 if (commonOpenFileDialog.ShowDialog() != CommonFileDialogResult.Ok)
1065 {
1066 return;
1067 }
1068  
1069 _mainForm.Configuration.LastFolder = commonOpenFileDialog.FileName;
1070 _mainForm.ChangedConfigurationContinuation.Schedule(TimeSpan.FromSeconds(1),
1071 async () => await _mainForm.SaveConfiguration(), _cancellationToken);
1072  
1073 var directory = commonOpenFileDialog.FileName;
1074  
1075 var rows = GetSelectedDataGridViewRows(dataGridView1);
1076  
1077 var count = rows.Count;
1078  
1079 toolStripProgressBar1.Minimum = 0;
1080 toolStripProgressBar1.Maximum = count;
1081  
1082 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
1083 {
1084 var path = Path.Combine(directory,
1085 (string)rowProgress.Row.Cells["NameColumn"].Value);
1086  
1087 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
1088 {
1089 Log.Error(rowProgressFailure.Exception, "Could not relocate snapshot.");
1090  
1091 toolStripStatusLabel1.Text =
1092 $"Could not relocate {rowProgress.Row.Cells["NameColumn"].Value} to {path}...";
1093 toolStripProgressBar1.Value = rowProgress.Index + 1;
1094  
1095 statusStrip1.Update();
1096  
1097 return;
1098 }
1099  
1100 rowProgress.Row.Cells["PathColumn"].Value = path;
1101  
1102 toolStripStatusLabel1.Text =
1103 $"Relocated {rowProgress.Row.Cells["NameColumn"].Value} to {path}...";
1104 toolStripProgressBar1.Value = rowProgress.Index + 1;
1105  
1106 statusStrip1.Update();
1107 });
1108  
1109 await Task.Run(() => RelocateFiles(rows, directory, progress, _cancellationToken), _cancellationToken);
1110  
3 office 1111 if (_cancellationToken.IsCancellationRequested)
1 office 1112 {
1113 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
1114 toolStripStatusLabel1.Text = "Done.";
1115 }
1116 }
1117  
27 office 1118 private void NoteToolStripMenuItem_Click(object sender, EventArgs e)
1 office 1119 {
1120 var row = GetSelectedDataGridViewRows(dataGridView1).FirstOrDefault();
1121 if (row == null)
1122 {
1123 return;
1124 }
1125  
27 office 1126 var hash = (string)row.Cells["HashColumn"].Value;
1 office 1127  
27 office 1128 if (_snapshotNoteForm is { Visible: true })
1 office 1129 {
27 office 1130 _snapshotNoteForm.Close();
1 office 1131 }
27 office 1132  
1133 _snapshotNoteForm = new SnapshotNoteForm(hash, _snapshotDatabase, _cancellationToken);
1134 _snapshotNoteForm.Owner = this;
1135 _snapshotNoteForm.SaveNote += SnapshotNoteFormSaveNoteForm;
1136 _snapshotNoteForm.Closing += SnapshotNoteForm_Closing;
1137 _snapshotNoteForm.Show();
1 office 1138 }
1139  
27 office 1140 private async void SnapshotNoteFormSaveNoteForm(object sender, SaveNoteEventArgs e)
1 office 1141 {
1142 var rows = GetSelectedDataGridViewRows(dataGridView1);
1143  
1144 var count = rows.Count;
1145  
1146 toolStripProgressBar1.Minimum = 0;
1147 toolStripProgressBar1.Maximum = count;
1148  
1149 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
1150 {
1151 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
1152 {
1153 Log.Error(rowProgressFailure.Exception, "Could not update note for snapshot.");
1154  
1155 toolStripStatusLabel1.Text =
1156 $"Could not update note for {rowProgress.Row.Cells["NameColumn"].Value}...";
1157 toolStripProgressBar1.Value = rowProgress.Index + 1;
1158  
1159 statusStrip1.Update();
1160  
1161 return;
1162 }
1163  
1164 toolStripStatusLabel1.Text =
1165 $"Updated note for {rowProgress.Row.Cells["NameColumn"].Value}...";
1166 toolStripProgressBar1.Value = rowProgress.Index + 1;
1167  
1168 statusStrip1.Update();
1169 });
1170  
1171 await Task.Run(() => UpdateNote(rows, e.Note, progress, _cancellationToken), _cancellationToken);
1172  
3 office 1173 if (_cancellationToken.IsCancellationRequested)
1 office 1174 {
1175 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
1176 toolStripStatusLabel1.Text = "Done.";
1177 }
1178 }
1179  
27 office 1180 private void SnapshotNoteForm_Closing(object sender, CancelEventArgs e)
1 office 1181 {
27 office 1182 if (_snapshotNoteForm is { Visible: false })
1 office 1183 {
1184 return;
1185 }
1186  
27 office 1187 _snapshotNoteForm.SaveNote -= SnapshotNoteFormSaveNoteForm;
1188 _snapshotNoteForm.Closing -= SnapshotNoteForm_Closing;
1189 _snapshotNoteForm.Dispose();
1 office 1190 }
1191  
27 office 1192 private void ViewHexToolStripMenuItem_Click(object sender, EventArgs e)
1 office 1193 {
1194 var rows = GetSelectedDataGridViewRows(dataGridView1);
1195 var row = rows.FirstOrDefault();
1196 if (row == null)
1197 {
1198 return;
1199 }
1200  
1201 var hash = (string)row.Cells["HashColumn"].Value;
1202  
27 office 1203 if (_hexViewForm is { Visible: true })
1 office 1204 {
27 office 1205 _hexViewForm.Close();
1206 }
1 office 1207  
27 office 1208 _hexViewForm = new HexViewForm(hash, _snapshotDatabase, _cancellationToken);
1209 _hexViewForm.Owner = this;
1210 _hexViewForm.Closing += HexViewForm_Closing;
1211 _hexViewForm.SaveData += HexViewForm_SaveData;
1212 _hexViewForm.Show();
1 office 1213 }
1214  
1215 private async void HexViewForm_SaveData(object sender, SaveDataEventArgs e)
1216 {
27 office 1217 string hash;
1 office 1218  
27 office 1219 try
1220 {
1221 hash = await _snapshotDatabase.UpdateFileAsync(e.Hash, e.Data, _cancellationToken);
1222 }
1223 catch (Exception exception)
1224 {
1225 Log.Error(exception, "Could not update snapshot data.");
1226 return;
1227 }
1228  
1 office 1229 if (string.IsNullOrEmpty(hash))
1230 {
1231 return;
1232 }
1233  
1234 dataGridView1.InvokeIfRequired(dataGridView =>
1235 {
1236 // Update the hash in the datagridview.
1237 var removeRows = new List<DataGridViewRow>();
1238 foreach (var row in dataGridView.Rows.OfType<DataGridViewRow>())
1239 {
1240 if ((string)row.Cells["HashColumn"].Value == hash)
1241 {
1242 removeRows.Add(row);
1243 }
1244  
1245 if ((string)row.Cells["HashColumn"].Value != e.Hash)
1246 {
1247 continue;
1248 }
1249  
1250 row.Cells["HashColumn"].Value = hash;
1251 }
1252  
1253 // Remove rows that might have the same hash.
1254 foreach (var row in removeRows)
1255 {
1256 dataGridView.Rows.Remove(row);
1257 }
1258 });
1259 }
1260  
1261 private void HexViewForm_Closing(object sender, CancelEventArgs e)
1262 {
27 office 1263 if (_hexViewForm is { Visible: false })
1 office 1264 {
1265 return;
1266 }
1267  
1268 _hexViewForm.SaveData -= HexViewForm_SaveData;
1269 _hexViewForm.Closing -= HexViewForm_Closing;
27 office 1270 _hexViewForm.Dispose();
1 office 1271 }
1272  
1273 private async void FileToolStripMenuItem2_Click(object sender, EventArgs e)
1274 {
1275 var commonOpenFileDialog = new CommonOpenFileDialog
1276 {
1277 InitialDirectory = _mainForm.Configuration.LastFolder,
1278 IsFolderPicker = true
1279 };
1280  
1281 if (commonOpenFileDialog.ShowDialog() == CommonFileDialogResult.Ok)
1282 {
1283 _mainForm.Configuration.LastFolder = commonOpenFileDialog.FileName;
1284 _mainForm.ChangedConfigurationContinuation.Schedule(TimeSpan.FromSeconds(1),
1285 async () => await _mainForm.SaveConfiguration(), _cancellationToken);
1286  
1287 var directory = commonOpenFileDialog.FileName;
1288  
1289 var rows = GetSelectedDataGridViewRows(dataGridView1);
1290  
1291 var count = rows.Count;
1292  
1293 toolStripProgressBar1.Minimum = 0;
1294 toolStripProgressBar1.Maximum = count;
1295  
1296 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
1297 {
1298 var fileInfo =
1299 new FileInfo((string)rowProgress.Row.Cells["NameColumn"].Value);
1300 var file = fileInfo.Name;
1301 var path = Path.Combine(directory, file);
1302  
1303 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
1304 {
1305 Log.Error(rowProgressFailure.Exception, "Could not save snapshot.");
1306  
1307 toolStripStatusLabel1.Text =
1308 $"Could not save snapshot {rowProgress.Row.Cells["NameColumn"].Value} to {path}...";
1309 toolStripProgressBar1.Value = rowProgress.Index + 1;
1310  
1311 statusStrip1.Update();
1312  
1313 return;
1314 }
1315  
1316 toolStripStatusLabel1.Text =
1317 $"Saved {rowProgress.Row.Cells["NameColumn"].Value} to {path}...";
1318 toolStripProgressBar1.Value = rowProgress.Index + 1;
1319  
1320 statusStrip1.Update();
1321 });
1322  
1323 await Task.Run(() => SaveFilesTo(rows, directory, progress, _cancellationToken), _cancellationToken);
1324  
3 office 1325 if (_cancellationToken.IsCancellationRequested)
1 office 1326 {
1327 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
1328 toolStripStatusLabel1.Text = "Done.";
1329 }
1330 }
1331 }
1332  
1333 private async void DirectoryToolStripMenuItem2_Click(object sender, EventArgs e)
1334 {
1335 var select = GetSelectedDataGridViewRows(dataGridView1).FirstOrDefault();
1336  
1337 if (select == null)
1338 {
1339 return;
1340 }
1341  
1342 // C:\aa\bbb\dd.txt
1343 var path = (string)select.Cells["PathColumn"].Value;
1344  
1345 // C:\aa\bbb\
1346 var basePath = Path.GetDirectoryName(path);
1347  
1348 var dialog = new CommonOpenFileDialog { IsFolderPicker = true };
1349 if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
1350 {
1351 //Log.Information(dialog.FileName);
1352 var rows = GetAllDataGridViewRows(dataGridView1);
1353 var count = rows.Count;
1354  
1355 toolStripProgressBar1.Minimum = 0;
1356 toolStripProgressBar1.Maximum = count;
1357 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
1358 {
1359 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
1360 {
1361 Log.Error(rowProgressFailure.Exception, "Could not save file.");
1362  
1363 toolStripStatusLabel1.Text =
1364 $"Could not save file {rowProgress.Row.Cells["NameColumn"].Value} to {basePath}...";
1365 toolStripProgressBar1.Value = rowProgress.Index + 1;
1366  
1367 statusStrip1.Update();
1368  
1369 return;
1370 }
1371  
1372 toolStripStatusLabel1.Text =
1373 $"Saved {rowProgress.Row.Cells["NameColumn"].Value} to {basePath}...";
1374 toolStripProgressBar1.Value = rowProgress.Index + 1;
1375  
1376 statusStrip1.Update();
1377 });
1378  
1379 await Task.Run(() => SaveDirectoryTo(rows, basePath, dialog.FileName, progress, _cancellationToken),
1380 _cancellationToken);
1381  
3 office 1382 if (_cancellationToken.IsCancellationRequested)
1 office 1383 {
1384 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
1385 toolStripStatusLabel1.Text = "Done.";
1386 }
1387 }
1388 }
1389  
1390 private void TextBox1_TextChanged(object sender, EventArgs e)
1391 {
1392 _searchTextBoxChangedContinuation.Schedule(TimeSpan.FromSeconds(1), () =>
1393 {
1394 textBox1.InvokeIfRequired(textBox =>
1395 {
1396 var search = textBox.Text;
1397  
1398 dataGridView1.InvokeIfRequired(dataGridView =>
1399 {
1400 foreach (var row in GetAllDataGridViewRows(dataGridView))
1401 {
1402 if(row.Cells["PathColumn"].Value == null)
1403 {
1404 continue;
1405 }
1406  
1407 switch (((string)row.Cells["PathColumn"].Value).IndexOf(search,
1408 StringComparison.OrdinalIgnoreCase))
1409 {
1410 case -1:
1411 row.Visible = false;
1412 break;
1413 default:
1414 row.Visible = true;
1415 break;
1416 }
1417 }
1418 });
1419 });
1420 }, _cancellationToken);
1421 }
1422  
1423 private async void RecomputeHashesToolStripMenuItem1_Click(object sender, EventArgs e)
1424 {
1425 var rows = GetSelectedDataGridViewRows(dataGridView1);
1426  
1427 var count = rows.Count;
1428  
1429 toolStripProgressBar1.Minimum = 0;
1430 toolStripProgressBar1.Maximum = count;
1431  
1432 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
1433 {
1434 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
1435 {
1436 Log.Error(rowProgressFailure.Exception, "Could not recompute hash for snapshot.");
1437  
1438 toolStripStatusLabel1.Text =
1439 $"Could not recompute hash for {rowProgress.Row.Cells["NameColumn"].Value}...";
1440 toolStripProgressBar1.Value = rowProgress.Index + 1;
1441  
1442 statusStrip1.Update();
1443  
1444 return;
1445 }
1446  
1447 toolStripStatusLabel1.Text =
1448 $"Recomputed hash for {rowProgress.Row.Cells["NameColumn"].Value}...";
1449 toolStripProgressBar1.Value = rowProgress.Index + 1;
1450  
1451 statusStrip1.Update();
1452 });
1453  
1454 await Task.Run(() => RecomputeHashes(rows, progress, _cancellationToken), _cancellationToken);
1455  
3 office 1456 if (_cancellationToken.IsCancellationRequested)
1 office 1457 {
1458 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
1459 toolStripStatusLabel1.Text = "Done.";
1460 }
1461 }
1462  
1463 private async void NormalizeDateTimeToolStripMenuItem_Click(object sender, EventArgs e)
1464 {
1465 var rows = GetSelectedDataGridViewRows(dataGridView1);
1466  
1467 var count = rows.Count;
1468  
1469 toolStripProgressBar1.Minimum = 0;
1470 toolStripProgressBar1.Maximum = count;
1471  
1472 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
1473 {
1474 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
1475 {
1476 Log.Error(rowProgressFailure.Exception, "Could not normalize date-time for snapshot.");
1477  
1478 toolStripStatusLabel1.Text =
1479 $"Could not normalize date-time for {rowProgress.Row.Cells["NameColumn"].Value}...";
1480 toolStripProgressBar1.Value = rowProgress.Index + 1;
1481  
1482 statusStrip1.Update();
1483  
1484 return;
1485 }
1486  
1487 toolStripStatusLabel1.Text =
1488 $"Normalized date-time for {rowProgress.Row.Cells["NameColumn"].Value}...";
1489 toolStripProgressBar1.Value = rowProgress.Index + 1;
1490  
1491 statusStrip1.Update();
1492 });
1493  
1494 await Task.Run(() => NormalizeDateTime(rows, progress, _cancellationToken), _cancellationToken);
1495  
3 office 1496 if (_cancellationToken.IsCancellationRequested)
1 office 1497 {
1498 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
1499 toolStripStatusLabel1.Text = "Done.";
1500 }
1501 }
1502  
1503 #endregion
1504  
1505 #region Private Methods
12 office 1506 private void DataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
1507 {
1508 DataGridView dataGridView = sender as DataGridView;
1509 foreach (DataGridViewCell cell in dataGridView.Rows[e.RowIndex].Cells)
1510 {
1511 if (cell.Selected == false) { continue; }
1512 var bgColorCell = Color.White;
1513 if (cell.Style.BackColor != Color.Empty) { bgColorCell = cell.Style.BackColor; }
1514 else if (cell.InheritedStyle.BackColor != Color.Empty) { bgColorCell = cell.InheritedStyle.BackColor; }
1515 cell.Style.SelectionBackColor = MixColor(bgColorCell, Color.FromArgb(0, 150, 255), 10, 4);
1516 }
1517 }
1 office 1518  
12 office 1519 //Mix two colors
1520 //Example: Steps=10 & Position=4 makes Color2 mix 40% into Color1
1521 /// <summary>
1522 /// Mix two colors.
1523 /// </summary>
1524 /// <param name="Color1"></param>
1525 /// <param name="Color2"></param>
1526 /// <param name="Steps"></param>
1527 /// <param name="Position"></param>
1528 /// <example>Steps=10 & Positon=4 makes Color2 mix 40% into Color1</example>
1529 /// <remarks>https://stackoverflow.com/questions/38337849/transparent-selectionbackcolor-for-datagridview-cell</remarks>
1530 /// <returns></returns>
1531 public static Color MixColor(Color Color1, Color Color2, int Steps, int Position)
1532 {
1533 if (Position <= 0 || Steps <= 1) { return Color1; }
1534 if (Position >= Steps) { return Color2; }
1535 return Color.FromArgb(
1536 Color1.R + ((Color2.R - Color1.R) / Steps * Position),
1537 Color1.G + ((Color2.G - Color1.G) / Steps * Position),
1538 Color1.B + ((Color2.B - Color1.B) / Steps * Position)
1539 );
1540 }
1541  
1 office 1542 private async Task DeleteFiles(IReadOnlyList<DataGridViewRow> rows, IProgress<DataGridViewRowProgress> progress,
1543 CancellationToken cancellationToken)
1544 {
1545 var count = rows.Count;
1546  
1547 for (var index = 0; index < count && !cancellationToken.IsCancellationRequested; ++index)
1548 {
1549 try
1550 {
27 office 1551 var hash = (string)rows[index].Cells["HashColumn"].Value;
1 office 1552  
27 office 1553 await _snapshotDatabase.RemoveFileAsync(hash, cancellationToken);
1554  
1 office 1555 progress.Report(new DataGridViewRowProgressSuccess(rows[index], index));
1556 }
1557 catch (Exception exception)
1558 {
1559 progress.Report(new DataGridViewRowProgressFailure(rows[index], index, exception));
1560 }
1561 }
1562 }
1563  
1564 private async Task DeleteFilesFast(IReadOnlyList<DataGridViewRow> rows, CancellationToken cancellationToken)
1565 {
1566 var hashes = rows.Select(row => (string)row.Cells["HashColumn"].Value);
1567  
27 office 1568 try
1569 {
1570 await _snapshotDatabase.RemoveFileFastAsync(hashes, cancellationToken);
1571 }
1572 catch (Exception exception)
1573 {
1574 Log.Error(exception, "Failed to remove files.");
1575 }
1 office 1576 }
1577  
1578 private async Task UpdateNote(IReadOnlyList<DataGridViewRow> rows, string note,
1579 IProgress<DataGridViewRowProgress> progress, CancellationToken cancellationToken)
1580 {
1581 var count = rows.Count;
1582  
1583 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1584 {
1585 try
1586 {
27 office 1587 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1588  
27 office 1589 await _snapshotDatabase.UpdateNoteAsync(hash, note,cancellationToken);
1590  
1 office 1591 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1592 }
1593 catch (Exception exception)
1594 {
1595 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1596 }
1597 }
1598 }
1599  
1600 private static List<DataGridViewRow> GetSelectedDataGridViewRows(DataGridView dataGridView)
1601 {
22 office 1602 return dataGridView.SelectedRows.OfType<DataGridViewRow>().Where(row => row.Visible).ToList();
1 office 1603 }
1604  
1605 private static List<DataGridViewRow> GetAllDataGridViewRows(DataGridView dataGridView)
1606 {
22 office 1607 return dataGridView.Rows.OfType<DataGridViewRow>().Where(row => row.Visible).ToList();
1 office 1608 }
1609  
1610 private async Task RemoveColorFiles(IReadOnlyList<DataGridViewRow> rows,
1611 IProgress<DataGridViewRowProgress> progress,
1612 CancellationToken cancellationToken)
1613 {
1614 var count = rows.Count;
1615  
1616 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1617 {
1618 try
1619 {
27 office 1620 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1621  
27 office 1622 await _snapshotDatabase.RemoveColorAsync(hash, cancellationToken);
1623  
1 office 1624 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1625 }
1626 catch (Exception exception)
1627 {
1628 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1629 }
1630 }
1631 }
1632  
1633 private async Task ColorFiles(IReadOnlyList<DataGridViewRow> rows, Color color,
1634 IProgress<DataGridViewRowProgress> progress, CancellationToken cancellationToken)
1635 {
1636 var count = rows.Count;
1637  
1638 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1639 {
1640 try
1641 {
27 office 1642 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1643  
27 office 1644 await _snapshotDatabase.UpdateColorAsync(hash, color, cancellationToken);
1645  
1 office 1646 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1647 }
1648 catch (Exception exception)
1649 {
1650 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1651 }
1652 }
1653 }
1654  
12 office 1655 private async Task TransferFiles(IReadOnlyList<DataGridViewRow> rows, Service service,
1656 IProgress<DataGridViewRowProgress> progress, CancellationToken cancellationToken)
1657 {
1658  
1659 var client = new WatsonTcpClient($"{service.HostEntry.AddressList[0]}", service.UPort);
21 office 1660 client.Events.MessageReceived += Events_MessageReceived;
1661 client.Events.ServerConnected += Events_ServerConnected;
1662 client.Events.ServerDisconnected += Events_ServerDisconnected;
1663 client.Events.ExceptionEncountered += Events_ExceptionEncountered;
12 office 1664  
1665 try
1666 {
1667 client.Connect();
1668  
1669 var count = rows.Count;
1670  
1671 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1672 {
1673 try
1674 {
27 office 1675 var hash = (string)rows[i].Cells["HashColumn"].Value;
1676  
21 office 1677 var completeSnapshot =
27 office 1678 await _snapshotDatabase.GenerateTransferSnapshotAsync(hash, cancellationToken);
12 office 1679  
1680 var jsonSnapshot = JsonConvert.SerializeObject(completeSnapshot);
1681  
1682 await client.SendAsync(jsonSnapshot, null, cancellationToken);
1683  
1684 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1685 }
1686 catch (Exception exception)
1687 {
1688 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1689 }
1690 }
1691 }
24 office 1692 catch (Exception exception) when (exception is TimeoutException || exception is SocketException)
21 office 1693 {
1694 Log.Error(exception, "Client threw exception.");
1695 }
12 office 1696 finally
1697 {
21 office 1698 client.Events.MessageReceived -= Events_MessageReceived;
1699 client.Events.ServerConnected -= Events_ServerConnected;
1700 client.Events.ServerDisconnected -= Events_ServerDisconnected;
1701 client.Events.ExceptionEncountered -= Events_ExceptionEncountered;
1702  
12 office 1703 client.Dispose();
1704 }
21 office 1705  
12 office 1706 }
1707  
21 office 1708 private void Events_ExceptionEncountered(object sender, ExceptionEventArgs e)
1709 {
1710 Log.Error(e.Exception, $"Client threw exception.");
1711 }
1712  
1713 private void Events_ServerDisconnected(object sender, DisconnectionEventArgs e)
1714 {
1715 Log.Information($"{e.Client?.IpPort} connected to server due to: {e.Reason}.");
1716 }
1717  
1718 private void Events_MessageReceived(object sender, MessageReceivedEventArgs e)
1719 {
1720 Log.Information($"{e.Data?.Length} byte long message received from {e.Client?.IpPort}");
1721 }
1722  
1723 private void Events_ServerConnected(object sender, WatsonTcp.ConnectionEventArgs e)
1724 {
1725 Log.Information($"{e.Client?.IpPort} connected to server.");
1726 }
1727  
1 office 1728 private async Task RevertFile(IReadOnlyList<DataGridViewRow> rows, IProgress<DataGridViewRowProgress> progress,
1729 CancellationToken cancellationToken)
1730 {
1731 var count = rows.Count;
1732  
1733 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1734 {
1735 try
1736 {
27 office 1737 var path = (string)rows[i].Cells["NameColumn"].Value;
1738 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1739  
27 office 1740 await _snapshotDatabase.RevertFileAsync(path, hash, cancellationToken, _mainForm.Configuration.AtomicOperations);
1741  
1 office 1742 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1743 }
1744 catch (Exception exception)
1745 {
1746 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1747 }
1748 }
1749 }
1750  
1751 private async void SaveFilesTo(IReadOnlyList<DataGridViewRow> rows, string directory,
1752 IProgress<DataGridViewRowProgress> progress, CancellationToken cancellationToken)
1753 {
1754 var count = rows.Count;
1755  
1756 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1757 {
1758 try
1759 {
27 office 1760 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1761 var fileInfo = new FileInfo((string)rows[i].Cells["NameColumn"].Value);
1762 var file = fileInfo.Name;
1763 var path = Path.Combine(directory, file);
1764  
27 office 1765 await _snapshotDatabase.SaveFileAsync(path, hash, cancellationToken);
1 office 1766  
1767 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1768 }
1769 catch (Exception exception)
1770 {
1771 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1772 }
1773 }
1774 }
1775  
1776 private async Task RelocateFiles(IReadOnlyList<DataGridViewRow> rows, string directory,
1777 IProgress<DataGridViewRowProgress> progress,
1778 CancellationToken cancellationToken)
1779 {
1780 var count = rows.Count;
1781  
1782 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1783 {
1784 try
1785 {
27 office 1786 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1787 var path = Path.Combine(directory, (string)rows[i].Cells["NameColumn"].Value);
1788  
27 office 1789 await _snapshotDatabase.RelocateFileAsync(hash, path, cancellationToken);
1 office 1790  
1791 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1792 }
1793 catch (Exception exception)
1794 {
1795 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1796 }
1797 }
1798 }
1799  
1800 private async void RecomputeHashes(IReadOnlyList<DataGridViewRow> rows,
1801 IProgress<DataGridViewRowProgress> progress,
1802 CancellationToken cancellationToken)
1803 {
1804 var count = rows.Count;
1805  
1806 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1807 {
1808 try
1809 {
27 office 1810 var hash = (string)rows[i].Cells["HashColumn"].Value;
1811  
1812 using var memoryStream = await _snapshotDatabase.RetrieveFileStreamAsync(hash, cancellationToken);
1813 if (memoryStream == null)
1 office 1814 {
27 office 1815 continue;
1816 }
1 office 1817  
27 office 1818 using var md5 = MD5.Create();
1 office 1819  
27 office 1820 var recomputedHash = md5.ComputeHash(memoryStream);
1821 var hashHex = BitConverter.ToString(recomputedHash).Replace("-", "")
1822 .ToLowerInvariant();
1823  
1824 await _snapshotDatabase.UpdateHashAsync(hash, hashHex,
1825 cancellationToken);
1 office 1826  
27 office 1827 rows[i].Cells["HashColumn"].Value = hashHex;
1 office 1828  
27 office 1829 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1 office 1830 }
1831 catch (Exception exception)
1832 {
1833 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1834 }
1835 }
1836 }
1837  
1838 private async Task SaveDirectoryTo(IReadOnlyList<DataGridViewRow> rows, string basePath, string targetPath,
1839 IProgress<DataGridViewRowProgress> progress,
1840 CancellationToken cancellationToken)
1841 {
1842 var store = new HashSet<string>();
1843  
1844 var count = rows.Count;
1845  
1846 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1847 {
1848 try
1849 {
1850 // C:\aa\bbb\fff\gg.txt
1851 var rowPath = (string)rows[i].Cells["PathColumn"].Value;
1852 if (store.Contains(rowPath))
1853 {
1854 continue;
1855 }
1856  
1857 // C:\aa\bbb\fff\gg.txt subpath C:\aa\bbb\
1858 if (!rowPath.IsPathEqual(basePath) &&
1859 !rowPath.IsSubPathOf(basePath))
1860 {
1861 continue;
1862 }
1863  
1864 var rootPath = new DirectoryInfo(basePath).Name;
1865 var relPath = rowPath.Remove(0, basePath.Length).Trim('\\');
1866 var newPath = Path.Combine(targetPath, rootPath, relPath);
1867  
1868 var hash = (string)rows[i].Cells["HashColumn"].Value;
27 office 1869  
11 office 1870 await _snapshotDatabase.SaveFileAsync(newPath, hash, cancellationToken);
1 office 1871  
1872 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1873  
1874 if (!store.Contains(rowPath))
1875 {
1876 store.Add(rowPath);
1877 }
1878 }
1879 catch (Exception exception)
1880 {
1881 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1882 }
1883 }
1884 }
1885  
1886 private async Task NormalizeDateTime(IReadOnlyList<DataGridViewRow> rows,
1887 IProgress<DataGridViewRowProgress> progress,
1888 CancellationToken cancellationToken)
1889 {
1890 var count = rows.Count;
1891  
1892 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1893 {
1894 try
1895 {
27 office 1896 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1897  
27 office 1898 await _snapshotDatabase.NormalizeTimeAsync(hash, cancellationToken);
1899  
1 office 1900 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1901 }
1902 catch (Exception exception)
1903 {
1904 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1905 }
1906 }
1907 }
1908  
1909 private async void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
1910 {
1911 var toolStripMenuItem = (ToolStripMenuItem)sender;
1912  
1913 var rows = GetSelectedDataGridViewRows(dataGridView1);
1914  
1915 var count = rows.Count;
1916  
1917 toolStripProgressBar1.Minimum = 0;
1918 toolStripProgressBar1.Maximum = count;
1919  
1920 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
1921 {
1922 if (rowProgress is DataGridViewRowProgressFailure rowProgressFailure)
1923 {
1924 Log.Error(rowProgressFailure.Exception, "Unable to delete screenshot.");
1925  
1926 toolStripStatusLabel1.Text =
1927 $"Could not delete screenshot for {rowProgress.Row.Cells["NameColumn"].Value}...";
1928 toolStripProgressBar1.Value = rowProgress.Index + 1;
1929  
1930 statusStrip1.Update();
1931  
1932 return;
1933 }
1934  
1935 toolStripStatusLabel1.Text =
1936 $"Colored {rowProgress.Row.Cells["NameColumn"].Value}...";
1937 toolStripProgressBar1.Value = rowProgress.Index + 1;
1938  
1939 statusStrip1.Update();
1940 });
1941  
1942 await Task.Run(() => DeleteScreenshots(rows, progress, _cancellationToken), _cancellationToken);
1943  
3 office 1944 if (_cancellationToken.IsCancellationRequested)
1 office 1945 {
1946 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
1947 toolStripStatusLabel1.Text = "Done.";
1948 }
1949 }
1950  
1951 private async Task DeleteScreenshots(IReadOnlyList<DataGridViewRow> rows,
1952 IProgress<DataGridViewRowProgress> progress,
1953 CancellationToken cancellationToken)
1954 {
1955 var count = rows.Count;
1956  
1957 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
1958 {
1959 try
1960 {
27 office 1961 var hash = (string)rows[i].Cells["HashColumn"].Value;
1 office 1962  
27 office 1963 await _snapshotDatabase.DeleteScreenshotAsync(hash, cancellationToken);
1964  
1 office 1965 progress.Report(new DataGridViewRowProgressSuccess(rows[i], i));
1966 }
1967 catch (Exception exception)
1968 {
1969 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
1970 }
1971 }
1972 }
1973  
1974 #endregion
23 office 1975  
1976 private void copyHashToolStripMenuItem_Click(object sender, EventArgs e)
1977 {
1978 var row = GetSelectedDataGridViewRows(dataGridView1).FirstOrDefault();
1979 if (row == null)
1980 {
1981 return;
1982 }
1983  
1984 Clipboard.SetText($"{row.Cells["HashColumn"].Value}");
1985  
1986 }
1 office 1987 }
1988 }