-
Notifications
You must be signed in to change notification settings - Fork 1
/
Helpers.cs
2655 lines (2379 loc) · 117 KB
/
Helpers.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
using Aerospike.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using Aerospike.Database.LINQPadDriver;
using System.Globalization;
using Newtonsoft.Json.Linq;
using Aerospike.Database.LINQPadDriver.Extensions;
using LPEDC = LINQPad.Extensibility.DataContext;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;
namespace Aerospike.Client
{
/// <summary>
/// Instructs the Aerospike LinqPad Driver to use this name for the bin instead of the field/property name.
/// </summary>
/// <seealso cref="ConstructorAttribute"/>
/// <seealso cref="BinIgnoreAttribute"/>
/// <seealso cref="PrimaryKeyAttribute"/>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class BinNameAttribute : Attribute
{
public BinNameAttribute(string name)
{
this.Name = name;
}
public string Name { get; set; }
public string PropertyName { get => this.Name; set => this.Name = value; }
}
/// <summary>
/// Instructs the Serializer to use the specified constructor when deserializing that object.
/// </summary>
/// <seealso cref="BinNameAttribute"/>
/// <seealso cref="BinIgnoreAttribute"/>
/// <seealso cref="PrimaryKeyAttribute"/>
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class ConstructorAttribute : Attribute
{
}
/// <summary>
/// Instructs the Aerospike LinqPad Driver not to serialize/deserialize the field/property value.
/// </summary>
/// <seealso cref="ConstructorAttribute"/>
/// <seealso cref="BinNameAttribute"/>
/// <seealso cref="PrimaryKeyAttribute"/>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class BinIgnoreAttribute : Attribute
{
}
/// <summary>
/// Instructs the Aerospike LinqPad Driver that this field/property is the Primary Key.
/// </summary>
/// <seealso cref="ConstructorAttribute"/>
/// <seealso cref="BinNameAttribute"/>
/// <seealso cref="BinIgnoreAttribute"/>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class PrimaryKeyAttribute : Attribute
{
}
public static class LPDHelpers
{
/// <summary>
/// Copies <see cref="ARecord"/>'s from the <paramref name="source"/> to <paramref name="targetSet"/>.
/// Note that if the namespace and/or set is different, this instances's values are used, except
/// in the case where the primary key is a digest. In these cases, an <see cref="InvalidOperationException"/> is thrown but the PK can be changed with <paramref name="newPrimaryKeyValue"/>.
/// </summary>
/// <param name="source">
/// The collection of records that will be copied
/// </param>
/// <param name="targetSet">
/// The targeted Set where the records will be copied too.
/// </param>
/// <param name="newPrimaryKeyValue">
/// Each record is passed as the first argument, and the return is the new primary key for that record.
/// Note: it is possible to change any of the record's bin values via the <see cref="ARecord.SetValue(string, object, bool)"/> method,
/// but this would change the original record.
/// </param>
/// <param name="writePolity">
/// The Aerospike Write Policy.
/// </param>
/// <param name="parallelOptions">
/// The <see cref="ParallelOptions"/> used to perform the copy operation.
/// </param>
/// <returns>
/// Returns the Set passed in with <paramref name="targetSet"/>
/// </returns>
/// <exception cref="InvalidOperationException">
/// If the record's primary key is a digest (not an actual value). This exception will be thrown,
/// since a digest has the namespace and set of where this record was retrieved from.
/// </exception>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, ANamespaceAccess, string, WritePolicy, ParallelOptions)"/>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, SetRecords, WritePolicy, ParallelOptions)"/>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, ANamespaceAccess, string, Func{ARecord, dynamic}, WritePolicy, ParallelOptions)"/>
public static SetRecords CopyRecords([NotNull] this IEnumerable<ARecord> source,
[NotNull] SetRecords targetSet,
Func<ARecord, dynamic> newPrimaryKeyValue,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
=> CopyRecords<ARecord>(source, targetSet, newPrimaryKeyValue, writePolity, parallelOptions);
public static SetRecords CopyRecords<S>([NotNull] IEnumerable<S> source,
[NotNull] SetRecords targetSet,
Func<S, dynamic> newPrimaryKeyValue,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
where S : ARecord
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(targetSet);
parallelOptions ??= new ParallelOptions();
Parallel.ForEach(source, parallelOptions, record =>
{
var newPK = newPrimaryKeyValue(record);
targetSet.Put(newPK,
record.ToDictionary(),
writePolity,
record.Aerospike.TTL);
});
return targetSet;
}
/// <summary>
/// Copies <see cref="ARecord"/>'s from the <paramref name="source"/> to <paramref name="targetSetName"/> in <paramref name="targetNamespace"/>.
/// Note that if the namespace and/or set is different, this instances's values are used, except
/// in the case where the primary key is a digest. In these cases, an <see cref="InvalidOperationException"/> is thrown but the PK can be changed with <paramref name="newPrimaryKeyValue"/>
/// </summary>
/// <param name="source">
/// The collection of records that will be copied
/// </param>
/// <param name="targetNamespace">
/// The Namespace that will be the target of the record copy.
/// </param>
/// <param name="targetSetName">
/// The targeted Set where the records will be copied too.
/// This can be a new set within the namespace.
/// This can be null, in which case the records are copied to the 'null' set.
/// </param>
/// <param name="newPrimaryKeyValue">
/// Each record is passed as the first argument, and the return is the new primary key for that record.
/// Note: it is possible to change any of the record's bin values via the <see cref="ARecord.SetValue(string, object, bool)"/> method,
/// but this would change the original record.
/// </param>
/// <param name="writePolity">
/// The Aerospike Write Policy.
/// </param>
/// <param name="parallelOptions">
/// The <see cref="ParallelOptions"/> used to perform the copy operation.
/// </param>
/// <returns>
/// Returns the Set instance that was the target set or null to indicated that a <see cref="ANamespaceAccess.RefreshExplorer"/> is required.
/// </returns>
/// <exception cref="InvalidOperationException">
/// If the record's primary key is a digest (not an actual value). This exception will be thrown,
/// since a digest has the namespace and set of where this record was retrieved from.
/// </exception>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, SetRecords, WritePolicy, ParallelOptions)"/>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, SetRecords, Func{ARecord, dynamic}, WritePolicy, ParallelOptions)"/>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, ANamespaceAccess, string, WritePolicy, ParallelOptions)"/>
public static SetRecords CopyRecords([NotNull] this IEnumerable<ARecord> source,
[NotNull] ANamespaceAccess targetNamespace,
string targetSetName,
Func<ARecord, dynamic> newPrimaryKeyValue,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
=> CopyRecords<ARecord>(source, targetNamespace, targetSetName, newPrimaryKeyValue, writePolity, parallelOptions);
public static SetRecords CopyRecords<T>([NotNull] IEnumerable<T> source,
[NotNull] ANamespaceAccess targetNamespace,
string targetSetName,
Func<T, dynamic> newPrimaryKeyValue,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
where T : ARecord
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(targetNamespace);
parallelOptions ??= new ParallelOptions();
Parallel.ForEach(source, parallelOptions, record =>
{
var newPK = newPrimaryKeyValue(record);
targetNamespace.Put(targetSetName,
newPK,
record.ToDictionary(),
writePolity,
record.Aerospike.TTL);
});
return targetNamespace.Sets.FirstOrDefault(s => s.SetName == targetSetName);
}
/// <summary>
/// Copies <see cref="ARecord"/>'s from the <paramref name="source"/> to <paramref name="targetSet"/>.
/// Note that if the namespace and/or set is different, this instances's values are used, except
/// in the case where the primary key is a digest. In these cases, an <see cref="InvalidOperationException"/> is thrown.
/// </summary>
/// <param name="source">
/// The collection of records that will be copied
/// </param>
/// <param name="targetSet">
/// The targeted Set where the records will be copied too.
/// </param>
/// <param name="writePolity">
/// The Aerospike Write Policy.
/// </param>
/// <param name="parallelOptions">
/// The <see cref="ParallelOptions"/> used to perform the copy operation.
/// </param>
/// <returns>
/// Returns the Set passed in with <paramref name="targetSet"/>
/// </returns>
/// <exception cref="InvalidOperationException">
/// If the record's primary key is a digest (not an actual value). This exception will be thrown,
/// since a digest has the namespace and set of where this record was retrieved from.
/// </exception>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, ANamespaceAccess, string, WritePolicy, ParallelOptions)"/>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, SetRecords, Func{ARecord, dynamic}, WritePolicy, ParallelOptions)"/>
public static SetRecords CopyRecords([NotNull] this IEnumerable<ARecord> source,
[NotNull] SetRecords targetSet,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
=> CopyRecords<ARecord>(source, targetSet, writePolity, parallelOptions);
public static SetRecords CopyRecords<S>([NotNull] IEnumerable<S> source,
[NotNull] SetRecords targetSet,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
where S : ARecord
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(targetSet);
parallelOptions ??= new ParallelOptions();
Parallel.ForEach(source, parallelOptions, record =>
{
targetSet.Put(record, writePolicy: writePolity);
});
return targetSet;
}
/// <summary>
/// Copies <see cref="ARecord"/>'s from the <paramref name="source"/> to <paramref name="targetSetName"/> in <paramref name="targetNamespace"/>.
/// Note that if the namespace and/or set is different, this instances's values are used, except
/// in the case where the primary key is a digest. In these cases, an <see cref="InvalidOperationException"/> is thrown.
/// </summary>
/// <param name="source">
/// The collection of records that will be copied
/// </param>
/// <param name="targetNamespace">
/// The Namespace that will be the target of the record copy.
/// </param>
/// <param name="targetSetName">
/// The targeted Set where the records will be copied too.
/// This can be a new set within the namespace.
/// This can be null, in which case the records are copied to the 'null' set.
/// </param>
/// <param name="writePolity">
/// The Aerospike Write Policy.
/// </param>
/// <param name="parallelOptions">
/// The <see cref="ParallelOptions"/> used to perform the copy operation.
/// </param>
/// <returns>
/// Returns the Set instance that was the target set or null to indicated that a <see cref="ANamespaceAccess.RefreshExplorer"/> is required.
/// </returns>
/// <exception cref="InvalidOperationException">
/// If the record's primary key is a digest (not an actual value). This exception will be thrown,
/// since a digest has the namespace and set of where this record was retrieved from.
/// </exception>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, SetRecords, WritePolicy, ParallelOptions)"/>
/// <seealso cref="CopyRecords(IEnumerable{ARecord}, ANamespaceAccess, string, Func{ARecord, dynamic}, WritePolicy, ParallelOptions)"/>
public static SetRecords CopyRecords([NotNull] this IEnumerable<ARecord> source,
[NotNull] ANamespaceAccess targetNamespace,
string targetSetName,
WritePolicy writePolity = null,
ParallelOptions parallelOptions = null)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(targetNamespace);
parallelOptions ??= new ParallelOptions();
Parallel.ForEach(source, parallelOptions, record =>
{
targetNamespace.Put(record,
setName: targetSetName,
writePolicy: writePolity);
});
return targetNamespace.Sets.FirstOrDefault(s => s.SetName == targetSetName);
}
/// <summary>
/// Returns a collection of <see cref="Aerospike.Client.Record"/> from an <see cref="Aerospike.Client.RecordSet"/>.
/// </summary>
/// <param name="recordSet">
/// An <see cref="Aerospike.Client.RecordSet"/>
/// </param>
/// <returns>
/// A collection of <see cref="Aerospike.Client.Record"/>
/// </returns>
/// <exception cref="NullReferenceException">
/// Thrown if <paramref name="recordSet"/> is null.
/// </exception>
public static IEnumerable<Record> AsEnumerable(this RecordSet recordSet)
{
while (recordSet.Next())
{
yield return recordSet.Record;
}
}
/// <summary>
/// Casts a <see cref="Aerospike.Client.Bin"/>'s value into <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">
/// Data type that the Value will try to be cast too.
/// </typeparam>
/// <param name="bin">
/// The <see cref="Aerospike.Client.Bin"/>
/// </param>
/// <returns>
/// The value casted to <typeparamref name="T"/> or an exception.
/// </returns>
/// <exception cref="InvalidCastException">
/// If the value cannot be casted.
/// </exception>
public static T Cast<T>(this Bin bin) => (T) Helpers.CastToNativeType(bin.name, typeof(T), bin.name, bin.value.Object);
/// <summary>
/// Casts a <see cref="Aerospike.Client.Value"/>'s value into <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">
/// Data type that the Value will try to be cast too.
/// </typeparam>
/// <param name="value">
/// The <see cref="Aerospike.Client.Value"/>
/// </param>
/// <returns>
/// The value casted to <typeparamref name="T"/> or an exception.
/// </returns>
/// <exception cref="InvalidCastException">
/// If the value cannot be casted.
/// </exception>
public static T Cast<T>(this Value value) => value is null ? default : (T) Helpers.CastToNativeType("Value", typeof(T), "Value", value.Object);
public static JArray ToJArray(this IEnumerable<JsonDocument> documents) => new JArray(documents.Cast<JObject>());
public static JsonDocument ToJsonDocument(this IDictionary<string,object> document) => new JsonDocument(document);
/// <summary>
/// This will convert a list of <see cref="JObject"/> to a list of dictionary items.
/// </summary>
/// <param name="documentLst">A list of JSON documents/JObjects</param>
/// <returns>
/// a list of dictionary items.
/// </returns>
public static IEnumerable<IDictionary<string,object>> ToCDT(this IEnumerable<JObject> documentLst)
{
foreach(var document in documentLst)
{
yield return CDTConverter.ConvertToDictionary(document);
}
}
/// <summary>
/// This will convert a list of <see cref="JsonDocument"/> to a list of dictionary items.
/// </summary>
/// <param name="documentLst">A list of JSON documents/JObjects</param>
/// <returns>
/// a list of dictionary items.
/// </returns>
public static IEnumerable<IDictionary<string, object>> ToCDT(this IEnumerable<JsonDocument> documentLst)
{
foreach (var document in documentLst)
{
yield return document.ToDictionary();
}
}
/// <summary>
/// Converts a .Net object into an Aerospike <see cref="Value"/>, if possible.
/// </summary>
/// <param name="value">A .Net object.</param>
/// <returns>
/// An Aerospike <see cref="Value"/> instance.
/// </returns>
public static Client.Value ToAerospikeValue(this object value) => Client.Value.Get(Helpers.ConvertToAerospikeType(value));
public static Client.Exp ToAerospikeExpression(this object value)
=> Helpers.ConvertToAerospikeType(value) switch
{
byte[] castedObj => Exp.Val(castedObj),
IList castedObj => Exp.Val(castedObj),
IDictionary castedObj => Exp.Val(castedObj, MapOrder.UNORDERED),
string castedObj => Exp.Val(castedObj),
int castedObj => Exp.Val(castedObj),
long castedObj => Exp.Val(castedObj),
bool castedObj => Exp.Val(castedObj),
Enum castedObj => Exp.Val(Convert.ToInt32(castedObj)),
byte castedObj => Exp.Val(castedObj),
sbyte castedObj => Exp.Val(castedObj),
short castedObj => Exp.Val(castedObj),
uint castedObj => Exp.Val(castedObj),
ulong castedObj => Exp.Val(castedObj),
ushort castedObj => Exp.Val(castedObj),
null => Exp.Nil(),
_ => throw new ArgumentException($"Object type is not supported in Aerospike: {value.GetType()}"),
};
/// <summary>
/// Converts a date/time to Unix Epoch nanosecond value
/// </summary>
/// <param name="dateTime">Date time to convert</param>
/// <returns>
/// Unix Epoch time in nanoseconds
/// </returns>
public static long ToUnixEpochNS(this DateTime dateTime) => Helpers.NanosFromEpoch(dateTime);
/// <summary>
/// Converts a date/time offset to Unix Epoch nanosecond value
/// </summary>
/// <param name="dateTimeOffset">Date time offset to convert</param>
/// <returns>
/// Unix Epoch time in nanoseconds
/// </returns>
public static long ToUnixEpochNS(this DateTimeOffset dateTimeOffset) => Helpers.NanosFromEpoch(dateTimeOffset.UtcDateTime);
/// <summary>
/// Converts a Unix Epoch nanoseconds value to a date time value.
/// </summary>
/// <param name="unixEpoch">Unix Epoch in nanoseconds</param>
/// <returns>Date time value</returns>
public static DateTime FromUnixEpochNS(this long unixEpoch) => Helpers.NanoEpochToDateTime(unixEpoch);
}
}
namespace Aerospike.Database.LINQPadDriver
{
public static partial class Helpers
{
public static bool IsPrivateAddress(string ipAddress)
{
if(string.IsNullOrEmpty(ipAddress)
|| ipAddress.ToLower() == "localhost"
|| ipAddress.ToLower() == "local")
return true;
try
{
int[] ipParts = ipAddress.Split('.', StringSplitOptions.RemoveEmptyEntries)
.Select(s => int.Parse(s)).ToArray();
// in private ip range
if(ipParts[0] == 10 || ipParts[0] == 127 ||
(ipParts[0] == 192 && ipParts[1] == 168) ||
(ipParts[0] == 172 && (ipParts[1] >= 16 && ipParts[1] <= 31)))
{
return true;
}
}
catch { return false; }
// IP Address is probably public.
// This doesn't catch some VPN ranges like OpenVPN and Hamachi.
return false;
}
/// <summary>
/// Checks to see if <paramref name="interfaceClass"/> is a subclass of <paramref name="classToCheck"/>.
/// If the types are generic, the underlying types are ignored.
/// </summary>
/// <param name="interfaceClass"></param>
/// <param name="classToCheck"></param>
/// <returns></returns>
public static bool IsSubclassOfInterface(Type interfaceClass, Type classToCheck)
{
if(interfaceClass is null || classToCheck is null) return false;
if(ReferenceEquals(interfaceClass, classToCheck)) return true;
if(classToCheck.IsGenericType)
{
if(!classToCheck.IsGenericTypeDefinition)
classToCheck = classToCheck.GetGenericTypeDefinition();
}
if(interfaceClass.IsGenericType)
{
if(!interfaceClass.IsGenericTypeDefinition)
interfaceClass = interfaceClass.GetGenericTypeDefinition();
}
if(ReferenceEquals(interfaceClass, classToCheck)) return true;
return classToCheck.GetInterfaces().Any(ctc => IsSubclassOfInterface(interfaceClass, ctc));
}
public static string CheckName(string name, string contextType)
{
var changeList = new char[] { '.', ' ', '[', ']', '(', ')', '+', '-', '=', '^', '*', '/', '\\', ',', '<', '>', ';', ':', '@', '#', '!', '%', '&', '?', '~', '`', '$', '"', '\'' };
StringBuilder newName = new StringBuilder();
foreach(char c in name)
{
if(changeList.Contains(c))
{
newName.Append('_');
}
else
newName.Append(c);
}
var newStr = newName.ToString();
if(Char.IsDigit(newStr.FirstOrDefault()))
newStr = contextType + newStr;
if(LPEDC.DataContextDriver.IsCSharpKeyword(newStr))
{
return newStr + '_' + contextType;
}
return newStr;
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach(byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
#if NET7_0_OR_GREATER
[GeneratedRegex("(?<namespace>[^.]+)+",
RegexOptions.Compiled)]
static private partial Regex NamespaceRegEx();
#else
static readonly Regex namespaceRegEx = new Regex("(?<namespace>[^.]+)+",
RegexOptions.Compiled);
static private Regex NamespaceRegEx() => namespaceRegEx;
#endif
public static string GetRealTypeName(Type t, bool makeIntoNullable = false, bool includeNameSpace = false)
{
if(t == null) return null;
string ns = null;
if(includeNameSpace)
{
var parts = NamespaceRegEx().Matches(t.FullName);
ns = string.Join(',', parts.SkipLast(1).Select(a => a.Value));
}
static string GetDeclaringClass(Type currentType)
{
if(currentType.IsGenericParameter)
return "{PARAM}";
var declaringTpe = currentType.DeclaringType;
return declaringTpe is null
? currentType.Name
: GetRealTypeName(declaringTpe, false, false) + '.' + currentType.Name;
}
if(!t.IsGenericType)
{
string className = GetDeclaringClass(t);
if(!string.IsNullOrWhiteSpace(ns))
className = ns + "." + className;
return makeIntoNullable && t.IsValueType
? $"Nullable<{className}>"
: className;
}
StringBuilder sb = new StringBuilder();
var genericName = GetDeclaringClass(t);
var paramCnt = genericName.Count(c => c == '{');
var paramIdx = genericName.IndexOf('}');
var genericFnd = genericName.Contains('`');
bool appendComma = false;
if(!string.IsNullOrEmpty(ns))
sb.Append(ns);
if(genericFnd)
{
sb.Append(genericName.AsSpan(0, genericName.IndexOf('`')));
sb.Append('<');
appendComma = false;
}
else
{
sb.Append(genericName);
appendComma = true;
}
foreach(Type arg in t.GetGenericArguments())
{
var genericArg = GetRealTypeName(arg, makeIntoNullable, includeNameSpace);
if(paramCnt-- > 0)
{
sb.Replace("{PARAM}", genericArg, 0, paramIdx + 1);
paramIdx = genericName.IndexOf('}', paramIdx + 1);
}
else
{
if(appendComma) sb.Append(',');
sb.Append(genericArg);
appendComma = true;
}
}
if(genericFnd)
sb.Append('>');
return makeIntoNullable && t.IsValueType
? $"Nullable<{sb}>"
: sb.ToString();
}
private static string GetBinNameFromProperty(PropertyInfo property)
{
if(Attribute.IsDefined(property, typeof(BinIgnoreAttribute)))
return null;
string binName;
if(Attribute.IsDefined(property, typeof(BinNameAttribute)))
{
binName = ((BinNameAttribute) Attribute.GetCustomAttribute(property, typeof(BinNameAttribute), false))
?.Name
?? property.Name;
}
else
binName = property.Name;
return binName;
}
private static string GetBinNameFromField(FieldInfo field)
{
if(Attribute.IsDefined(field, typeof(BinIgnoreAttribute)))
return null;
string binName;
if(Attribute.IsDefined(field, typeof(BinNameAttribute)))
{
binName = ((BinNameAttribute) Attribute.GetCustomAttribute(field, typeof(BinNameAttribute), false))
?.Name
?? field.Name;
}
else
binName = field.Name;
return binName;
}
private static ConstructorInfo GetConstructorInfo(Type type)
{
var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
ConstructorInfo constructor = null;
if(constructors.Length > 0)
{
if(constructors.Length == 1 && constructors.First().GetParameters().Length == 0)
{
return null;
}
bool hasDefault = false;
foreach(var item in constructors)
{
if(item.CustomAttributes.Any(a => a.AttributeType == typeof(ConstructorAttribute)))
{
return item;
}
if(item.GetParameters().Length == 0)
{
hasDefault = true;
}
else
{
constructor = item;
}
}
if(hasDefault) return null;
}
return constructor;
}
public static T[] RemoveDups<T>(IEnumerable<T> items)
{
return items.GroupBy(g => g).Select(g => g.First()).ToArray();
}
public static bool SequenceEquals<T>(IEnumerable<T> items, object obj)
{
if(items is null) return obj is null;
if(ReferenceEquals(items, obj)) return true;
if(obj is IEnumerable<T> tItems) return items.SequenceEqual(tItems);
if(obj is JArray jArray)
{
return SequenceEquals(items, CDTConverter.ConvertToList(jArray));
}
if(obj is JObject jObject)
{
if(IsSubclassOfInterface(typeof(KeyValuePair<,>), typeof(T)))
return SequenceEquals(items,
CDTConverter.ConvertToDictionary(jObject));
return false;
}
if(obj is JProperty jProp)
{
if(IsSubclassOfInterface(typeof(KeyValuePair<,>), typeof(T)))
return SequenceEquals(items,
CDTConverter.ConvertToDictionary(jProp));
return false;
}
if(obj is IEnumerable iobj)
{
return items.Cast<object>().SequenceEqual(iobj.Cast<object>());
}
return false;
}
public static bool IsAerospikeType(Type type)
{
return type.IsPrimitive
|| type == typeof(string)
|| type.IsSubclassOf(typeof(Client.Value));
}
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
#if NET7_0_OR_GREATER
public static long NanosFromEpoch(DateTime dt) => (long) dt.ToUniversalTime().Subtract(UnixEpoch).TotalNanoseconds;
#else
public static long NanosFromEpoch(DateTime dt) => (long) dt.ToUniversalTime().Subtract(UnixEpoch).TotalMilliseconds * 1000000;
#endif
public static DateTime NanoEpochToDateTime(long nanoseconds) => UnixEpoch.AddTicks(nanoseconds / 100);
internal const string defaultDateTimeFormat = "yyyy-MM-ddTHH:mm:ss.ffff";
internal const string defaultDateTimeOffsetFormat = "yyyy-MM-ddTHH:mm:ss.ffffzzz";
internal const string defaultTimeSpanFormat = "c";
/// <summary>
/// Format used to serialize or deserialize a date to/from string
/// A null value will use the default format.
/// <see href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings"/>
/// </summary>
public static string DateTimeFormat = defaultDateTimeFormat;
/// <summary>
/// Format used to serialize or deserialize a date offset to/from string
/// A null value will use the default format.
/// <see href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings"/>
/// </summary>
public static string DateTimeOffsetFormat = defaultDateTimeOffsetFormat;
/// <summary>
/// Format used to serialize or deserialize a time to/from string
/// A null value will use the default format.
/// <see href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings"/>
/// </summary>
public static string TimeSpanFormat = defaultTimeSpanFormat;
/// <summary>
/// A boolean, if true numeric values from the DB for targeted Date/Time data types are nanoseconds from Unix Epoch.
/// If false, the numeric value represents .net ticks.
/// <see cref="DateTime.DateTime(long)"/>
/// <see cref="DateTimeOffset.DateTimeOffset(long, TimeSpan)"/>
/// <see cref="Client.Exp.Val(DateTime)"/>
/// <see cref="AllDateTimeUseUnixEpochNano"/>
/// </summary>
public static bool UseUnixEpochNanoForNumericDateTime = true;
/// <summary>
/// All Date/Time values are converted to nanoseconds from Unix Epoch Date/Time.
/// </summary>
/// <see cref="UseUnixEpochNanoForNumericDateTime"/>
public static bool AllDateTimeUseUnixEpochNano = false;
public static object ConvertToAerospikeType(object putObject)
{
if(putObject == null)
return null;
if(!IsAerospikeType(putObject.GetType()))
{
if(putObject is ARecord aRecord)
{
putObject = ConvertToAerospikeType(aRecord.Aerospike.GetValues());
}
else if(putObject is AValue aValue)
{
putObject = ConvertToAerospikeType(aValue.Value);
}
else if(putObject is Aerospike.Client.Value asValue)
{
putObject = asValue.Object;
}
else if(putObject is Aerospike.Client.Bin asBin)
{
putObject = asBin.value?.Object;
}
else if(putObject is Decimal decValue)
{
putObject = (double) decValue;
}
else if(putObject is Enum enumValue)
{
putObject = putObject.ToString();
}
else if(putObject is DateTime dateTimeValue)
{
putObject = AllDateTimeUseUnixEpochNano
? (object) NanosFromEpoch(dateTimeValue)
: dateTimeValue.ToString(DateTimeFormat);
}
else if(putObject is DateTimeOffset dateTimeOffsetValue)
{
putObject = AllDateTimeUseUnixEpochNano
? (object) NanosFromEpoch(dateTimeOffsetValue.UtcDateTime)
: dateTimeOffsetValue.ToString(DateTimeOffsetFormat);
}
else if(putObject is TimeSpan timeSpanValue)
{
putObject = AllDateTimeUseUnixEpochNano
? (object) ((long) timeSpanValue.TotalMilliseconds * 1000000L)
: timeSpanValue.ToString(TimeSpanFormat);
}
else if(putObject is Guid guidValue)
{
putObject = guidValue.ToString();
}
else if(GeoJSONHelpers.IsGeoValue(putObject.GetType()))
{
return GeoJSONHelpers.ConvertFromGeoJson(putObject);
}
else if(putObject is JObject jObject)
{
return ConvertToAerospikeType(CDTConverter.ConvertToDictionary(jObject));
}
else if(putObject is JArray jArray)
{
return ConvertToAerospikeType(CDTConverter.ConvertToList(jArray));
}
else if(putObject is JProperty jProp)
{
return ConvertToAerospikeType(CDTConverter.ConvertToDictionary(jProp));
}
else if(putObject is JValue jValue)
{
return ConvertToAerospikeType(jValue.Value);
}
else if(putObject is IDictionary dictValue)
{
var genericTypes = dictValue.GetType().GetGenericArguments();
if(genericTypes.Length == 2
&& genericTypes[0] == typeof(string))
{
if(!IsAerospikeType(genericTypes[1]))
{
var newDict = new Dictionary<string, object>();
foreach(DictionaryEntry kvp in dictValue)
{
newDict.Add((string) kvp.Key,
ConvertToAerospikeType(kvp.Value));
}
putObject = newDict;
}
}
else if(genericTypes.Length == 0
|| !IsAerospikeType(genericTypes[0])
|| !IsAerospikeType(genericTypes[1]))
{
var kvps = dictValue.Keys
.Cast<object>()
.Select(key => ConvertToAerospikeType(key))
.Zip(dictValue.Values
.Cast<object>()
.Select(value => ConvertToAerospikeType(value)),
(k, v) => new KeyValuePair<object, object>(k, v));
putObject = new Dictionary<object, object>(kvps);
}
}
else if(putObject is byte[] byteArray)
{
putObject = byteArray;
}
else if(putObject is IEnumerable enumerableValue)
{
var genericTypes = enumerableValue.GetType().GetGenericArguments();
if(genericTypes.Length == 0 || !IsAerospikeType(genericTypes[0]))
{
var newList = new List<object>();
foreach(var item in enumerableValue)
{
newList.Add(ConvertToAerospikeType(item));
}
putObject = newList;
}
}
else
{
putObject = TransForm(putObject, nestedItem: true);
}
}
return putObject;
}
/// <summary>
/// Transform object into a Dictionary that can be used with generating a document or bins in Aerospike.
///
/// <see cref="Aerospike.Client.BinNameAttribute"/> -- defines the bin name, otherwise the kvPair name is used
/// <see cref="Aerospike.Client.BinIgnoreAttribute"/> -- will ignore this kvPair
/// </summary>
/// <param name="instance">Item being transformed</param>
/// <param name="transform">
/// A action that is called to perform customized transformation.
/// First argument -- the name of the kvPair
/// Second argument -- the name of the bin (can be different from kvPair if <see cref="Aerospike.Client.BinNameAttribute"/> is defined)
/// Third argument -- the instance being transformed
/// Fourth argument -- if true the instance is within another object.
/// Returns the new transformed object or null to indicate that this kvPair should be skipped.
/// </param>
/// <param name="nestedItem">Indicates if item was nested inside another object.</param>
/// <returns>
/// The Dictionary used to pass to Aerospike's put command.
/// </returns>
/// <seealso cref="Aerospike.Client.BinNameAttribute"/>
/// <seealso cref="Aerospike.Client.BinIgnoreAttribute"/>
/// <seealso cref="CreateBinRecord(object, string, Bin[])"/>
public static Dictionary<string, object> TransForm(object instance,
Func<string, string, object, bool, object> transform = null,
bool nestedItem = false)
{
var dictionary = new Dictionary<string, object>();
foreach(var property in instance.GetType().GetProperties())
{
string binName = GetBinNameFromProperty(property);
object putObject;
if(string.IsNullOrEmpty(binName)) continue;
if(transform == null)
{
putObject = property.GetValue(instance);
dictionary.Add(binName, ConvertToAerospikeType(putObject));
}