-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUtility.cs
3228 lines (2898 loc) · 130 KB
/
Utility.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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Related components
using System;
using System.IO;
using System.Xml;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Http;
using System.IO.Compression;
using System.Net.Http.Headers;
using System.Numerics;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Configuration;
using Microsoft.IO;
using Newtonsoft.Json.Linq;
#endregion
#if !SIGN
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VIEApps.Components.XUnitTests")]
#endif
namespace net.vieapps.Components.Utility
{
/// <summary>
/// Utility servicing methods
/// </summary>
public static partial class UtilityService
{
#region UUID
/// <summary>
/// Gets an UUID (128 bits unique universal identity)
/// </summary>
/// <param name="asBase64Url">Set to true to encoded as base64-url string</param>
/// <param name="uuid">The string that presents an UUID</param>
/// <param name="format">The string that presents the format</param>
/// <returns>The string that presents an 128 bits UUID</returns>
public static string GetUUID(bool asBase64Url = false, string uuid = null, string format = null)
{
var guid = string.IsNullOrWhiteSpace(uuid) ? Guid.NewGuid() : new Guid(uuid.Trim());
return asBase64Url ? guid.ToByteArray().ToBase64Url() : guid.ToString(format ?? "N");
}
/// <summary>
/// Gets an UUID (128 bits unique universal identity)
/// </summary>
/// <param name="uuid">The array of bytes that presents an UUID</param>
/// <param name="format">The string that presents the format</param>
/// <param name="asBase64Url">Set to true to encoded as base64-url string</param>
/// <returns>The string that presents an 128 bits UUID</returns>
public static string GetUUID(string uuid, string format = null, bool asBase64Url = false)
=> UtilityService.GetUUID(asBase64Url, uuid, format);
/// <summary>
/// Gets an UUID (128 bits unique universal identity)
/// </summary>
/// <param name="uuid">The array of bytes that presents an UUID</param>
/// <param name="format">The string that presents the format</param>
/// <param name="asBase64Url">Set to true to encoded as base64-url string</param>
/// <returns>The string that presents an 128 bits UUID</returns>
public static string GetUUID(byte[] uuid, string format = null, bool asBase64Url = false)
{
var guid = uuid == null || !uuid.Any() ? Guid.NewGuid() : new Guid(uuid.Take(16));
return asBase64Url ? guid.ToByteArray().ToBase64Url() : guid.ToString(format ?? "N");
}
/// <summary>
/// Generate an identity as UUID-format from this string
/// </summary>
/// <param name="string"></param>
/// <param name="format">The string that presents the format</param>
/// <param name="mode">BLAKE or MD5</param>
/// <param name="asBase64Url">Set to true to encoded as base64-url string</param>
/// <returns>The string that presents an 128 bits UUID</returns>
public static string GenerateUUID(this string @string, string format = null, string mode = null, bool asBase64Url = false)
=> string.IsNullOrWhiteSpace(@string)
? UtilityService.GetUUID(asBase64Url, null, format)
: UtilityService.GetUUID(@string.GetHash(!string.IsNullOrWhiteSpace(mode) && mode.IsStartsWith("blake") ? "blake128" : "md5"), format, asBase64Url);
/// <summary>
/// Generate an identity as UUID-format from this array of bytes
/// </summary>
/// <param name="bytes"></param>
/// <param name="format">The string that presents the format</param>
/// <param name="mode">BLAKE or MD5</param>
/// <param name="asBase64Url">Set to true to encoded as base64-url string</param>
/// <returns>The string that presents an 128 bits UUID</returns>
public static string GenerateUUID(this byte[] bytes, string format = null, string mode = null, bool asBase64Url = false)
=> UtilityService.GetUUID(bytes?.GetHash(!string.IsNullOrWhiteSpace(mode) && mode.IsStartsWith("blake") ? "blake128" : "md5"), format, asBase64Url);
/// <summary>
/// Gets a new UUID (universal unique identity - 128 bits or 32 hexa-characters)
/// </summary>
public static string NewUUID => UtilityService.GetUUID();
static string _BlankUUID = null;
/// <summary>
/// Gets the blank UUID
/// </summary>
/// <returns></returns>
public static string BlankUUID => UtilityService._BlankUUID ?? (UtilityService._BlankUUID = new string('0', 32));
static Regex HexRegex => new Regex("[^0-9a-fA-F]+");
/// <summary>
/// Validates the UUID string
/// </summary>
/// <param name="uuid"></param>
/// <param name="onlyHex">true to only allow hexa characters</param>
/// <returns>true if it is valid; otherwise false.</returns>
public static bool IsValidUUID(this string uuid, bool onlyHex = true)
=> !string.IsNullOrWhiteSpace(uuid) && uuid.Length.Equals(32) && (onlyHex ? UtilityService.HexRegex.Replace(uuid, "").Equals(uuid) : !uuid.Contains(" ") && !uuid.Contains(";"));
#endregion
#region Random number & code
readonly static Random _Random = new Random();
/// <summary>
/// Gets the random number between min and max
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static int GetRandomNumber(int min = 0, int max = Int32.MaxValue)
=> UtilityService._Random.Next(min, max);
readonly static RandomBigInteger _RandomBigInteger = new RandomBigInteger();
/// <summary>
/// Gets the random of big integer number
/// </summary>
/// <param name="length">The number of random bits to generate.</param>
/// <returns></returns>
public static BigInteger GetRandomNumber(int length)
=> UtilityService._RandomBigInteger.Next(length);
/// <summary>
/// Gets a random code
/// </summary>
/// <param name="useShortCode">true to use short-code</param>
/// <param name="useHex">true to use hexa in code</param>
/// <returns>The string that presents random code</returns>
public static string GetRandomCode(bool useShortCode = true, bool useHex = false)
{
var code = UtilityService.GetUUID();
var length = 9;
if (useShortCode)
length = 4;
if (!useHex)
{
code = UtilityService.GetRandomNumber(1000).ToString() + UtilityService.GetRandomNumber(1000).ToString();
while (code.Length < length + 5)
code += UtilityService.GetRandomNumber(1000).ToString();
}
var index = UtilityService.GetRandomNumber(0, code.Length);
if (index > code.Length - length)
index = code.Length - length;
code = code.Substring(index, length);
var random1 = ((char)UtilityService.GetRandomNumber(48, 57)).ToString();
var replacement = "O";
while (replacement.Equals("O"))
replacement = ((char)UtilityService.GetRandomNumber(71, 90)).ToString();
code = code.Replace(random1, replacement);
if (length > 4)
{
var random2 = random1;
while (random2.Equals(random1))
random2 = ((char)UtilityService.GetRandomNumber(48, 57)).ToString();
replacement = "O";
while (replacement.Equals("O"))
replacement = ((char)UtilityService.GetRandomNumber(71, 90)).ToString();
code = code.Replace(random2, replacement);
var random3 = random1;
while (random3.Equals(random1))
{
random3 = ((char)UtilityService.GetRandomNumber(48, 57)).ToString();
if (random3.Equals(random2))
random3 = ((char)UtilityService.GetRandomNumber(48, 57)).ToString();
}
replacement = "O";
while (replacement.Equals("O"))
replacement = ((char)UtilityService.GetRandomNumber(71, 90)).ToString();
code = code.Replace(random3, replacement);
}
var hasNumber = false;
var hasChar = false;
for (int charIndex = 0; charIndex < code.Length; charIndex++)
{
if (code[charIndex] >= '0' && code[charIndex] <= '9')
hasNumber = true;
if (code[charIndex] >= 'A' && code[charIndex] <= 'Z')
hasChar = true;
if (hasNumber && hasChar)
break;
}
if (!hasNumber)
code += ((char)UtilityService.GetRandomNumber(48, 57)).ToString();
if (!hasChar)
{
replacement = "O";
while (replacement.Equals("O"))
replacement = ((char)UtilityService.GetRandomNumber(65, 90)).ToString();
code += replacement;
}
return code.Right(length);
}
#endregion
#region Task/CancellationToken extensions
/// <summary>
/// Executes an action in the thread pool with cancellation supported
/// </summary>
/// <param name="action">The action to run in the thread pool</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="creationOptions">The options that controls the behavior of the created task</param>
/// <param name="scheduler">The scheduler that is used to schedule the created task</param>
/// <returns>An awaitable task</returns>
public static Task ExecuteTask(Action action, CancellationToken cancellationToken = default, TaskCreationOptions creationOptions = TaskCreationOptions.DenyChildAttach, TaskScheduler scheduler = null)
=> Task.Factory.StartNew(action, cancellationToken, creationOptions, scheduler ?? TaskScheduler.Default);
/// <summary>
/// Executes an action in the thread pool with cancellation supported
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func">The function to run in the thread pool</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="creationOptions">The options that controls the behavior of the created task</param>
/// <param name="scheduler">The scheduler that is used to schedule the created task</param>
/// <returns>An awaitable task</returns>
public static Task<T> ExecuteTask<T>(Func<T> func, CancellationToken cancellationToken = default, TaskCreationOptions creationOptions = TaskCreationOptions.DenyChildAttach, TaskScheduler scheduler = null)
=> Task.Factory.StartNew(func, cancellationToken, creationOptions, scheduler ?? TaskScheduler.Default);
/// <summary>
/// Runs a task and just forget it (or wait for completion)
/// </summary>
/// <param name="task"></param>
/// <param name="onError">The error handler</param>
/// <param name="waitForCompletion">true to wait for completion of the task</param>
/// <param name="defer">defer in miliseconds</param>
public static void Run(this Task task, Action<Exception> onError = null, bool waitForCompletion = false, int defer = 0)
{
var instance = Task.Run(async () =>
{
try
{
if (defer > 0)
await Task.Delay(defer).ConfigureAwait(false);
await task.ConfigureAwait(false);
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
});
if (waitForCompletion)
instance.Wait();
else
instance.ConfigureAwait(false);
}
/// <summary>
/// Runs a task and just forget it (or wait for completion)
/// </summary>
/// <param name="task"></param>
/// <param name="waitForCompletion">true to wait for completion of the task</param>
public static void Run(this Task task, bool waitForCompletion)
=> task.Run(null, waitForCompletion, 0);
/// <summary>
/// Runs a task and just forget it (or wait for completion)
/// </summary>
/// <param name="task"></param>
/// <param name="defer">defer in miliseconds</param>
public static void Run(this Task task, int defer)
=> task.Run(null, false, defer);
/// <summary>
/// Runs a task and just forget it (or wait for completion)
/// </summary>
/// <param name="task"></param>
/// <param name="onError">The error handler</param>
/// <param name="waitForCompletion">true to wait for completion of the task</param>
/// <param name="defer">defer in miliseconds</param>
public static void Run(this ValueTask task, Action<Exception> onError = null, bool waitForCompletion = false, int defer = 0)
=> task.AsTask().Run(onError, waitForCompletion, defer);
/// <summary>
/// Runs a task and just forget it (or wait for completion)
/// </summary>
/// <param name="task"></param>
/// <param name="waitForCompletion">true to wait for completion of the task</param>
public static void Run(this ValueTask task, bool waitForCompletion)
=> task.Run(null, waitForCompletion, 0);
/// <summary>
/// Runs a task and just forget it (or wait for completion)
/// </summary>
/// <param name="task"></param>
/// <param name="defer">defer in miliseconds</param>
public static void Run(this ValueTask task, int defer)
=> task.Run(null, false, defer);
/// <summary>
/// Performs an awaitable task with cancellation token supported
/// </summary>
/// <param name="task"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task WithCancellationToken(this Task task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs, false))
{
var result = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
if (result != task)
throw new OperationCanceledException(cancellationToken);
}
}
/// <summary>
/// Performs an awaitable task with cancellation token supported
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="task"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<T> WithCancellationToken<T>(this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(state => ((TaskCompletionSource<bool>)state).TrySetResult(true), tcs, false))
{
var result = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false);
return result != task
? throw new OperationCanceledException(cancellationToken)
: task.Result;
}
}
/// <summary>
/// Writes a string to the stream asynchronously
/// </summary>
/// <param name="writer"></param>
/// <param name="string"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteAsync(this StreamWriter writer, string @string, CancellationToken cancellationToken)
#if NETSTANDARD2_0
=> writer.WriteAsync(@string).WithCancellationToken(cancellationToken);
#else
=> writer.WriteAsync(@string == null ? null : @string.AsMemory(), cancellationToken);
#endif
/// <summary>
/// Writes a line of string to the stream asynchronously
/// </summary>
/// <param name="writer"></param>
/// <param name="string"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteLineAsync(this StreamWriter writer, string @string, CancellationToken cancellationToken)
#if NETSTANDARD2_0
=> writer.WriteLineAsync(@string).WithCancellationToken(cancellationToken);
#else
=> writer.WriteLineAsync(@string == null ? null : @string.AsMemory(), cancellationToken);
#endif
#if NETSTANDARD2_0
/// <summary>
/// Reads all characters from the current position to the end of the stream asynchronously and returns them as one string
/// </summary>
/// <param name="reader"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<string> ReadToEndAsync(this StreamReader reader, CancellationToken cancellationToken)
=> reader.ReadToEndAsync().WithCancellationToken(cancellationToken);
/// <summary>
/// Reads a line of characters asynchronously from the current stream and returns the data as a string
/// </summary>
/// <param name="reader"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<string> ReadLineAsync(this StreamReader reader, CancellationToken cancellationToken)
=> reader.ReadLineAsync().WithCancellationToken(cancellationToken);
public static Task CopyToAsync(this Stream source, Stream destinaion, CancellationToken cancellationToken)
=> source.CopyToAsync(destinaion).WithCancellationToken(cancellationToken);
public static Task CopyToAsync(this HttpContent httpContent, Stream stream, CancellationToken cancellationToken)
=> httpContent.CopyToAsync(stream).WithCancellationToken(cancellationToken);
public static Task<Stream> ReadAsStreamAsync(this HttpContent httpContent, CancellationToken cancellationToken)
=> httpContent.ReadAsStreamAsync().WithCancellationToken(cancellationToken);
public static Task<byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, CancellationToken cancellationToken)
=> httpContent.ReadAsByteArrayAsync().WithCancellationToken(cancellationToken);
public static Task<string> ReadAsStringAsync(this HttpContent httpContent, CancellationToken cancellationToken)
=> httpContent.ReadAsStringAsync().WithCancellationToken(cancellationToken);
#endif
#endregion
#region Stream/MemoryStream extensions
static RecyclableMemoryStreamManager RecyclableMemoryStreamManager { get; } = new RecyclableMemoryStreamManager();
/// <summary>
/// Gets the recyclable memory stream manager (with RecyclableMemoryStreamManager class to limit LOH fragmentation and improve performance)
/// </summary>
/// <returns></returns>
public static RecyclableMemoryStreamManager GetRecyclableMemoryStreamManager()
=> UtilityService.RecyclableMemoryStreamManager;
/// <summary>
/// Creates an instance of <see cref="MemoryStream">MemoryStream</see> using RecyclableMemoryStream to limit LOH fragmentation and improve performance
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
/// <returns></returns>
public static MemoryStream CreateMemoryStream(byte[] buffer = null, int index = 0, int count = 0)
{
MemoryStream stream;
try
{
stream = UtilityService.RecyclableMemoryStreamManager.GetStream();
}
catch
{
stream = new MemoryStream();
}
if (buffer != null && buffer.Length > 0)
{
index = index > -1 && index < buffer.Length ? index : 0;
count = count > 0 && count < buffer.Length - index ? count : buffer.Length - index;
stream.Write(buffer, index, count);
stream.Seek(0, SeekOrigin.Begin);
}
return stream;
}
/// <summary>
/// Converts this array of bytes to memory stream
/// </summary>
/// <param name="buffer"></param>
/// <param name="index"></param>
/// <param name="count"></param>
/// <returns></returns>
public static MemoryStream ToMemoryStream(this byte[] buffer, int index = 0, int count = 0)
=> UtilityService.CreateMemoryStream(buffer, index, count);
/// <summary>
/// Converts this array segment of bytes to memory stream
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static MemoryStream ToMemoryStream(this ArraySegment<byte> buffer)
=> UtilityService.CreateMemoryStream(buffer.Array, buffer.Offset, buffer.Count);
/// <summary>
/// Reads this stream and converts to memory stream
/// </summary>
/// <param name="stream"></param>
/// <param name="onCompleted"></param>
/// <returns></returns>
public static MemoryStream ToMemoryStream(this Stream stream, Action<MemoryStream> onCompleted = null)
{
var memoryStream = UtilityService.CreateMemoryStream();
var buffer = new byte[4096];
var read = stream.Read(buffer, 0, buffer.Length);
while (read > 0)
{
memoryStream.Write(buffer, 0, read);
read = stream.Read(buffer, 0, buffer.Length);
}
memoryStream.Seek(0, SeekOrigin.Begin);
onCompleted?.Invoke(memoryStream);
return memoryStream;
}
/// <summary>
/// Reads this stream and converts to memory stream
/// </summary>
/// <param name="stream"></param>
/// <param name="cancellationToken"></param>
/// <param name="onCompleted"></param>
/// <returns></returns>
public static async Task<MemoryStream> ToMemoryStreamAsync(this Stream stream, CancellationToken cancellationToken = default, Action<MemoryStream> onCompleted = null)
{
var memoryStream = UtilityService.CreateMemoryStream();
var buffer = new byte[4096];
var read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
while (read > 0)
{
await memoryStream.WriteAsync(buffer, read, cancellationToken).ConfigureAwait(false);
read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
}
memoryStream.Seek(0, SeekOrigin.Begin);
onCompleted?.Invoke(memoryStream);
return memoryStream;
}
/// <summary>
/// Converts this memory stream to array segment of byte
/// </summary>
/// <param name="stream"></param>
/// <remarks>
/// Try to get buffer first to avoid calling ToArray on the MemoryStream because it allocates a new byte array on the heap.
/// Avoid this by attempting to access the internal memory stream buffer, this works with supported streams like the recyclable memory stream and writable memory streams
/// </remarks>
/// <returns></returns>
public static ArraySegment<byte> ToArraySegment(this MemoryStream stream)
=> stream.TryGetBuffer(out var buffer) ? buffer : new ArraySegment<byte>(stream.ToArray());
/// <summary>
/// Converts this memory stream to array of bytes
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static byte[] ToBytes(this MemoryStream stream)
{
if (stream.TryGetBuffer(out var buffer))
{
var array = new byte[buffer.Count];
Buffer.BlockCopy(buffer.Array, buffer.Offset, array, 0, buffer.Count);
return array;
}
return stream.ToArray();
}
/// <summary>
/// Writes the string lines to the stream asynchronously
/// </summary>
/// <param name="writer"></param>
/// <param name="lines"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteLinesAsync(this StreamWriter writer, IEnumerable<string> lines, CancellationToken cancellationToken)
=> lines == null
? Task.CompletedTask
#if NETSTANDARD2_0
: lines.Where(line => line != null).ForEachAsync(line => writer.WriteLineAsync(line, cancellationToken), true, false);
#else
: lines.Where(line => line != null).ForEachAsync(line => writer.WriteLineAsync(line.AsMemory(), cancellationToken), true, false);
#endif
/// <summary>
/// Writes the string lines to the stream asynchronously
/// </summary>
/// <param name="writer"></param>
/// <param name="lines"></param>
/// <returns></returns>
public static void WriteLines(this StreamWriter writer, IEnumerable<string> lines)
=> lines?.Where(line => line != null).ForEach(line => writer.WriteLine(line));
/// <summary>
/// Reads all characters from the stream asynchronously and returns them as one string
/// </summary>
/// <param name="stream"></param>
/// <param name="cancellationToken"></param>
/// <param name="leaveOpen"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static async Task<string> ReadAllAsync(this Stream stream, CancellationToken cancellationToken = default, bool leaveOpen = false, Encoding encoding = null)
{
if (stream.CanSeek)
stream.Seek(0, SeekOrigin.Begin);
using (var streamReader = new StreamReader(stream, encoding ?? Encoding.UTF8, encoding == null, TextFileReader.BufferSize, leaveOpen))
return await streamReader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
}
#if NETSTANDARD2_0
public static Task<int> ReadAsync(this Stream stream, byte[] buffer, CancellationToken cancellationToken)
=> stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
public static Task WriteAsync(this Stream stream, byte[] buffer, int count = 0, CancellationToken cancellationToken = default)
=> stream.WriteAsync(buffer, 0, count > 0 ? count : buffer.Length, cancellationToken);
public static Task WriteAsync(this Stream stream, ArraySegment<byte> buffer, CancellationToken cancellationToken = default)
=> stream.WriteAsync(buffer.Array, buffer.Offset, buffer.Count, cancellationToken);
#else
public static Task WriteAsync(this Stream stream, byte[] buffer, int count = 0, CancellationToken cancellationToken = default)
=> stream.WriteAsync(buffer.AsMemory(0, count > 0 ? count : buffer.Length), cancellationToken).AsTask();
public static Task WriteAsync(this Stream stream, ArraySegment<byte> buffer, CancellationToken cancellationToken = default)
=> stream.WriteAsync(buffer.AsMemory(), cancellationToken).AsTask();
#endif
#endregion
#region Send HTTP requests
internal static string[] UserAgents { get; } = new[]
{
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"SAMSUNG-SGH-E250/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 UP.Browser/6.2.3.3.c.1.101 (GUI) MMP/2.0 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Google (+https://developers.google.com/+/web/snippet/)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (compatible; Bingbot/2.0; +http://www.bing.com/bingbot.htm)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (compatible; Yahoo! Slurp; +http://help.yahoo.com/help/us/ysearch/slurp)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"DuckDuckBot/1.0; (+http://duckduckgo.com/duckduckbot.html)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"Mozilla/5.0 (compatible; Exabot/3.0; +http://www.exabot.com/go/robot)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"ia_archiver (+http://www.alexa.com/site/help/webmasters; crawler@alexa.com)",
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
};
/// <summary>
/// Gets an user-agent as spider-bot
/// </summary>
public static string SpiderUserAgent => UtilityService.UserAgents[UtilityService.GetRandomNumber(0, UtilityService.UserAgents.Length - 1)];
/// <summary>
/// Gets an user-agent as mobile browser
/// </summary>
public static string MobileUserAgent => "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1.1 Mobile/15E148 Safari/604.1 QNGX/10.9";
/// <summary>
/// Gets an user-agent as desktop browser
/// </summary>
public static string DesktopUserAgent => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1.1 Safari/605.1.15 QNGX/10.9";
/// <summary>
/// Gets the web proxy
/// </summary>
/// <param name="uri"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="bypass"></param>
/// <returns></returns>
public static WebProxy GetWebProxy(Uri uri, string username, string password, IEnumerable<string> bypass = null)
=> uri != null
? new WebProxy(uri, true, bypass?.ToArray(), !string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password) ? new CredentialCache { { uri, "Basic", new NetworkCredential(username, password) } } : null)
: null;
/// <summary>
/// Gets the web proxy
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="bypass"></param>
/// <returns></returns>
public static WebProxy GetWebProxy(string host, int port, string username, string password, IEnumerable<string> bypass = null)
=> UtilityService.GetWebProxy(string.IsNullOrWhiteSpace(host) ? null : new Uri($"{(!host.IsStartsWith("http://") && !host.IsStartsWith("https://") ? "http://" : "")}{host}:{port}"), username, password, bypass);
/// <summary>
/// Gets the pre-configurated web proxy
/// </summary>
public static WebProxy Proxy { get; private set; }
/// <summary>
/// Assigns the web-proxy
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="bypass"></param>
/// <returns></returns>
public static WebProxy AssignWebProxy(string host, int port, string username, string password, IEnumerable<string> bypass = null)
=> UtilityService.Proxy ?? (UtilityService.Proxy = UtilityService.GetWebProxy(host, port, username, password, bypass));
/// <summary>
/// Converts the collection of cookies to a string for using in HTTP headers
/// </summary>
/// <param name="cookies"></param>
/// <returns></returns>
public static string GetHttpCookies(this IEnumerable<Cookie> cookies)
=> cookies.Select(cookie => $"{cookie.Name}={cookie.Value?.UrlEncode()}; path={cookie.Path ?? "/"}; domain={cookie.Domain ?? "*"}; expires={(cookie.Expired ? "-1" : cookie.Expires.ToHttpString())};{(cookie.Secure ? " secure;" : "")}{(cookie.HttpOnly ? " httponly;" : "")}").Join(",");
/// <summary>
/// Converts the collection of cookies to a string for using in HTTP headers
/// </summary>
/// <param name="cookies"></param>
/// <returns></returns>
public static string GetHttpCookies(this CookieCollection cookies)
=> cookies.ToList().GetHttpCookies();
/// <summary>
/// Converts the HTTP cookies string to a collection of cookies
/// </summary>
/// <param name="httpCookies"></param>
/// <param name="domain"></param>
/// <param name="onAdd"></param>
/// <returns></returns>
public static CookieCollection GetCookies(this IEnumerable<string> httpCookies, string domain, Action<Cookie> onAdd = null)
{
var index = 0;
var strCookies = (httpCookies ?? new List<string>()).ToList();
while (index < strCookies.Count)
{
if (strCookies[index].IsContains("expires=") && !strCookies[index].IsContains(","))
{
strCookies[index] = $"{strCookies[index]}, {strCookies[index + 1]}";
strCookies.RemoveAt(index + 1);
}
index++;
}
var cookies = new CookieCollection();
strCookies.ForEach(value =>
{
var cookie = new Cookie();
var parts = value.ToList(";");
for (index = 0; index < parts.Count; index++)
{
if (index == 0 && parts[index] != string.Empty)
{
var pos = parts[index].IndexOf("=");
cookie.Name = parts[index].Left(pos);
cookie.Value = parts[index].Right(parts[index].Length - pos - 1);
}
else if (parts[index].IsContains("domain="))
{
var values = parts[index].ToList("=");
if (!string.IsNullOrWhiteSpace(values[1]))
cookie.Domain = values[1];
}
else if (parts[index].IsContains("path="))
{
var values = parts[index].ToList("=");
if (!string.IsNullOrWhiteSpace(values[1]))
cookie.Path = values[1];
}
else if (parts[index].IsContains("expires="))
try
{
var values = parts[index].ToList("=");
if (!string.IsNullOrWhiteSpace(values[1]))
cookie.Expires = values[1].FromHttpDateTime(true);
}
catch { }
else if (parts[index].IsContains("secure"))
cookie.Secure = true;
else if (parts[index].IsContains("httponly"))
cookie.HttpOnly = true;
}
cookie.Domain = string.IsNullOrWhiteSpace(cookie.Domain) ? domain : cookie.Domain;
cookie.Path = string.IsNullOrWhiteSpace(cookie.Path) ? "/" : cookie.Path;
onAdd?.Invoke(cookie);
cookies.Add(cookie);
});
return cookies;
}
static CookieCollection GetCookies(this Dictionary<string, string> headers, string domain, Action<Cookie> onAdd)
=> headers.TryGetValue("Set-Cookie", out var cookies) && !string.IsNullOrWhiteSpace(cookies) ? cookies.ToList().GetCookies(domain, onAdd) : new CookieCollection();
/// <summary>
/// Gets the HTTP cookies
/// </summary>
/// <param name="response"></param>
/// <param name="onAdd"></param>
/// <returns></returns>
public static CookieCollection GetCookies(this HttpResponseMessage response, Action<Cookie> onAdd = null)
=> response.GetHeaders().GetCookies(response.RequestMessage.RequestUri.Host, onAdd);
/// <summary>
/// Gets the HTTP cookies
/// </summary>
/// <param name="exception"></param>
/// <param name="onAdd"></param>
/// <returns></returns>
public static CookieCollection GetCookies(this RemoteServerException exception, Action<Cookie> onAdd = null)
=> exception.Headers.GetCookies(exception.URI.Host, onAdd);
/// <summary>
/// Gets the HTTP headers
/// </summary>
/// <param name="response"></param>
/// <param name="excluded"></param>
/// <param name="onCompleted"></param>
/// <returns></returns>
public static Dictionary<string, string> GetHeaders(this HttpResponseMessage response, IEnumerable<string> excluded = null, Action<Dictionary<string, string>> onCompleted = null)
{
var headers = response.Content.Headers?.ToDictionary() ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
#if !NETSTANDARD2_0
response.TrailingHeaders?.ToDictionary().ForEach(kvp => headers[kvp.Key] = kvp.Value);
#endif
response.Headers?.ToDictionary().ForEach(kvp => headers[kvp.Key] = kvp.Value);
return headers.Copy(excluded, onCompleted);
}
/// <summary>
/// Copies this HTTP headers (dictionary)
/// </summary>
/// <param name="object"></param>
/// <param name="excluded"></param>
/// <param name="onCompleted"></param>
/// <returns></returns>
public static Dictionary<string, string> Copy(this Dictionary<string, string> @object, IEnumerable<string> excluded = null, Action<Dictionary<string, string>> onCompleted = null)
{
var dictionary = new Dictionary<string, string>(@object ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
excluded?.ForEach(name => dictionary.Remove(name));
onCompleted?.Invoke(dictionary);
return dictionary;
}
/// <summary>
/// Copies the response stream asynchronously
/// </summary>
/// <param name="response"></param>
/// <param name="stream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task CopyToAsync(this HttpResponseMessage response, Stream stream, CancellationToken cancellationToken = default)
=> response.Content.CopyToAsync(stream, cancellationToken);
/// <summary>
/// Reads the response stream asynchronously
/// </summary>
/// <param name="response"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<Stream> ReadAsStreamAsync(this HttpResponseMessage response, CancellationToken cancellationToken = default)
=> response.Content.ReadAsStreamAsync(cancellationToken);
/// <summary>
/// Reads the response stream asynchronously
/// </summary>
/// <param name="response"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<byte[]> ReadAsByteArrayAsync(this HttpResponseMessage response, CancellationToken cancellationToken = default)
=> response.Content.ReadAsByteArrayAsync(cancellationToken);
/// <summary>
/// Reads all characters from the response stream asynchronously and returns them as one string
/// </summary>
/// <param name="response"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<string> ReadAsStringAsync(this HttpResponseMessage response, CancellationToken cancellationToken = default)
{
var @string = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
return response.GetHeaders().TryGetValue("Content-Type", out var contentType) && contentType.IsStartsWith("text/html") ? @string?.HtmlDecode() : @string;
}
/// <summary>
/// Sends a request to a remote end-point
/// </summary>
/// <param name="uri">The URI to perform request to</param>
/// <param name="method">The HTTP verb to perform request</param>
/// <param name="headers">The requesting headers</param>
/// <param name="body">The requesting body</param>
/// <param name="timeout">The requesting timeout (in seconds)</param>
/// <param name="credential">The credential for sending the request</param>
/// <param name="proxy">The proxy for sending the request</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="multipartFilename">The name of the file that presents by the body stream</param>
/// <returns></returns>
public static async Task<HttpResponseMessage> SendHttpRequestAsync(this Uri uri, string method, Dictionary<string, string> headers, object body, int timeout, NetworkCredential credential, IWebProxy proxy, CancellationToken cancellationToken, string multipartFilename = null)
{
if (string.IsNullOrWhiteSpace(uri?.AbsoluteUri))
throw new InformationRequiredException("The URI is invalid");
headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
using (var request = new HttpRequestMessage(new HttpMethod(string.IsNullOrWhiteSpace(method) ? "GET" : method.ToUpper()), uri))
{
headers.Copy(new[] { "Accept-Encoding", "Connection", "Content-Type", "Cookie", "Host", "AllowAutoRedirect" }).ForEach(kvp =>
{
try
{
request.Headers.Add(kvp.Key, kvp.Value?.AsciiEncode());
}
catch { }
});
if (!headers.ContainsKey("User-Agent"))
request.Headers.Add("User-Agent", UtilityService.DesktopUserAgent);
if (!headers.ContainsKey("Accept"))
request.Headers.Add("Accept", string.IsNullOrWhiteSpace(multipartFilename) ? "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" : "application/json,text/plain,*/*");
if (!headers.ContainsKey("Accept-Language"))
request.Headers.Add("Accept-Language", "en-US,en;q=0.9,vi;q=0.8");
#if NETSTANDARD2_0
request.Headers.Add("Accept-Encoding", "deflate, gzip");
if (body != null && (request.Method.Equals(HttpMethod.Post) || request.Method.Equals(HttpMethod.Put)))
#else
request.Headers.Add("Accept-Encoding", "deflate, gzip, br");
if (body != null && (request.Method.Equals(HttpMethod.Post) || request.Method.Equals(HttpMethod.Put) || request.Method.Equals(HttpMethod.Patch)))
#endif
{
if (body is string @string)
request.Content = new StringContent(@string);
else if (body is byte[] bytes)
request.Content = new ByteArrayContent(bytes);
else if (body is ArraySegment<byte> array)
request.Content = new ByteArrayContent(array.ToBytes());
else if (body is Stream stream)
{
if (string.IsNullOrWhiteSpace(multipartFilename))
request.Content = new StreamContent(stream);
else
{
request.Content = new MultipartFormDataContent($"vieapps-ngx---{UtilityService.GetRandomNumber()}-----");
request.Content.Headers.ContentType.CharSet = "utf-8";
(request.Content as MultipartFormDataContent).Add(new StreamContent(stream), "files", multipartFilename);
}
}
else
throw new InvalidRequestException("Body is invalid");
if (string.IsNullOrWhiteSpace(multipartFilename))
{
if (!headers.TryGetValue("Content-Type", out var contenType) || string.IsNullOrWhiteSpace(contenType))
contenType = "application/octet-stream; charset=utf-8";
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contenType);
}
}
using (var handler = new HttpClientHandler { UseCookies = true })
{
if (headers.TryGetValue("Cookie", out var cookies))
{
handler.CookieContainer = new CookieContainer();
handler.CookieContainer.Add(new Uri($"{uri.Scheme}://{uri.Host}"), cookies.ToList().GetCookies(uri.Host));
}
if (credential != null)
{
handler.PreAuthenticate = true;
handler.UseDefaultCredentials = false;
handler.Credentials = credential;
}
proxy = proxy ?? UtilityService.Proxy;
if (proxy != null)
{
handler.Proxy = proxy;
handler.UseProxy = true;
}
handler.AllowAutoRedirect = headers.TryGetValue("AllowAutoRedirect", out var allowAutoRedirect) && "true".IsEquals(allowAutoRedirect);
handler.ServerCertificateCustomValidationCallback = (requestMsg, certificate, chain, sslPolicyErrors) => true;
#if NETSTANDARD2_0
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
#else
handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.Brotli;
#endif
using (var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(timeout) })
try
{
var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
var heads = response.GetHeaders();
var isMoved = response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Redirect;
var isNotModified = response.StatusCode == HttpStatusCode.NotModified;
var exception = isMoved
? new RemoteServerMovedException(response.StatusCode, request.Method.ToString(), uri, heads, $"Resource on the remote server was moved [{(heads.TryGetValue("Location", out var url) && !string.IsNullOrWhiteSpace(url) ? new Uri((url.IsContains("://") ? "" : $"{uri.Scheme}://{uri.Host}") + url) : uri)}]")
: new RemoteServerException(response.StatusCode, isNotModified, request.Method.ToString(), uri, heads);
if (!isMoved && !isNotModified)
try
{
exception.Body = await response.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
exception.Body = string.IsNullOrWhiteSpace(exception.Body) ? null : exception.Body;
}
catch { }
response.Dispose();
throw exception;
}
return response;
}
catch (TaskCanceledException ex)
{