-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
575 lines (507 loc) · 14.5 KB
/
MainWindow.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows;
using System.Xml;
using System.Xml.Serialization;
using Standart.Hash.xxHash;
using System.Windows.Media;
namespace Wrangler
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static List<Device> devices = new List<Device>();
public static List<Preset> presets = new List<Preset>();
public static Dictionary<string, string> hashCache = new Dictionary<string, string>();
public static int totalFiles = 0;
public static int processedFiles = 0;
public static int verifiedFiles = 0;
public static Queue<Tuple<string, string>> verificationQueue = new Queue<Tuple<string, string>>();
public static List<Thread> threads = new List<Thread>();
public static Boolean running = true;
public static Queue<string> logBuffer = new Queue<string>();
public MainWindow()
{
try
{
InitializeComponent();
cbxSources.ItemsSource = devices;
UpdateDriveList();
var p = new Preset
{
name = "Test"
};
try
{
presets = DeSerializeObject<List<Preset>>("presets.xml");
}
catch (FileNotFoundException)
{
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Unable to load presets from file: {0}", ex.Message), "Unable to load presets", MessageBoxButton.OK, MessageBoxImage.Error);
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("Unable to load presets from file: {0}", ex.Message));
}
}
if (presets == null)
{
presets = new List<Preset>();
}
cbxPreset.ItemsSource = presets;
Thread tv = new Thread(() => Verification(this));
tv.Start();
threads.Add(tv);
Thread tl = new Thread(() => Log());
tl.Start();
threads.Add(tl);
}
catch (Exception ex2)
{
MessageBox.Show(String.Format("There was an unexpected error: {0}", ex2.Message), "Unexpected error", MessageBoxButton.OK, MessageBoxImage.Error);
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("There was an unexpected error: {0}", ex2.Message));
}
throw;
}
}
/// <summary>
/// Serializes an object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serializableObject"></param>
/// <param name="fileName"></param>
public void SerializeObject<T>(T serializableObject, string fileName)
{
if (serializableObject == null) { return; }
try
{
XmlDocument xmlDocument = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, serializableObject);
stream.Position = 0;
xmlDocument.Load(stream);
xmlDocument.Save(fileName);
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Deserializes an xml file into an object list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public T DeSerializeObject<T>(string fileName)
{
if (string.IsNullOrEmpty(fileName)) { return default(T); }
T objectOut = default(T);
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
string xmlString = xmlDocument.OuterXml;
using (StringReader read = new StringReader(xmlString))
{
Type outType = typeof(T);
XmlSerializer serializer = new XmlSerializer(outType);
using (XmlReader reader = new XmlTextReader(read))
{
objectOut = (T)serializer.Deserialize(reader);
}
}
}
catch (Exception ex)
{
throw ex;
}
return objectOut;
}
private void UpdateDriveList()
{
devices.Clear();
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (!drive.DriveType.Equals(DriveType.Network) && !drive.DriveType.Equals(DriveType.Fixed) && drive.IsReady)
{
devices.Add(new Device
{
driveLetter = drive.Name,
name = drive.VolumeLabel,
used = (drive.TotalSize - drive.TotalFreeSpace) / 1024 / 1024,
total = drive.TotalSize / 1024 / 1024
});
}
}
cbxSources.Items.Refresh();
if (cbxSources.Items.Count > 0)
{
cbxSources.SelectedIndex = 0;
}
}
private void btnDeviceRefresh_Click(object sender, RoutedEventArgs e)
{
UpdateDriveList();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
try
{
Device sourceDevice = (Device)cbxSources.SelectedItem;
if (sourceDevice == null)
{
MessageBox.Show("Need to select a removable drive to copy from.");
return;
}
Preset targetPreset = (Preset)cbxPreset.SelectedItem;
if (targetPreset == null || targetPreset.paths.Count == 0)
{
MessageBox.Show("Need to select a preset to copy too.");
return;
}
List<string> sourceFilePaths = new List<string>();
try
{
sourceFilePaths.AddRange(GetAllFiles(sourceDevice.driveLetter));
}
catch (Exception inner)
{
UpdateDriveList();
lock (logBuffer)
{
logBuffer.Enqueue("Unable to get list of files from source device");
}
throw new Exception("Unable to get list of files from source device", inner);
}
//Copy
totalFiles = sourceFilePaths.Count * targetPreset.paths.Count;
processedFiles = 0;
pbr1.Maximum = totalFiles;
pbr1.Foreground = Brushes.Yellow;
txtProgress.Foreground = Brushes.Black;
pbr1.Value = processedFiles;
txtProgress.Text = string.Format("0% {0}/{1} copied", processedFiles, totalFiles);
verifiedFiles = 0;
pbrVerified.Maximum = totalFiles;
pbrVerified.Foreground = Brushes.Yellow;
txtVerificationProgress.Foreground = Brushes.Black;
pbrVerified.Value = verifiedFiles;
txtVerificationProgress.Text = string.Format("0% {0}/{1} verified", verifiedFiles, totalFiles);
verificationQueue.Clear();
btnStart.IsEnabled = false;
foreach (var destinationPath in targetPreset.paths)
{
Thread t = new Thread(() => Copy(sourceFilePaths, destinationPath, this));
t.Start();
threads.Add(t);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "An error occured");
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("An error occuredL {0}", ex.Message));
}
btnStart.IsEnabled = true;
}
}
private void Copy(List<string> sourceFilePaths, string destinationPath, MainWindow mw)
{
try
{
foreach (string sourceFilePath in sourceFilePaths)
{
if (!running)
{
break;
}
string relativeFilePath = sourceFilePath.Substring(sourceFilePath.IndexOf("\\", 0), sourceFilePath.Length - sourceFilePath.IndexOf("\\", 0));
string middlePath = relativeFilePath.Substring(0, relativeFilePath.LastIndexOf("\\"));
string directoryPathToCreate = destinationPath + middlePath;
string filePathDestination = destinationPath + relativeFilePath;
Directory.CreateDirectory(directoryPathToCreate);
File.Copy(sourceFilePath, filePathDestination);
IncrementProgress(mw, "copy", String.Format("Copied {0} to {1}", sourceFilePath, filePathDestination));
verificationQueue.Enqueue(new Tuple<string, string>(sourceFilePath, filePathDestination));
}
}
catch (Exception ex)
{
IncrementProgress(mw, "copy-error", String.Format("Copy error {0}", ex));
MessageBox.Show(ex.Message, String.Format("Error whilst copying to {0}", destinationPath));
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("Error whilst copying to {0} {1}", destinationPath, ex.Message));
}
}
}
private void Verification(MainWindow mw)
{
try
{
Boolean waiting = true;
while (running)
{
while (waiting)
{
if (verificationQueue.Count < totalFiles || totalFiles == 0)
{
Thread.Sleep(1000);
}
else
{
waiting = false;
}
}
Tuple<string, string> hashCheck;
try
{
hashCheck = verificationQueue.Dequeue();
}
catch (InvalidOperationException)
{
hashCheck = null;
}
if (hashCheck == null)
{
Thread.Sleep(100);
}
else
{
int retryAttempt = 4;
while (retryAttempt > 0)
{
string sourceFilePath = "";
string filePathDestination = "";
try
{
sourceFilePath = hashCheck.Item1;
filePathDestination = hashCheck.Item2;
string sourceHash;
string destinationHash;
if (hashCache.ContainsKey(sourceFilePath))
{
lock (hashCache)
{
sourceHash = hashCache[sourceFilePath];
}
}
else
{
using (var stream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
{
sourceHash = xxHash64.ComputeHash(stream).ToString();
hashCache[sourceFilePath] = sourceHash;
}
}
using (var stream = new FileStream(filePathDestination, FileMode.Open, FileAccess.Read))
{
destinationHash = xxHash64.ComputeHash(stream).ToString();
}
if (sourceHash == destinationHash)
{
IncrementProgress(mw, "verify", String.Format("Verified {0} with hash {1}", filePathDestination, destinationHash));
}
break;
}
catch (Exception ex)
{
Thread.Sleep(500);
retryAttempt--;
if (retryAttempt == 0)
{
Dispatcher.Invoke(() =>
{
mw.pbrVerified.Foreground = Brushes.Red;
mw.btnStart.IsEnabled = true;
});
MessageBox.Show(String.Format("Unable to verify file {0} -> {1} Error: {2}", sourceFilePath, filePathDestination, ex.Message), "Unable to verify file", MessageBoxButton.OK, MessageBoxImage.Error);
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("Unable to verify file {0} -> {1} Error: {2}", sourceFilePath, filePathDestination, ex.Message));
}
}
}
}
}
waiting = (verificationQueue.Count == 0);
}
}
catch (ThreadInterruptedException)
{
}
catch (Exception ex3)
{
Dispatcher.Invoke(() =>
{
mw.txtVerificationProgress.Foreground = Brushes.Black;
mw.pbrVerified.Foreground = Brushes.Red;
btnStart.IsEnabled = true;
});
MessageBox.Show(String.Format("Issue during verification:{0}", ex3.Message), "Unable to verify files", MessageBoxButton.OK, MessageBoxImage.Error);
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("Issue during verification:{0}", ex3.Message));
}
}
}
private IEnumerable<string> GetAllFiles(string dir)
{
return Directory.GetFiles(dir, "*", SearchOption.AllDirectories);
}
private void btnManagePresets_Click(object sender, RoutedEventArgs e)
{
Presets winPresets = new Presets(this);
winPresets.Show();
winPresets.Focus();
}
public void UpdatePresets()
{
cbxPreset.Items.Refresh();
try
{
SerializeObject<List<Preset>>(presets, "presets.xml");
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Unable to save presets to file: {0}", ex.Message), "Unable to save presets", MessageBoxButton.OK, MessageBoxImage.Error);
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("Unable to save presets to file: {0}", ex.Message));
}
}
}
public void IncrementProgress(MainWindow mw, string type, string lastEvent)
{
try
{
lock (mw)
{
Dispatcher.Invoke(() =>
{
mw.txtLog.Text = String.Format("{0}{1}{2}", lastEvent, Environment.NewLine, mw.txtLog.Text);
lock (logBuffer)
{
logBuffer.Enqueue(lastEvent);
}
});
switch (type)
{
case "copy":
processedFiles++;
Dispatcher.Invoke(() =>
{
mw.pbr1.Value = processedFiles;
decimal percentage = ((decimal)processedFiles / (decimal)totalFiles) * 100;
percentage = Math.Round(percentage);
mw.txtProgress.Text = string.Format("{0}% {1}/{2} copied", percentage, processedFiles, totalFiles);
if (processedFiles == totalFiles)
{
mw.txtProgress.Foreground = Brushes.Black;
mw.pbr1.Foreground = Brushes.Green;
}
});
break;
case "copy-error":
Dispatcher.Invoke(() =>
{
mw.txtProgress.Foreground = Brushes.White;
mw.pbr1.Foreground = Brushes.Red;
});
break;
case "verify":
verifiedFiles++;
Dispatcher.Invoke(() =>
{
mw.pbrVerified.Value = verifiedFiles;
decimal percentage = ((decimal)verifiedFiles / (decimal)totalFiles) * 100;
percentage = Math.Round(percentage);
mw.txtVerificationProgress.Text = string.Format("{0}% {1}/{2} verified", percentage, verifiedFiles, totalFiles);
if (totalFiles == verifiedFiles)
{
btnStart.IsEnabled = true;
mw.txtVerificationProgress.Foreground = Brushes.Black;
mw.pbrVerified.Foreground = Brushes.Green;
MessageBox.Show("Copy and Verification Completed, Recommend Manual Checking of Files", "Completed", MessageBoxButton.OK, MessageBoxImage.Information);
}
});
break;
case "finish":
Dispatcher.Invoke(() =>
{
mw.btnStart.IsEnabled = true;
});
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Unable to update progress: {0}", ex.Message), "Unable to update progress", MessageBoxButton.OK, MessageBoxImage.Error);
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("Unable to update progress: {0}", ex.Message));
}
btnStart.IsEnabled = true;
}
}
private void Log()
{
try
{
while (true)
{
Thread.Sleep(1000);
List<String> dataToWrite = new List<String>();
String logEntry="";
lock (logBuffer)
{
while (logBuffer.TryDequeue(out logEntry))
{
dataToWrite.Add(logEntry);
}
}
if (dataToWrite.Count > 0)
{
File.AppendAllLines("log.txt", dataToWrite.ToArray());
dataToWrite.Clear();
logEntry = "";
}
}
}
catch (ThreadInterruptedException)
{
}
catch (Exception ex3)
{
lock (logBuffer)
{
logBuffer.Enqueue(String.Format("Issue during log processing:{0}", ex3.Message));
}
MessageBox.Show(String.Format("Issue during log processing:{0}", ex3.Message), "Unable to log events", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void Window_Closed(object sender, EventArgs e)
{
foreach (var thread in threads)
{
running = false;
thread.Interrupt();
}
}
}
}