-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathChoRoboCopyManager.cs
642 lines (525 loc) · 23 KB
/
ChoRoboCopyManager.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
namespace ChoEazyCopy
{
#region NameSpaces
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using Cinchoo.Core.IO;
using Cinchoo.Core;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Management;
#endregion NameSpaces
public class ChoFileProcessEventArgs : EventArgs
{
#region Instance Data Members (Public)
public string Message
{
get;
private set;
}
public object Tag
{
get;
private set;
}
#endregion Instance Data Members (Public)
#region Constructors
public ChoFileProcessEventArgs(string message, object tag = null)
{
Message = message;
Tag = tag;
}
#endregion Constructors
}
public class ChoRoboCopyProgressEventArgs : EventArgs
{
#region Instance Data Members (Public)
public long _runningBytes
{
get;
private set;
}
public long _runningFileCount
{
get;
private set;
}
public long _totalBytes
{
get;
private set;
}
public long _totalFileCount
{
get;
private set;
}
#endregion Instance Data Members (Public)
#region Constructors
public ChoRoboCopyProgressEventArgs(long runningBytes, long runningFileCount, long totalBytes, long totalFileCount)
{
_runningBytes = runningBytes;
_runningFileCount = runningFileCount;
_totalBytes = totalBytes;
_totalFileCount = totalFileCount;
}
#endregion Constructors
}
public class ChoRoboCopyManager : IDisposable
{
#region Shared Data Members (Private)
private static readonly ChoAppSettings _appSettings = new ChoAppSettings();
#endregion Shared Data Members (Private)
#region EventHandlers
public event EventHandler<ChoFileProcessEventArgs> Status;
public event EventHandler<ChoFileProcessEventArgs> AppStatus;
public event EventHandler<ChoRoboCopyProgressEventArgs> Progress;
#endregion EventHandlers
#region Instance Data Members (Private)
private Process _process = null;
private Process _robocopyProcess = null;
private Process _analyzeRobocopyProcess = null;
private long _totalFileCount = 0;
private long _totalBytes = 0;
private long _runningFileCount = 0;
private long _runningBytes = 0;
private bool _cancel = false;
private bool _hasError = false;
AutoResetEvent _waitForRobocopyProcessToExit = new AutoResetEvent(false);
private Regex _regexBytes = new Regex(@"(?<=\s+)\d+(?=\s+)", RegexOptions.Compiled);
#endregion Instance Data Members (Private)
#region Constructors
public ChoRoboCopyManager(string settingsFilePath = null)
{
if (settingsFilePath.IsNullOrWhiteSpace())
{
if (File.Exists(settingsFilePath))
{
string settingsText = File.ReadAllText(settingsFilePath);
_appSettings.LoadXml(settingsText);
}
}
}
#endregion Constructors
#region Instance Members (Public)
public void Process(ChoAppSettings appSettings, bool console = false)
{
string fileName = appSettings.RoboCopyFilePath;
string arguments = appSettings.GetCmdLineParams();
AppStatus.Raise(this, new ChoFileProcessEventArgs("Starting RoboCopy operation..."));
Status.Raise(this, new ChoFileProcessEventArgs(Environment.NewLine));
string preCommands = appSettings.Precommands;
string postCommands = appSettings.Postcommands;
bool testRun = appSettings.ListOnly;
_cancel = false;
try
{
// Setup the process start info
var processStartInfo = new ProcessStartInfo("cmd.exe", " /E:OFF /F:OFF /V:OFF /K") // new ProcessStartInfo(fileName, arguments) //_appSettings.RoboCopyFilePath, _appSettings.GetCmdLineParams(sourceDirectory, destDirectory))
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
// Setup the process
Process process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };
// Register event
_process = process;
string echoCmd = testRun ? "@ECHO " : "";
//Run precommands
Status.Raise(this, new ChoFileProcessEventArgs($"**************************************" + Environment.NewLine));
Status.Raise(this, new ChoFileProcessEventArgs($"Starting RoboCopy operations..." + Environment.NewLine));
if (!preCommands.IsNullOrWhiteSpace())
{
_hasError = false;
// Start process
process.Start();
//Task.Factory.StartNew(new Action<object>(ReadFromStreamReader), process.StandardOutput);
Task.Factory.StartNew(new Action<object>(ReadFromStreamReader), process.StandardError);
//Replace tokens
preCommands = preCommands.Replace("{SRC_DIR}", appSettings.SourceDirectory);
preCommands = preCommands.Replace("{DEST_DIR}", appSettings.DestDirectory);
if (!testRun)
Status.Raise(this, new ChoFileProcessEventArgs($"Executing pre-process commands..." + Environment.NewLine));
else
Status.Raise(this, new ChoFileProcessEventArgs($"SKIP: Executing pre-process commands..." + Environment.NewLine));
Status.Raise(this, new ChoFileProcessEventArgs($"{FormatCmd(preCommands, appSettings)}" + Environment.NewLine));
if (!testRun)
process.StandardInput.WriteLine(preCommands);
//foreach (var cmd in preCommands.SplitNTrim().Select(c => c.NTrim()).Select(c => MarshalCmd(c, appSettings)).Where(c => !c.IsNullOrWhiteSpace()))
//{
// Status.Raise(this, new ChoFileProcessEventArgs($">{echoCmd}{cmd}" + Environment.NewLine));
// process.StandardInput.WriteLine($"{echoCmd}{cmd}");
//}
process.StandardInput.WriteLine("exit");
process.WaitForExit();
if (_hasError)
{
Status.Raise(this, new ChoFileProcessEventArgs($"RoboCopy operations failed." + Environment.NewLine));
AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operations failed.", "RoboCopy operations failed."));
return;
}
}
//Run robocopy
//process.StandardInput.WriteLine($"{fileName} {arguments}");
if (appSettings.ShowRoboCopyProgress)
{
if (!Analyze(appSettings))
return;
}
if (!RunRoboCopyOperation(appSettings))
return;
//Run postcommands
if (!postCommands.IsNullOrWhiteSpace())
{
_hasError = false;
// Start process
process.Start();
//Task.Factory.StartNew(new Action<object>(ReadFromStreamReader), process.StandardOutput);
Task.Factory.StartNew(new Action<object>(ReadFromStreamReader), process.StandardError);
//Replace tokens
postCommands = postCommands.Replace("{SRC_DIR}", appSettings.SourceDirectory);
postCommands = postCommands.Replace("{DEST_DIR}", appSettings.DestDirectory);
if (!testRun)
Status.Raise(this, new ChoFileProcessEventArgs($"Executing post-process commands..." + Environment.NewLine));
else
Status.Raise(this, new ChoFileProcessEventArgs($"SKIP: Executing post-process commands..." + Environment.NewLine));
Status.Raise(this, new ChoFileProcessEventArgs($"{FormatCmd(postCommands, appSettings)}" + Environment.NewLine));
if (!testRun)
process.StandardInput.WriteLine(postCommands);
//foreach (var cmd in postCommands.SplitNTrim().Select(c => c.NTrim()).Select(c => MarshalCmd(c, appSettings)).Where(c => !c.IsNullOrWhiteSpace()))
//{
// Status.Raise(this, new ChoFileProcessEventArgs($">{echoCmd}{cmd}" + Environment.NewLine));
// process.StandardInput.WriteLine($"{echoCmd}{cmd}");
//}
process.StandardInput.WriteLine("exit");
process.WaitForExit();
if (_hasError)
{
Status.Raise(this, new ChoFileProcessEventArgs($"RoboCopy operations failed." + Environment.NewLine));
AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operations failed.", "RoboCopy operations failed."));
return;
}
}
_process = null;
if (!_cancel)
{
Status.Raise(this, new ChoFileProcessEventArgs($"RoboCopy operations completed successfully." + Environment.NewLine));
AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operation completed successfully.", "RoboCopy operation completed successfully."));
}
else
{
Status.Raise(this, new ChoFileProcessEventArgs($"RoboCopy operations cancelled by user." + Environment.NewLine));
AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operations cancelled by user.", "RoboCopy operations cancelled by user."));
}
}
catch (ThreadAbortException)
{
Status.Raise(this, new ChoFileProcessEventArgs(Environment.NewLine + "RoboCopy operation canceled by user." + Environment.NewLine, "RoboCopy operation canceled by user."));
AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operation canceled by user.", "RoboCopy operation canceled by user."));
}
catch (Exception ex)
{
Status.Raise(this, new ChoFileProcessEventArgs(Environment.NewLine + ex.ToString() + Environment.NewLine));
AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operation failed.", "RoboCopy operation failed."));
}
}
private string FormatCmd(string cmd, ChoAppSettings appSettings)
{
return cmd.Split("\n").Select(line => $">{line.Trim()}").Join(Environment.NewLine);
}
public bool RunRoboCopyOperation(ChoAppSettings appSettings)
{
string fileName = appSettings.RoboCopyFilePath;
string arguments = appSettings.GetCmdLineParams();
AppStatus.Raise(this, new ChoFileProcessEventArgs("Performing RoboCopy operation..."));
Status.Raise(this, new ChoFileProcessEventArgs("Performing RoboCopy operation..."));
string preCommands = appSettings.Precommands;
string postCommands = appSettings.Postcommands;
bool testRun = appSettings.ListOnly;
try
{
_waitForRobocopyProcessToExit.Reset();
// Setup the process start info
var processStartInfo = new ProcessStartInfo(fileName, arguments) // new ProcessStartInfo(fileName, arguments) //_appSettings.RoboCopyFilePath, _appSettings.GetCmdLineParams(sourceDirectory, destDirectory))
{
UseShellExecute = false,
//RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
Status.Raise(this, new ChoFileProcessEventArgs(Environment.NewLine));
// Setup the process
Process process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };
Status.Raise(this, new ChoFileProcessEventArgs($">{fileName} {arguments}"));
// Register event
_robocopyProcess = process;
// Start process
process.Start();
//process.BeginOutputReadLine();
Task.Factory.StartNew(new Action<object>(ParseRobocopyOutput), new Tuple<StreamReader, bool>(process.StandardOutput, false));
Task.Factory.StartNew(new Action<object>(ReadFromStreamReader), process.StandardError);
//Run robocopy
//process.StandardInput.WriteLine($"{fileName} {arguments} /L");
//process.StandardInput.WriteLine("exit");
process.WaitForExit();
_waitForRobocopyProcessToExit.WaitOne();
Status.Raise(this, new ChoFileProcessEventArgs(Environment.NewLine));
_robocopyProcess = null;
}
catch (ThreadAbortException)
{
return false;
}
catch (Exception)
{
return false;
}
return true;
}
public bool Analyze(ChoAppSettings appSettings)
{
string fileName = appSettings.RoboCopyFilePath;
string arguments = appSettings.GetCmdLineParams() + " /L";
AppStatus.Raise(this, new ChoFileProcessEventArgs("Analyzing RoboCopy operation..."));
Status.Raise(this, new ChoFileProcessEventArgs("Analyzing RoboCopy operation..."));
string preCommands = appSettings.Precommands;
string postCommands = appSettings.Postcommands;
bool testRun = appSettings.ListOnly;
try
{
_waitForRobocopyProcessToExit.Reset();
// Setup the process start info
var processStartInfo = new ProcessStartInfo(fileName, arguments) // new ProcessStartInfo(fileName, arguments) //_appSettings.RoboCopyFilePath, _appSettings.GetCmdLineParams(sourceDirectory, destDirectory))
{
UseShellExecute = false,
//RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
// Setup the process
Process process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };
// Register event
_analyzeRobocopyProcess = process;
// Start process
process.Start();
//process.BeginOutputReadLine();
Task.Factory.StartNew(new Action<object>(ParseRobocopyOutput), new Tuple<StreamReader, bool>(process.StandardOutput, true));
Task.Factory.StartNew(new Action<object>(ReadFromStreamReader), process.StandardError);
//Run robocopy
//process.StandardInput.WriteLine($"{fileName} {arguments} /L");
//process.StandardInput.WriteLine("exit");
process.WaitForExit();
_waitForRobocopyProcessToExit.WaitOne();
_analyzeRobocopyProcess = null;
}
catch (ThreadAbortException)
{
return false;
}
catch (Exception)
{
return false;
}
return true;
}
bool cleanup = false;
private string CleanUp(string txt)
{
//if (!cleanup)
//{
// if (txt.Contains(Environment.NewLine))
// txt = txt.Substring(txt.IndexOf(Environment.NewLine));
// else
// txt = null;
// cleanup = true;
//}
return txt;
}
private void ParseRobocopyOutput(object state)
{
cleanup = false;
StreamReader reader = ((Tuple<StreamReader, bool>)state).Item1;
bool isAnalyze = ((Tuple<StreamReader, bool>)state).Item2;
char[] buffer = new char[32768];
int chars;
StringBuilder txt = new StringBuilder();
while ((chars = reader.Read(buffer, 0, buffer.Length)) > 0)
{
string data = new string(buffer, 0, chars);
txt.Append(data);
if (txt.Length > 0)
{
var msg = CleanUp(txt.ToString());
int pos = msg.LastIndexOf(Environment.NewLine);
if (pos >= 0)
{
ParseRobocopyOutputData(msg.Substring(0, pos), isAnalyze);
txt.Clear();
txt.Append(msg.Substring(pos + 1));
}
}
}
if (txt.Length > 0)
{
ParseRobocopyOutputData(CleanUp(txt.ToString()), isAnalyze);
txt.Clear();
}
_waitForRobocopyProcessToExit.Set();
// You arrive here when process is terminated.
}
private void ParseRobocopyOutputData(string msg, bool isAnalyze)
{
if (!isAnalyze && msg.Length > 0)
Status.Raise(this, new ChoFileProcessEventArgs(msg));
var lines = msg.Split(Environment.NewLine).Where(m => !m.IsNullOrWhiteSpace()).ToArray();
long fileSize = 0;
foreach (var line in lines)
{
fileSize = 0;
var match = _regexBytes.Match(line);
if (match.Success)
{
fileSize += match.Value.CastTo<long>();
}
if (isAnalyze)
{
_totalBytes += fileSize;
_totalFileCount++;
}
else
{
_runningBytes += fileSize;
_runningFileCount++;
#if TEST_MODE
Thread.Sleep(1000);
#endif
var progress = Progress;
if (progress != null && _totalBytes > 0)
{
progress.Raise(null, new ChoRoboCopyProgressEventArgs(_runningBytes, _runningFileCount, _totalBytes, _totalFileCount));
}
}
}
}
private void ReadFromStreamReader(object state)
{
cleanup = false;
StreamReader reader = state as StreamReader;
char[] buffer = new char[32768];
int chars;
StringBuilder txt = new StringBuilder();
while ((chars = reader.Read(buffer, 0, buffer.Length)) > 0)
{
string data = new string(buffer, 0, chars);
txt.Append(data);
if (txt.Length > 0)
{
_hasError = true;
Status.Raise(this, new ChoFileProcessEventArgs(CleanUp(txt.ToString())));
txt.Clear();
}
}
if (txt.Length > 0)
{
_hasError = true;
Status.Raise(this, new ChoFileProcessEventArgs(CleanUp(txt.ToString())));
txt.Clear();
}
// You arrive here when process is terminated.
}
internal void Cancel()
{
_cancel = true;
_waitForRobocopyProcessToExit.Set();
Process process = _analyzeRobocopyProcess;
if (process != null)
{
try
{
try
{
KillProcessAndChildrens(_process.Id);
}
catch { }
process.Kill();
//AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operation canceled."));
_analyzeRobocopyProcess = null;
}
catch { }
}
process = _robocopyProcess;
if (process != null)
{
try
{
try
{
KillProcessAndChildrens(_process.Id);
}
catch { }
process.Kill();
//AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operation canceled."));
_robocopyProcess = null;
}
catch { }
}
process = _process;
if (process != null)
{
try
{
try
{
KillProcessAndChildrens(_process.Id);
}
catch { }
process.Kill();
AppStatus.Raise(this, new ChoFileProcessEventArgs("RoboCopy operation canceled."));
_process = null;
}
catch { }
}
}
private void KillProcessAndChildrens(int pid)
{
ManagementObjectSearcher processSearcher = new ManagementObjectSearcher
("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection processCollection = processSearcher.Get();
// We must kill child processes first!
if (processCollection != null)
{
foreach (ManagementObject mo in processCollection)
{
KillProcessAndChildrens(Convert.ToInt32(mo["ProcessID"])); //kill child processes(also kills childrens of childrens etc.)
}
}
// Then kill parents.
try
{
Process proc = System.Diagnostics.Process.GetProcessById(pid);
if (!proc.HasExited) proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
#endregion Instance Members (Public)
#region IDisposable Members
public void Dispose()
{
}
#endregion
}
}