-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Extensions.cs
701 lines (621 loc) · 31.3 KB
/
Extensions.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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//
// Copyright (c) Roland Pihlakas 2019 - 2023
// roland@simplify.ee
//
// Roland Pihlakas licenses this file to you under the GNU Lesser General Public License, ver 2.1.
// See the LICENSE file for more information.
//
#define ASYNC
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;
using Nito.AspNetBackgroundTasks;
using Nito.AsyncEx;
namespace FolderSync
{
public static class Extensions
{
public static Exception GetInnermostException(this Exception ex_in)
{
//see also https://stackoverflow.com/questions/16565834/exception-getbaseexception-returning-exception-with-not-null-innerexception
var ex2 = ex_in;
var ex2_aggex = ex2 as AggregateException;
while (
ex2_aggex != null
&& ex2_aggex.InnerExceptions.Count == 1
)
{
ex2 = ex2.InnerException;
ex2_aggex = ex2 as AggregateException;
}
return ex2;
}
public static long? CheckDiskSpace(string path)
{
long? freeBytes = null;
try //NB! on some drives (for example, RAM drives, GetDiskFreeSpaceEx does not work
{
//NB! DriveInfo works on paths well in Linux //TODO: what about Mac?
var drive = new DriveInfo(path);
freeBytes = drive.AvailableFreeSpace;
}
catch (ArgumentException)
{
if (ConfigParser.IsWindows)
{
long freeBytesOut;
if (WindowsDllImport.GetDiskFreeSpaceEx(path, out freeBytesOut, out var _, out var __))
freeBytes = freeBytesOut;
}
}
return freeBytes;
}
public static string GetLongPath(string path)
{
if (!ConfigParser.IsWindows)
{
//roland: fullCheck = false
return FolderSyncNetSource.Path.GetFullPath(path, fullCheck: false); //GetFullPath: convert relative path to full path
}
//@"\\?\" prefix is needed for reading from long paths: https://stackoverflow.com/questions/44888844/directorynotfoundexception-when-using-long-paths-in-net-4-7 and https://superuser.com/questions/1617012/support-of-the-unc-server-share-syntax-in-windows
if (
path.Length >= 4 //necessary to avoid exceptions in Substring()
&& path.Substring(0, 4) == @"\\?\" //network path or path already starting with \\?\
)
{
return path;
}
//https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats
else if (
path.Length >= 4 //necessary to avoid exceptions in Substring()
&& path.Substring(0, 4) == @"\\.\" //path already starting with \\.\
)
{
return path;
}
//https://stackoverflow.com/questions/36219317/pathname-too-long-to-open
else if (
path.Length >= 2 //necessary to avoid exceptions in Substring()
&& path.Substring(0, 2) == @"\\" //UNC network path
)
{
return @"\\?\UNC\" + path.Substring(2);
}
else
{
//roland: fullCheck = false
return @"\\?\" + FolderSyncNetSource.Path.GetFullPath(path, fullCheck: false); //GetFullPath: convert relative path to full path
}
} //public static string GetLongPath(string path)
public static string GetDirPathWithTrailingSlash(string dirPath)
{
if (string.IsNullOrWhiteSpace(dirPath))
return dirPath;
dirPath = FolderSyncNetSource.Path.Combine(dirPath, "_"); //NB! add "_" in order to ensure that slash is appended to the end of the path
dirPath = dirPath.Substring(0, dirPath.Length - 1); //drop the "_" again
return dirPath;
}
public static Task ContinueWithNoException(this Task task)
{
//https://stackoverflow.com/questions/20509158/taskcanceledexception-when-calling-task-delay-with-a-cancellationtoken-in-an-key/
//https://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html
var result = task.ContinueWith //ignore TaskCanceledException
(
completedTask => {
//this marks the exception as observed
return completedTask.Exception == null;
},
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, // | TaskContinuationOptions.OnlyOnCanceled,
TaskScheduler.Default
);
return result;
}
//on .NET 6 we could use .WaitAsync(new TimeSpan(timeout * 1000), childToken.Token) instead of creating a separate Task.Delay task.
//https://github.com/dotnet/runtime/blob/933988c35c172068652162adf6f20477231f815e/src/libraries/Common/tests/System/Threading/Tasks/TaskTimeoutExtensions.cs
//see also https://devblogs.microsoft.com/pfxteam/crafting-a-task-timeoutafter-method/
public static async Task WaitAsync(this Task task, int timeout, CancellationToken cancellationToken)
{
if (task.IsCompleted)
return;
var taskCompletionSource = new TaskCompletionSource<bool>();
using (new Timer
(
state => ((TaskCompletionSource<bool>)state).TrySetException(new TimeoutException()),
state: taskCompletionSource,
dueTime: timeout,
period: Timeout.Infinite
))
{
using (cancellationToken.Register
(
state => ((TaskCompletionSource<bool>)state).TrySetCanceled(cancellationToken),
taskCompletionSource
))
{
await Task.WhenAny(task, taskCompletionSource.Task);
}
}
}
private static async Task WriteLongRunningOperationMessage(BoolRef longRunningTaskMessageWrittenRef, AsyncLock longRunningOperationMessageLock, CancellationTokenSource childToken, string longRunningOperationMessage, bool suppressLogFile)
{
try
{
if (!childToken.IsCancellationRequested)
{
using (await longRunningOperationMessageLock.LockAsyncNoException(childToken.Token))
{
if (!childToken.IsCancellationRequested) //the above lock will not throw because we are using LockAsyncNoException
{
await ConsoleWatch.AddMessage(ConsoleColor.Gray, "Ongoing: " + longRunningOperationMessage, DateTime.Now, token: childToken.Token, suppressLogFile: suppressLogFile); //NB! suppressLogFile to avoid infinite recursion
longRunningTaskMessageWrittenRef.Value = true; //NB! set this flag only after the message was actually written else the task might be canceled before the console lock is taken
}
}
}
}
catch (Exception)
{
//ignore it
}
}
private static async Task RunWithTimeoutHelper(Task task, int timeout, CancellationToken parentToken, CancellationTokenSource childToken, string longRunningOperationMessage = null, bool suppressLogFile = false)
{
bool hasLongRunningOperationMessage = !string.IsNullOrWhiteSpace(longRunningOperationMessage);
var longRunningOperationMessageLock = new AsyncLock();
var longRunningTaskMessageWrittenRef = new BoolRef();
using
(
hasLongRunningOperationMessage
? new Timer
(
state => /*Task.WhenAny(*/Task.Run(async () => {
#if true
await WriteLongRunningOperationMessage
(
longRunningTaskMessageWrittenRef,
longRunningOperationMessageLock,
childToken,
longRunningOperationMessage,
suppressLogFile
)
.ContinueWithNoException();
#else
if (!childToken.IsCancellationRequested)
{
using (await longRunningOperationMessageLock.LockAsync(/*childToken.Token*/))
{
if (!childToken.IsCancellationRequested)
{
await Program.AddMessage(ConsoleColor.Gray, longRunningOperationMessage, DateTime.Now, token: childToken.Token, suppressLogFile: suppressLogFile); //NB! suppressLogFile to avoid infinite recursion
longRunningTaskMessageWritten = true; //NB! set this flag only after the message was actually written else the task might be canceled before the console lock is taken
}
}
}
#endif
})/*)*/,
state: null,
dueTime: 1000, //TODO: config
period: 60 * 1000 //TODO: config
)
: null
)
{
try
{
if (timeout > 0)
{
await task.WaitAsync(timeout * 1000, parentToken);
}
else
{
await task;
}
}
finally
{
if (!parentToken.IsCancellationRequested/* && !task.IsCompleted*/)
{
//cancel task and longRunningOperationMessage lock wait. Else the timer callback may run after the timer is disposed
//"Note that callbacks can occur after the Dispose() method overload has been called, because the timer queues callbacks for execution by thread pool threads."
//https://msdn.microsoft.com/en-us/library/system.threading.timer.aspx#Remarks
childToken.Cancel();
}
}
} //using (new Timer
if (hasLongRunningOperationMessage)
{
//do not enter the if (longRunningTaskMessageWritten) check before the longRunningOperationMessageLock is free
using (await longRunningOperationMessageLock.LockAsyncNoException(parentToken))
{
//NB! The above lock will not throw because we are using LockAsyncNoException
if (task.IsCompleted && !task.IsCanceled)
{
if (longRunningTaskMessageWrittenRef.Value)
{
//NB! not using childToken here since it will be already canceled and would raise an exception
await ConsoleWatch.AddMessage(ConsoleColor.Gray, "DONE " + longRunningOperationMessage, DateTime.Now, token: parentToken, suppressLogFile: suppressLogFile); //NB! suppressLogFile to avoid infinite recursion
}
}
else if (/*longRunningTaskMessageWrittenRef.Value && */parentToken.IsCancellationRequested) //the above lock will not throw because we are using LockAsyncNoException
{
await ConsoleWatch.AddMessage(ConsoleColor.Red, "CANCELED " + longRunningOperationMessage, DateTime.Now, token: parentToken, suppressLogFile: suppressLogFile); //NB! suppressLogFile to avoid infinite recursion
}
else if (task.Status == TaskStatus.Faulted)
{
await ConsoleWatch.AddMessage(ConsoleColor.Red, "FAILED " + longRunningOperationMessage, DateTime.Now, token: parentToken, suppressLogFile: suppressLogFile); //NB! suppressLogFile to avoid infinite recursion
}
else //if (longRunningTaskMessageWrittenRef.Value)
{
await ConsoleWatch.AddMessage(ConsoleColor.Red, "TIMED OUT " + longRunningOperationMessage, DateTime.Now, token: parentToken, suppressLogFile: suppressLogFile); //NB! suppressLogFile to avoid infinite recursion
}
}
} //if (hasLongRunningOperationMessage)
} //private static async Task<bool> RunWithTimeoutHelper(Task task, int timeout, CancellationToken token, CancellationTokenSource childToken, string longRunningOperationMessage = null, bool suppressLogFile = false)
public static async Task RunWithTimeout(Action<CancellationToken> func, int timeout, CancellationToken parentToken, string longRunningOperationMessage = null, bool suppressLogFile = false)
{
if (parentToken.IsCancellationRequested)
throw new TaskCanceledException();
//no timeout
if (timeout <= 0 && string.IsNullOrWhiteSpace(longRunningOperationMessage))
{
func(parentToken);
return;
}
//using (var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken))
var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken); //remove "using" since the childToken needs to stay alive until the task ends
{
//no need for TaskCreationOptions.LongRunning : http://blog.i3arnon.com/2015/07/02/task-run-long-running/
var task = Task.Run(() => func(childToken.Token), childToken.Token);
await RunWithTimeoutHelper(task, timeout, parentToken, childToken, longRunningOperationMessage, suppressLogFile);
//Disposal is only required for tokens that won't be cancelled, as cancellation does all of the same cleanup. - https://github.com/aspnet/AspNetKatana/issues/108
//childToken.Cancel(); //comment-out: already called inside RunWithTimeoutHelper()
if (task.IsCompleted && !task.IsCanceled)
{
await task; //raise any exceptions from the task
return;
}
else if (parentToken.IsCancellationRequested)
throw new TaskCanceledException(task);
else
throw new TimeoutException("Timed out");
}
} //public static async Task RunWithTimeout(Action func, int timeout, CancellationToken parentToken)
public static async Task RunWithTimeout(Func<CancellationToken, Task> func, int timeout, CancellationToken parentToken, string longRunningOperationMessage = null, bool suppressLogFile = false)
{
if (parentToken.IsCancellationRequested)
throw new TaskCanceledException();
//no timeout
if (timeout <= 0 && string.IsNullOrWhiteSpace(longRunningOperationMessage))
{
await func(parentToken);
return;
}
//using (var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken))
var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken); //remove "using" since the childToken needs to stay alive until the task ends
{
//no need for TaskCreationOptions.LongRunning : http://blog.i3arnon.com/2015/07/02/task-run-long-running/
var task = Task.Run(() => func(childToken.Token), childToken.Token);
await RunWithTimeoutHelper(task, timeout, parentToken, childToken, longRunningOperationMessage, suppressLogFile);
//Disposal is only required for tokens that won't be cancelled, as cancellation does all of the same cleanup. - https://github.com/aspnet/AspNetKatana/issues/108
//childToken.Cancel(); //comment-out: already called inside RunWithTimeoutHelper()
if (task.IsCompleted && !task.IsCanceled)
{
await task; //raise any exceptions from the task
return;
}
else if (parentToken.IsCancellationRequested)
throw new TaskCanceledException(task);
else
throw new TimeoutException("Timed out");
}
} //public static async Task RunWithTimeout(Action func, int timeout, CancellationToken parentToken)
public static async Task<T> RunWithTimeout<T>(Func<CancellationToken, T> func, int timeout, CancellationToken parentToken, string longRunningOperationMessage = null, bool suppressLogFile = false)
{
if (parentToken.IsCancellationRequested)
throw new TaskCanceledException();
//no timeout
if (timeout <= 0 && string.IsNullOrWhiteSpace(longRunningOperationMessage))
{
var result = func(parentToken);
return result;
}
//using (var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken))
var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken); //remove "using" since the childToken needs to stay alive until the task ends
{
//no need for TaskCreationOptions.LongRunning : http://blog.i3arnon.com/2015/07/02/task-run-long-running/
var task = Task.Run(() => func(parentToken), childToken.Token);
await RunWithTimeoutHelper(task, timeout, parentToken, childToken, longRunningOperationMessage, suppressLogFile);
//Disposal is only required for tokens that won't be cancelled, as cancellation does all of the same cleanup. - https://github.com/aspnet/AspNetKatana/issues/108
//childToken.Cancel(); //comment-out: already called inside RunWithTimeoutHelper()
if (task.IsCompleted && !task.IsCanceled)
{
var result = await task; //raise any exceptions from the task
return result;
}
else if (parentToken.IsCancellationRequested)
throw new TaskCanceledException(task);
else
throw new TimeoutException("Timed out");
}
} //public static async Task<T> RunWithTimeout<T>(Func<T> func, int timeout, CancellationToken parentToken)
public static async Task<T> RunWithTimeout<T>(Func<CancellationToken, Task<T>> func, int timeout, CancellationToken parentToken, string longRunningOperationMessage = null, bool suppressLogFile = false)
{
if (parentToken.IsCancellationRequested)
throw new TaskCanceledException();
//no timeout
if (timeout <= 0 && string.IsNullOrWhiteSpace(longRunningOperationMessage))
{
var result = await func(parentToken);
return result;
}
//using (var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken))
var childToken = CancellationTokenSource.CreateLinkedTokenSource(parentToken); //remove "using" since the childToken needs to stay alive until the task ends
{
//no need for TaskCreationOptions.LongRunning : http://blog.i3arnon.com/2015/07/02/task-run-long-running/
var task = Task.Run(() => func(childToken.Token), childToken.Token);
await RunWithTimeoutHelper(task, timeout, parentToken, childToken, longRunningOperationMessage, suppressLogFile);
//Disposal is only required for tokens that won't be cancelled, as cancellation does all of the same cleanup. - https://github.com/aspnet/AspNetKatana/issues/108
//childToken.Cancel(); //comment-out: already called inside RunWithTimeoutHelper()
if (task.IsCompleted && !task.IsCanceled)
{
var result = await task; //raise any exceptions from the task
return result;
}
else if (parentToken.IsCancellationRequested)
throw new TaskCanceledException(task);
else
throw new TimeoutException("Timed out");
}
} //public static async Task<T> RunWithTimeout<T>(Func<T> func, int timeout, CancellationToken parentToken)
public static async Task FSOperation(Action<CancellationToken> func, string path, CancellationToken token, int? timeout = null, bool suppressLogFile = false, bool suppressLongRunningOperationMessage = false)
{
//await Task.Run(func).WaitAsync(token);
//func();
try
{
await RunWithTimeout
(
func,
timeout ?? Global.FSOperationTimeout,
token,
!suppressLongRunningOperationMessage ? "Running filesystem operation on " + path : null,
suppressLogFile
);
}
catch (TimeoutException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Timed out filesystem operation on " + path, ex);
}
catch (TaskCanceledException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Cancelled filesystem operation on " + path, ex);
}
}
public static async Task FSOperation(Func<CancellationToken, Task> func, string path, CancellationToken token, int? timeout = null, bool suppressLogFile = false, bool suppressLongRunningOperationMessage = false)
{
//await Task.Run(func).WaitAsync(token);
//func();
try
{
await RunWithTimeout
(
func,
timeout ?? Global.FSOperationTimeout,
token,
!suppressLongRunningOperationMessage ? "Running filesystem operation on " + path : null,
suppressLogFile
);
}
catch (TimeoutException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Timed out filesystem operation on " + path, ex);
}
catch (TaskCanceledException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Cancelled filesystem operation on " + path, ex);
}
}
public static async Task<T> FSOperation<T>(Func<CancellationToken, T> func, string path, CancellationToken token, int? timeout = null, bool suppressLogFile = false, bool suppressLongRunningOperationMessage = false)
{
//var result = await Task.Run(func).WaitAsync(token);
//var result = func();
//return result;
try
{
var result = await RunWithTimeout
(
func,
timeout ?? Global.FSOperationTimeout,
token,
!suppressLongRunningOperationMessage ? "Running filesystem operation on " + path : null,
suppressLogFile
);
return result;
}
catch (TimeoutException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Timed out filesystem operation on " + path, ex);
}
catch (TaskCanceledException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Cancelled filesystem operation on " + path, ex);
}
}
public static async Task<T> FSOperation<T>(Func<CancellationToken, Task<T>> func, string path, CancellationToken token, int? timeout = null, bool suppressLogFile = false, bool suppressLongRunningOperationMessage = false)
{
//var result = await Task.Run(func).WaitAsync(token);
//var result = func();
//return result;
try
{
var result = await RunWithTimeout
(
func,
timeout ?? Global.FSOperationTimeout,
token,
!suppressLongRunningOperationMessage ? "Running filesystem operation on " + path : null,
suppressLogFile
);
return result;
}
catch (TimeoutException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Timed out filesystem operation on " + path, ex);
}
catch (TaskCanceledException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Cancelled filesystem operation on " + path, ex);
}
}
public static async Task<T[]> DirListOperation<T>(Func<CancellationToken, T[]> func, string path, int retryCount, CancellationToken token, int? timeout = null, bool suppressLongRunningOperationMessage = false)
{
retryCount = Math.Max(0, retryCount);
for (int tryIndex = -1; tryIndex < retryCount; tryIndex++)
{
//T result = await Task.Run(func).WaitAsync(token);
//var result = func();
T[] result;
try
{
result = await RunWithTimeout
(
func,
timeout ?? Global.DirListOperationTimeout,
token,
!suppressLongRunningOperationMessage ? "Running dirlist operation on " + path : null
);
}
catch (TimeoutException ex)
{
//Console.WriteLine("Timed out dirlist operation on " + path);
//throw;
throw new AggregateException("Timed out dirlist operation on " + path, ex);
}
catch (TaskCanceledException ex)
{
//Console.WriteLine("Timed out filesystem operation on " + path);
//throw;
throw new AggregateException("Cancelled filesystem operation on " + path, ex);
}
if (result.Length > 0)
return result;
#if DEBUG
if (result is FileInfo[])
{
bool qqq = true; //for debugging
}
#endif
if (tryIndex + 1 < retryCount) //do not sleep after last try
{
#if !NOASYNC
await Task.Delay(1000, token); //TODO: config file?
#else
token.WaitHandle.WaitOne(1000);
#endif
}
}
return new T[0];
} //public static async Task<T[]> DirListOperation<T>(Func<T[]> func, string path, int retryCount, CancellationToken token)
public static byte[] SerializeBinary<T>(this T obj, bool compress = true)
{
var formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Persistence);
using (var mstream = new MemoryStream())
{
if (compress)
{
using (var gzStream = new GZipStream(mstream, CompressionLevel.Optimal, leaveOpen: true))
{
formatter.Serialize(gzStream, obj);
}
}
else
{
formatter.Serialize(mstream, obj);
}
byte[] bytes = new byte[mstream.Length];
mstream.Position = 0; //NB! reset stream position
mstream.Read(bytes, 0, (int)mstream.Length);
return bytes;
}
}
public static T DeserializeBinary<T>(this byte[] bytes, bool? decompress = null)
{
var formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Persistence);
using (var mstream = new MemoryStream(bytes))
{
mstream.Position = 0;
if (decompress == null) //auto detect
{
if (mstream.ReadByte() == 0x1F && mstream.ReadByte() == 0x8B)
decompress = true;
mstream.Position = 0; //reset stream position
}
if (decompress == true)
{
using (var gzStream = new GZipStream(mstream, CompressionMode.Decompress, leaveOpen: true))
{
object result = formatter.Deserialize(gzStream);
if (result is T)
return (T)result;
return default(T);
}
}
else
{
object result = formatter.Deserialize(mstream);
if (result is T)
return (T)result;
return default(T);
}
}
}
//https://stackoverflow.com/questions/7265315/replace-multiple-characters-in-a-c-sharp-string
public static string Replace(string str, char[] search, string replacement)
{
var temp = str.Split(search, StringSplitOptions.None);
return String.Join(replacement, temp);
}
/// <summary>
/// NB! If you use this method then you need to manually check whether cancellation was requested, since the lock will seemingly "enter", though it actually only canceled the wait
/// </summary>
//[DebuggerHidden]
//[DebuggerStepThrough]
public static async Task<IDisposable> LockAsyncNoException(this Nito.AsyncEx.AsyncLock lockObj, CancellationToken cancellationToken)
{
try
{
var lockHandle = await lockObj.LockAsync(cancellationToken);
return lockHandle;
}
catch (TaskCanceledException)
{
//ignore it
return Task.CompletedTask;
}
}
}
}