-
Notifications
You must be signed in to change notification settings - Fork 1
/
NoSqlHelper.cs
2478 lines (2287 loc) · 130 KB
/
NoSqlHelper.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.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using net.vieapps.Components.Utility;
#endregion
namespace net.vieapps.Components.Repository
{
/// <summary>
/// Collection of methods for working with NoSQL database (MongoDB)
/// </summary>
public static class NoSqlHelper
{
#region Client
internal static ConcurrentDictionary<string, IMongoClient> Clients { get; } = new ConcurrentDictionary<string, IMongoClient>();
internal static ConcurrentDictionary<int, bool> ReplicaSetClients { get; } = new ConcurrentDictionary<int, bool>();
/// <summary>
/// Checks to see client is connected to a ReplicaSet or not
/// </summary>
/// <param name="mongoClient"></param>
/// <returns></returns>
public static bool IsReplicaSet(this IMongoClient mongoClient)
{
if (NoSqlHelper.ReplicaSetClients.TryGetValue(mongoClient.GetHashCode(), out var status))
return status;
try
{
var statusDoc = mongoClient.GetDatabase("admin").RunCommand<BsonDocument>("{ replSetGetStatus: 1 }");
status = statusDoc.Contains("replSet");
}
catch
{
status = false;
}
NoSqlHelper.ReplicaSetClients.TryAdd(mongoClient.GetHashCode(), status);
return status;
}
/// <summary>
/// Checks to see client is connected to a ReplicaSet or not
/// </summary>
/// <param name="mongoClient"></param>
/// <returns></returns>
public static async Task<bool> IsReplicaSetAsync(this IMongoClient mongoClient, CancellationToken cancellationToken = default)
{
if (NoSqlHelper.ReplicaSetClients.TryGetValue(mongoClient.GetHashCode(), out var status))
return status;
try
{
var statusDoc = await mongoClient.GetDatabase("admin").RunCommandAsync<BsonDocument>("{ replSetGetStatus: 1 }", null, cancellationToken).ConfigureAwait(false);
status = statusDoc.Contains("replSet");
}
catch
{
status = false;
}
NoSqlHelper.ReplicaSetClients.TryAdd(mongoClient.GetHashCode(), status);
return status;
}
/// <summary>
/// Gets a client for working with MongoDB
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
public static IMongoClient GetClient(string connectionString)
{
if (string.IsNullOrWhiteSpace(connectionString))
return null;
var key = "MongoClient#" + connectionString.Trim().ToLower().GenerateUUID();
if (!NoSqlHelper.Clients.TryGetValue(key, out var client))
lock (NoSqlHelper.Clients)
{
if (!NoSqlHelper.Clients.TryGetValue(key, out client))
{
client = new MongoClient(connectionString);
NoSqlHelper.Clients.TryAdd(key, client);
}
}
return client;
}
#endregion
#region Database
/// <summary>
/// Gets a database of MongoDB
/// </summary>
/// <param name="mongoClient"></param>
/// <param name="databaseName"></param>
/// <param name="databaseSettings"></param>
/// <returns></returns>
public static IMongoDatabase GetDatabase(IMongoClient mongoClient, string databaseName, MongoDatabaseSettings databaseSettings = null)
=> !string.IsNullOrWhiteSpace(databaseName) && mongoClient != null
? mongoClient.GetDatabase(databaseName, databaseSettings)
: null;
internal static ConcurrentDictionary<string, IMongoDatabase> Databases { get; } = new ConcurrentDictionary<string, IMongoDatabase>();
/// <summary>
/// Gets a database of MongoDB
/// </summary>
/// <param name="connectionString"></param>
/// <param name="databaseName"></param>
/// <param name="databaseSettings"></param>
/// <returns></returns>
public static IMongoDatabase GetDatabase(string connectionString, string databaseName, MongoDatabaseSettings databaseSettings = null)
{
if (string.IsNullOrWhiteSpace(connectionString) || string.IsNullOrWhiteSpace(databaseName))
return null;
var key = databaseName.Trim() + "#" + connectionString.Trim().ToLower().GenerateUUID();
if (!NoSqlHelper.Databases.TryGetValue(key, out var database))
lock (NoSqlHelper.Databases)
{
if (!NoSqlHelper.Databases.TryGetValue(key, out database))
{
database = NoSqlHelper.GetDatabase(NoSqlHelper.GetClient(connectionString), databaseName, databaseSettings);
NoSqlHelper.Databases.TryAdd(key, database);
}
}
return database;
}
/// <summary>
/// Starts a client session of this database
/// </summary>
/// <param name="database"></param>
/// <param name="options"></param>
/// <returns></returns>
public static IClientSessionHandle StartSession(this IMongoDatabase database, ClientSessionOptions options = null)
=> database.Client.StartSession(options);
/// <summary>
/// Starts a client session of this database
/// </summary>
/// <param name="database"></param>
/// <param name="options"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<IClientSessionHandle> StartSessionAsync(this IMongoDatabase database, ClientSessionOptions options = null, CancellationToken cancellationToken = default)
=> database.Client.StartSessionAsync(options, cancellationToken);
/// <summary>
/// Checks to see database is belong to a client that is connected to a ReplicaSet or not
/// </summary>
/// <param name="database"></param>
/// <returns></returns>
public static bool IsReplicaSet(this IMongoDatabase database)
=> database.Client.IsReplicaSet();
/// <summary>
/// Checks to see database is belong to a client that is connected to a ReplicaSet or not
/// </summary>
/// <param name="database"></param>
/// <returns></returns>
public static Task<bool> IsReplicaSetAsync(this IMongoDatabase database, CancellationToken cancellationToken = default)
=> database.Client.IsReplicaSetAsync(cancellationToken);
#endregion
#region Collection
internal static ConcurrentDictionary<string, object> Collections { get; } = new ConcurrentDictionary<string, object>();
/// <summary>
/// Gets a collection of MongoDB
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mongoDatabase"></param>
/// <param name="collectionName"></param>
/// <param name="collectionSettings"></param>
/// <returns></returns>
public static IMongoCollection<T> GetCollection<T>(IMongoDatabase mongoDatabase, string collectionName, MongoCollectionSettings collectionSettings = null) where T : class
=> mongoDatabase != null && !string.IsNullOrWhiteSpace(collectionName)
? mongoDatabase.GetCollection<T>(collectionName, collectionSettings)
: null;
/// <summary>
/// Gets a collection of MongoDB
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connectionString"></param>
/// <param name="databaseName"></param>
/// <param name="collectionName"></param>
/// <param name="disableCache"></param>
/// <param name="databaseSettings"></param>
/// <param name="collectionSettings"></param>
/// <returns></returns>
public static IMongoCollection<T> GetCollection<T>(string connectionString, string databaseName, string collectionName, bool disableCache = false, MongoDatabaseSettings databaseSettings = null, MongoCollectionSettings collectionSettings = null) where T : class
{
if (string.IsNullOrWhiteSpace(connectionString) || string.IsNullOrWhiteSpace(databaseName) || string.IsNullOrWhiteSpace(collectionName))
return null;
if (disableCache)
return NoSqlHelper.GetCollection<T>(NoSqlHelper.GetDatabase(connectionString, databaseName, databaseSettings), collectionName, collectionSettings);
var key = collectionName.Trim() + "#" + (databaseName.Trim() + "#" + connectionString.Trim()).ToLower().GetMD5();
if (!NoSqlHelper.Collections.TryGetValue(key, out var collection))
lock (NoSqlHelper.Collections)
{
if (!NoSqlHelper.Collections.TryGetValue(key, out collection))
{
collection = NoSqlHelper.GetCollection<T>(NoSqlHelper.GetDatabase(connectionString, databaseName, databaseSettings), collectionName, collectionSettings);
NoSqlHelper.Collections.TryAdd(key, collection);
}
}
return collection as IMongoCollection<T>;
}
/// <summary>
/// Gets a collection in NoSQL database (MongoDB collection)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataSource">The data source</param>
/// <param name="entityDefinition">The entity definition</param>
/// <returns></returns>
public static IMongoCollection<T> GetCollection<T>(this DataSource dataSource, EntityDefinition entityDefinition) where T : class
=> NoSqlHelper.GetCollection<T>(RepositoryMediator.GetConnectionString(dataSource), dataSource.DatabaseName, entityDefinition.CollectionName);
/// <summary>
/// Gets a collection in NoSQL database (MongoDB collection)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataSource">The data source</param>
/// <returns></returns>
public static IMongoCollection<T> GetCollection<T>(this DataSource dataSource) where T : class
=> dataSource.GetCollection<T>(RepositoryMediator.GetEntityDefinition<T>());
/// <summary>
/// Gets a collection in NoSQL database (MongoDB collection)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <returns></returns>
public static IMongoCollection<T> GetCollection<T>(this RepositoryContext context, DataSource dataSource) where T : class
=> NoSqlHelper.GetCollection<T>(dataSource, context.EntityDefinition);
/// <summary>
/// Starts a client session of this collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="options"></param>
/// <returns></returns>
public static IClientSessionHandle StartSession<T>(this IMongoCollection<T> collection, ClientSessionOptions options = null) where T : class
=> collection.Database.StartSession(options);
/// <summary>
/// Starts a client session of this collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="options"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<IClientSessionHandle> StartSessionAsync<T>(this IMongoCollection<T> collection, ClientSessionOptions options = null, CancellationToken cancellationToken = default) where T : class
=> collection.Database.StartSessionAsync(options, cancellationToken);
/// <summary>
/// Starts a client session of this collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task<IClientSessionHandle> StartSessionAsync<T>(this IMongoCollection<T> collection, CancellationToken cancellationToken) where T : class
=> collection.Database.StartSessionAsync(null, cancellationToken);
/// <summary>
/// Checks to see collection is belong to a client that is connected to a ReplicaSet or not
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <returns></returns>
public static bool IsReplicaSet<T>(this IMongoCollection<T> collection)
=> collection.Database.IsReplicaSet();
/// <summary>
/// Checks to see collection is belong to a client that is connected to a ReplicaSet or not
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <returns></returns>
public static Task<bool> IsReplicaSetAsync<T>(this IMongoCollection<T> collection, CancellationToken cancellationToken = default)
=> collection.Database.IsReplicaSetAsync(cancellationToken);
#endregion
#region Helpers (filter, sort, projection, find fluent)
static string AllowDiskUse { get; } = UtilityService.GetAppSetting("Components:Repository:NoSql:AllowDiskUse", "true");
static string AllowPartialResults { get; } = UtilityService.GetAppSetting("Components:Repository:NoSql:AllowPartialResults");
static FilterDefinition<T> CreateFilterDefinition<T>(this string query) where T : class
{
var searchTerms = "";
var searchQuery = new SearchQuery(query);
searchQuery.AndWords.ForEach(word => searchTerms += (!searchTerms.Equals("") ? " " : "") + word);
searchQuery.OrWords.ForEach(word => searchTerms += (!searchTerms.Equals("") ? " " : "") + word);
searchQuery.NotWords.ForEach(word => searchTerms += (!searchTerms.Equals("") ? " " : "") + "-" + word);
searchQuery.AndPhrases.ForEach(phrase => searchTerms += (!searchTerms.Equals("") ? " " : "") + $"\"{phrase}\"");
searchQuery.OrPhrases.ForEach(phrase => searchTerms += (!searchTerms.Equals("") ? " " : "") + $"\"{phrase}\"");
searchQuery.NotPhrases.ForEach(phrase => searchTerms += (!searchTerms.Equals("") ? " " : "") + "-" + $"\"{phrase}\"");
return Builders<T>.Filter.Text(searchTerms, new TextSearchOptions { CaseSensitive = false });
}
static FilterDefinition<T> CreateFilterDefinition<T>(this IFilterBy<T> filter, string businessRepositoryEntityID = null) where T : class
{
var propertiesInfo = RepositoryMediator.GetProperties<T>(businessRepositoryEntityID);
var standardProperties = propertiesInfo.Item1;
var extendedProperties = propertiesInfo.Item2;
var filterDefinition = filter != null
? filter is FilterBys<T>
? (filter as FilterBys<T>).GetNoSqlStatement(standardProperties, extendedProperties)
: (filter as FilterBy<T>).GetNoSqlStatement(standardProperties, extendedProperties)
: null;
if (!string.IsNullOrWhiteSpace(businessRepositoryEntityID) && extendedProperties != null)
filterDefinition = filterDefinition == null
? Builders<T>.Filter.Eq("RepositoryEntityID", businessRepositoryEntityID)
: filterDefinition & Builders<T>.Filter.Eq("RepositoryEntityID", businessRepositoryEntityID);
return filterDefinition;
}
static SortDefinition<T> CreateSortDefinition<T>(this SortBy<T> sort, string businessRepositoryEntityID = null) where T : class
{
if (sort == null)
return null;
var propertiesInfo = RepositoryMediator.GetProperties<T>(businessRepositoryEntityID);
var standardProperties = propertiesInfo.Item1;
var extendedProperties = propertiesInfo.Item2;
return sort.GetNoSqlStatement(null, standardProperties, extendedProperties);
}
static SortDefinition<T> CreateSortDefinition<T>(this string scoreProperty) where T : class
=> Builders<T>.Sort.MetaTextScore(scoreProperty ?? "SearchScore");
static SortDefinition<T> CreateSortDefinition<T>(this SortDefinition<T> sort, string scoreProperty) where T : class
=> sort != null
? sort.MetaTextScore(scoreProperty ?? "SearchScore")
: NoSqlHelper.CreateSortDefinition<T>(scoreProperty);
static ProjectionDefinition<T> CreateProjectionDefinition<T>(this IEnumerable<string> attributes) where T : class
{
ProjectionDefinition<T> projection = null;
if (attributes == null || !attributes.Any())
projection = Builders<T>.Projection.Include("_id");
else
attributes.ForEach(attribute => projection = projection == null ? Builders<T>.Projection.Include(attribute) : projection.Include(attribute));
return projection;
}
static ProjectionDefinition<T> CreateProjectionDefinition<T>(this string scoreProperty) where T : class
=> Builders<T>.Projection.MetaTextScore(scoreProperty ?? "SearchScore");
static ProjectionDefinition<T> CreateProjectionDefinition<T>(this IEnumerable<string> attributes, string scoreProperty) where T : class
=> attributes != null && attributes.Any()
? NoSqlHelper.CreateProjectionDefinition<T>(attributes).MetaTextScore(scoreProperty ?? "SearchScore")
: NoSqlHelper.CreateProjectionDefinition<T>(scoreProperty);
static IFindFluent<T, T> CreateFindFluent<T>(this IMongoCollection<T> collection, IClientSessionHandle session, FilterDefinition<T> filter, SortDefinition<T> sort, int pageSize, int pageNumber, FindOptions options = null) where T : class
{
if (options == null)
{
options = new FindOptions();
if (!string.IsNullOrWhiteSpace(NoSqlHelper.AllowDiskUse) && !"(null)".IsEquals(NoSqlHelper.AllowDiskUse))
options.AllowDiskUse = "true".IsEquals(NoSqlHelper.AllowDiskUse);
if (!string.IsNullOrWhiteSpace(NoSqlHelper.AllowPartialResults) && !"(null)".IsEquals(NoSqlHelper.AllowPartialResults))
options.AllowPartialResults = "true".IsEquals(NoSqlHelper.AllowPartialResults);
}
var findFluent = collection.Find(session, filter ?? Builders<T>.Filter.Empty, options).Sort(sort ?? Builders<T>.Sort.Ascending("_id"));
if (pageSize > 0)
{
if (pageNumber > 1)
findFluent = findFluent.Skip((pageNumber - 1) * pageSize);
findFluent = findFluent.Limit(pageSize);
}
return findFluent;
}
static IFindFluent<T, BsonDocument> CreateSelectFluent<T>(this IMongoCollection<T> collection, IClientSessionHandle session, IEnumerable<string> attributes, FilterDefinition<T> filter, SortDefinition<T> sort, int pageSize, int pageNumber, FindOptions options = null) where T : class
=> collection.CreateFindFluent(session, filter, sort, pageSize, pageNumber, options).Project(NoSqlHelper.CreateProjectionDefinition<T>(attributes));
static IFindFluent<T, T> CreateSearchFluent<T>(this IMongoCollection<T> collection, IClientSessionHandle session, string query, FilterDefinition<T> filter, SortDefinition<T> sort, string scoreProperty, IEnumerable<string> attributes, int pageSize, int pageNumber, FindOptions options = null) where T : class
{
var filterBy = filter != null && !filter.Equals(Builders<T>.Filter.Empty)
? query.CreateFilterDefinition<T>() & filter
: query.CreateFilterDefinition<T>();
var sortBy = NoSqlHelper.CreateSortDefinition<T>(sort, scoreProperty);
var projection = NoSqlHelper.CreateProjectionDefinition<T>(attributes, scoreProperty);
return collection.CreateFindFluent(session, filterBy, sortBy, pageSize, pageNumber, options).Project<T>(projection);
}
static BsonDocument Render<T>(this FilterDefinition<T> filter) where T : class
{
var serializerRegistry = BsonSerializer.SerializerRegistry;
var documentSerializer = serializerRegistry.GetSerializer<T>();
return filter.Render(new RenderArgs<T>(documentSerializer, serializerRegistry));
}
#endregion
#region Create
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="object"></param>
/// <param name="options"></param>
public static void Create<T>(this IMongoCollection<T> collection, IClientSessionHandle session, T @object, InsertOneOptions options = null) where T : class
{
if (@object == null)
throw new ArgumentNullException(nameof(@object), "The object is null");
var stopwatch = Stopwatch.StartNew();
collection.InsertOne(session ?? collection.StartSession(), @object, options);
stopwatch.Stop();
if (RepositoryMediator.IsDebugEnabled)
RepositoryMediator.WriteLogs(new[]
{
$"NoSQL: Perform CREATE command successful [{typeof(T)}#{@object?.GetEntityID()}] @ {collection.CollectionNamespace.CollectionName}",
$"{(@object != null ? "Objects' data:\r\n\t" + @object.GetPublicProperties(attribute => !attribute.IsIgnored()).Select(attribute => $"+ @{attribute.Name} ({attribute.Type.GetTypeName(true)}) => [{@object.GetAttributeValue(attribute) ?? "(null)"}]").ToString("\r\n\t") + "\r\n" : "")}Execution times: {stopwatch.GetElapsedTimes()}"
});
}
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="object"></param>
/// <param name="options"></param>
public static void Create<T>(this IMongoCollection<T> collection, T @object, InsertOneOptions options = null) where T : class
=> collection.Create(null, @object, options);
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="options"></param>
public static void Create<T>(DataSource dataSource, T @object, InsertOneOptions options = null) where T : class
=> NoSqlHelper.GetCollection<T>(dataSource, RepositoryMediator.GetEntityDefinition<T>()).Create(@object, options);
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="options"></param>
public static void Create<T>(T @object, InsertOneOptions options = null) where T : class
=> NoSqlHelper.Create(RepositoryMediator.GetEntityDefinition<T>().GetPrimaryDataSource(), @object, options);
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="options"></param>
public static void Create<T>(this RepositoryContext context, DataSource dataSource, T @object, InsertOneOptions options = null) where T : class
=> context.GetCollection<T>(dataSource).Create(context.NoSqlSession, @object, options);
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="object"></param>
/// <param name="options"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task CreateAsync<T>(this IMongoCollection<T> collection, IClientSessionHandle session, T @object, InsertOneOptions options = null, CancellationToken cancellationToken = default) where T : class
{
if (@object == null)
throw new ArgumentNullException(nameof(@object), "The object is null");
var stopwatch = Stopwatch.StartNew();
await collection.InsertOneAsync(session ?? await collection.StartSessionAsync(cancellationToken).ConfigureAwait(false), @object, options, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
if (RepositoryMediator.IsDebugEnabled)
RepositoryMediator.WriteLogs(new[]
{
$"NoSQL: Perform CREATE command successful [{typeof(T)}#{@object?.GetEntityID()}] @ {collection.CollectionNamespace.CollectionName}",
$"{(@object != null ? "Objects' data:\r\n\t" + @object.GetPublicProperties(attribute => !attribute.IsIgnored()).Select(attribute => $"+ @{attribute.Name} ({attribute.Type.GetTypeName(true)}) => [{@object.GetAttributeValue(attribute) ?? "(null)"}]").ToString("\r\n\t") + "\r\n" : "")}Execution times: {stopwatch.GetElapsedTimes()}"
});
}
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="object"></param>
/// <param name="options"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task CreateAsync<T>(this IMongoCollection<T> collection, T @object, InsertOneOptions options = null, CancellationToken cancellationToken = default) where T : class
=> collection.CreateAsync(null, @object, options, cancellationToken);
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="options"></param>
public static Task CreateAsync<T>(DataSource dataSource, T @object, InsertOneOptions options = null, CancellationToken cancellationToken = default) where T : class
=> NoSqlHelper.GetCollection<T>(dataSource, RepositoryMediator.GetEntityDefinition<T>()).CreateAsync(@object, options, cancellationToken);
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="options"></param>
public static Task CreateAsync<T>(T @object, InsertOneOptions options = null, CancellationToken cancellationToken = default) where T : class
=> NoSqlHelper.CreateAsync(RepositoryMediator.GetEntityDefinition<T>().GetPrimaryDataSource(), @object, options, cancellationToken);
/// <summary>
/// Creates new document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="options"></param>
/// <param name="cancellationToken"></param>
public static Task CreateAsync<T>(this RepositoryContext context, DataSource dataSource, T @object, InsertOneOptions options = null, CancellationToken cancellationToken = default) where T : class
=> context.GetCollection<T>(dataSource).CreateAsync(context.NoSqlSession, @object, options, cancellationToken);
#endregion
#region Get
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="id"></param>
/// <param name="options">The options</param>
/// <returns></returns>
public static T Get<T>(this IMongoCollection<T> collection, IClientSessionHandle session, string id, FindOptions options = null) where T : class
=> !string.IsNullOrWhiteSpace(id)
? collection.Get(session, Builders<T>.Filter.Eq("_id", id), null, options)
: default;
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="id"></param>
/// <param name="options">The options</param>
/// <returns></returns>
public static T Get<T>(this IMongoCollection<T> collection, string id, FindOptions options = null) where T : class
=> collection.Get(null, id, options);
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="id">The string that presents identity</param>
/// <param name="options">The options</param>
/// <returns></returns>
public static T Get<T>(this RepositoryContext context, DataSource dataSource, string id, FindOptions options = null) where T : class
=> !string.IsNullOrWhiteSpace(id)
? context.GetCollection<T>(dataSource).Get(context.NoSqlSession, id, options)
: default;
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="id">The string that presents identity of the object that need to get</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<T> GetAsync<T>(this IMongoCollection<T> collection, IClientSessionHandle session, string id, FindOptions options = null, CancellationToken cancellationToken = default) where T : class
=> !string.IsNullOrWhiteSpace(id)
? collection.GetAsync(session, Builders<T>.Filter.Eq("_id", id), null, options, cancellationToken)
: Task.FromResult(default(T));
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="id">The string that presents identity of the object that need to get</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<T> GetAsync<T>(this IMongoCollection<T> collection, string id, FindOptions options = null, CancellationToken cancellationToken = default) where T : class
=> collection.GetAsync(null, id, options, cancellationToken);
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="id">The string that presents identity of the object that need to get</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<T> GetAsync<T>(this RepositoryContext context, DataSource dataSource, string id, FindOptions options = null, CancellationToken cancellationToken = default) where T : class
=> context.GetCollection<T>(dataSource).GetAsync(context.NoSqlSession, id, options, cancellationToken);
#endregion
#region Get (first match)
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="filter">The filter-by expression for filtering</param>
/// <param name="sort">The order-by expression for ordering</param>
/// <param name="options">The options</param>
/// <returns></returns>
public static T Get<T>(this IMongoCollection<T> collection, IClientSessionHandle session, FilterDefinition<T> filter, SortDefinition<T> sort = null, FindOptions options = null) where T : class
=> collection.Find(session, filter, sort, 1, 1, options).First();
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="filter">The filter-by expression for filtering</param>
/// <param name="sort">The order-by expression for ordering</param>
/// <param name="options">The options</param>
/// <returns></returns>
public static T Get<T>(this IMongoCollection<T> collection, FilterDefinition<T> filter, SortDefinition<T> sort = null, FindOptions options = null) where T : class
=> collection.Get(null, filter, sort, options);
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="filter">The filter-by expression for filtering</param>
/// <param name="sort">The order-by expression for ordering</param>
/// <param name="businessRepositoryEntityID">The identity of a business repository entity for working with extended properties/seperated data of a business content-type</param>
/// <param name="options">The options</param>
/// <returns></returns>
public static T Get<T>(this RepositoryContext context, DataSource dataSource, IFilterBy<T> filter, SortBy<T> sort = null, string businessRepositoryEntityID = null, FindOptions options = null) where T : class
=> context.GetCollection<T>(dataSource).Get(context.NoSqlSession, NoSqlHelper.CreateFilterDefinition<T>(filter, businessRepositoryEntityID), NoSqlHelper.CreateSortDefinition<T>(sort, businessRepositoryEntityID), options);
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="filter">The filter-by expression for filtering</param>
/// <param name="sort">The order-by expression for ordering</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task<T> GetAsync<T>(this IMongoCollection<T> collection, IClientSessionHandle session, FilterDefinition<T> filter, SortDefinition<T> sort = null, FindOptions options = null, CancellationToken cancellationToken = default) where T : class
=> (await collection.FindAsync(session, filter, sort, 1, 1, options, cancellationToken).ConfigureAwait(false)).First();
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="filter">The filter-by expression for filtering</param>
/// <param name="sort">The order-by expression for ordering</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<T> GetAsync<T>(this IMongoCollection<T> collection, FilterDefinition<T> filter, SortDefinition<T> sort = null, FindOptions options = null, CancellationToken cancellationToken = default) where T : class
=> collection.GetAsync(null, filter, sort, options, cancellationToken);
/// <summary>
/// Gets document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="filter">The filter-by expression for filtering</param>
/// <param name="sort">The order-by expression for ordering</param>
/// <param name="businessRepositoryEntityID">The identity of a business repository entity for working with extended properties/seperated data of a business content-type</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<T> GetAsync<T>(this RepositoryContext context, DataSource dataSource, IFilterBy<T> filter, SortBy<T> sort = null, string businessRepositoryEntityID = null, FindOptions options = null, CancellationToken cancellationToken = default) where T : class
=> context.GetCollection<T>(dataSource).GetAsync(context.NoSqlSession, NoSqlHelper.CreateFilterDefinition<T>(filter, businessRepositoryEntityID), NoSqlHelper.CreateSortDefinition<T>(sort, businessRepositoryEntityID), options, cancellationToken);
#endregion
#region Get (by definition and identity)
/// <summary>
/// Gets document of an object
/// </summary>
/// <param name="dataSource">The data source</param>
/// <param name="definition">The definition</param>
/// <param name="id">The identity</param>
/// <param name="options">The options</param>
/// <returns></returns>
public static object Get(DataSource dataSource, EntityDefinition definition, string id, FindOptions options = null)
{
dataSource = dataSource ?? definition.GetPrimaryDataSource();
var collection = NoSqlHelper.GetCollection<BsonDocument>(RepositoryMediator.GetConnectionString(dataSource), dataSource.DatabaseName, definition.CollectionName, true);
var document = collection.Get(id, options);
return document != null
? BsonSerializer.Deserialize(document, definition.Type)
: null;
}
/// <summary>
/// Gets document of an object
/// </summary>
/// <param name="definition">The definition</param>
/// <param name="id">The identity</param>
/// <param name="options">The options</param>
/// <returns></returns>
public static object Get(EntityDefinition definition, string id, FindOptions options = null)
=> NoSqlHelper.Get(definition?.GetPrimaryDataSource(), definition, id, options);
/// <summary>
/// Gets document of an object
/// </summary>
/// <param name="dataSource">The data source</param>
/// <param name="definition">The definition</param>
/// <param name="id">The identity</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task<object> GetAsync(DataSource dataSource, EntityDefinition definition, string id, FindOptions options = null, CancellationToken cancellationToken = default)
{
dataSource = dataSource ?? definition.GetPrimaryDataSource();
var collection = NoSqlHelper.GetCollection<BsonDocument>(RepositoryMediator.GetConnectionString(dataSource), dataSource.DatabaseName, definition.CollectionName, true);
var document = await collection.GetAsync(id, options, cancellationToken).ConfigureAwait(false);
return document != null
? BsonSerializer.Deserialize(document, definition.Type)
: null;
}
/// <summary>
/// Gets document of an object
/// </summary>
/// <param name="definition">The definition</param>
/// <param name="id">The identity</param>
/// <param name="options">The options</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<object> GetAsync(EntityDefinition definition, string id, FindOptions options = null, CancellationToken cancellationToken = default)
=> NoSqlHelper.GetAsync(definition?.GetPrimaryDataSource(), definition, id, options, cancellationToken);
#endregion
#region Replace
/// <summary>
/// Replaces document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="object">The object for updating</param>
/// <param name="options">The options for updating</param>
/// <returns></returns>
public static ReplaceOneResult Replace<T>(this IMongoCollection<T> collection, IClientSessionHandle session, T @object, ReplaceOptions options = null) where T : class
{
var stopwatch = Stopwatch.StartNew();
try
{
return @object != null
? collection.ReplaceOne(session ?? collection.StartSession(), Builders<T>.Filter.Eq("_id", @object.GetEntityID()), @object, options ?? new ReplaceOptions { IsUpsert = true })
: throw new ArgumentNullException(nameof(@object), "The object is null");
}
catch (Exception)
{
throw;
}
finally
{
stopwatch.Stop();
if (RepositoryMediator.IsDebugEnabled)
RepositoryMediator.WriteLogs(new[]
{
$"NoSQL: {(@object != null ? "Perform REPLACE command successful" : "No valid object to perform replace")} [{typeof(T)}#{@object?.GetEntityID()}] @ {collection.CollectionNamespace.CollectionName}",
$"{(@object != null ? "Objects' data:\r\n\t" + @object.GetPublicProperties(attribute => !attribute.IsIgnored()).Select(attribute => $"+ @{attribute.Name} ({attribute.Type.GetTypeName(true)}) => [{@object.GetAttributeValue(attribute) ?? "(null)"}]").ToString("\r\n\t") + "\r\n" : "")}Execution times: {stopwatch.GetElapsedTimes()}"
});
}
}
/// <summary>
/// Replaces document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="object">The object for updating</param>
/// <param name="options">The options for updating</param>
/// <returns></returns>
public static ReplaceOneResult Replace<T>(this IMongoCollection<T> collection, T @object, ReplaceOptions options = null) where T : class
=> collection.Replace(null, @object, options);
/// <summary>
/// Replaces document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for updating</param>
/// <param name="options">The options for updating</param>
/// <returns></returns>
public static ReplaceOneResult Replace<T>(this RepositoryContext context, DataSource dataSource, T @object, ReplaceOptions options = null) where T : class
=> context.GetCollection<T>(dataSource).Replace(context.NoSqlSession, @object, options);
/// <summary>
/// Replaces document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="object">The object for updating</param>
/// <param name="options">The options for updating</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task<ReplaceOneResult> ReplaceAsync<T>(this IMongoCollection<T> collection, IClientSessionHandle session, T @object, ReplaceOptions options = null, CancellationToken cancellationToken = default) where T : class
{
var stopwatch = Stopwatch.StartNew();
try
{
return @object != null
? await collection.ReplaceOneAsync(session ?? await collection.StartSessionAsync(cancellationToken).ConfigureAwait(false), Builders<T>.Filter.Eq("_id", @object.GetEntityID()), @object, options ?? new ReplaceOptions { IsUpsert = true }, cancellationToken).ConfigureAwait(false)
: throw new ArgumentNullException(nameof(@object), "The object is null");
}
catch (Exception)
{
throw;
}
finally
{
stopwatch.Stop();
if (RepositoryMediator.IsDebugEnabled)
RepositoryMediator.WriteLogs(new[]
{
$"NoSQL: {(@object != null ? "Perform REPLACE command successful" : "No valid object to perform replace")} [{typeof(T)}#{@object?.GetEntityID()}] @ {collection.CollectionNamespace.CollectionName}",
$"{(@object != null ? "Objects' data:\r\n\t" + @object.GetPublicProperties(attribute => !attribute.IsIgnored()).Select(attribute => $"+ @{attribute.Name} ({attribute.Type.GetTypeName(true)}) => [{@object.GetAttributeValue(attribute) ?? "(null)"}]").ToString("\r\n\t") + "\r\n" : "")}Execution times: {stopwatch.GetElapsedTimes()}"
});
}
}
/// <summary>
/// Replaces document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="object">The object for updating</param>
/// <param name="options">The options for updating</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<ReplaceOneResult> ReplaceAsync<T>(this IMongoCollection<T> collection, T @object, ReplaceOptions options = null, CancellationToken cancellationToken = default) where T : class
=> collection.ReplaceAsync(null, @object, options, cancellationToken);
/// <summary>
/// Replaces document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for updating</param>
/// <param name="options">The options for updating</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task<ReplaceOneResult> ReplaceAsync<T>(this RepositoryContext context, DataSource dataSource, T @object, ReplaceOptions options = null, CancellationToken cancellationToken = default) where T : class
=> context.GetCollection<T>(dataSource).ReplaceAsync(context.NoSqlSession, @object, options, cancellationToken);
#endregion
#region Update
static BsonArray ToBsonArray(this IEnumerable @object, Type type)
{
var values = new List<BsonValue>();
if (type.IsClassType())
foreach (var item in @object)
if (item == null)
values.Add(BsonNull.Value);
else
{
var document = item.ToBsonDocument();
document.Remove("_t");
values.Add(document);
}
else
foreach (var item in @object)
values.Add(item == null ? BsonNull.Value : BsonValue.Create(item));
return new BsonArray(values);
}
static BsonValue ToBsonValue(this ObjectService.AttributeInfo attribute, object value)
{
if (value == null)
return null;
var bsonRepresentation = attribute.IsEnum() ? attribute.GetCustomAttribute<BsonRepresentationAttribute>() : null;
return bsonRepresentation != null && bsonRepresentation.Representation.Equals(BsonType.String)
? BsonValue.Create(value.ToString())
: BsonValue.Create(value);
}
/// <summary>
/// Updates document of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="session">The working session</param>
/// <param name="object">The object for updating</param>
/// <param name="attributes">The collection of attributes for updating individually</param>
/// <param name="options">The options for updating</param>
/// <returns>ReplaceOneResult or UpdateResult object</returns>
public static void Update<T>(this IMongoCollection<T> collection, IClientSessionHandle session, T @object, List<string> attributes, UpdateOptions options = null) where T : class
{
// check
if (@object == null)
throw new ArgumentNullException(nameof(@object), "The object is null");
else if (attributes == null || attributes.Count < 1)
throw new ArgumentException("No attribute to update");
var stopwatch = Stopwatch.StartNew();
// get collection of all attributes
var objAttributes = RepositoryMediator.GetEntityDefinition<T>().Attributes;
// check to use replace (when got generic of primitive or class type member - workaround)
var useReplace = false;
foreach (var name in attributes)
{
if (name.StartsWith("ExtendedProperties."))
{
useReplace = true;
break;
}
var attribute = objAttributes.FirstOrDefault(a => a.Name.IsEquals(name));
if (attribute != null)
{
useReplace = attribute.Type.IsClassType() || (attribute.Type.IsGenericListOrHashSet() && attribute.Type.GenericTypeArguments[0].IsClassType()) || (attribute.Type.IsArray && attribute.Type.GetElementType().IsClassType());
if (useReplace)
break;
}
}
// replace whole document (when got generic of primitive or class type member - workaround)
if (useReplace)
{
collection.ReplaceOne(session ?? collection.StartSession(), Builders<T>.Filter.Eq("_id", @object.GetEntityID()), @object, new ReplaceOptions { IsUpsert = options == null || options.IsUpsert });
stopwatch.Stop();
if (RepositoryMediator.IsDebugEnabled)
RepositoryMediator.WriteLogs(new[]
{
$"NoSQL: updated attributes got a generic primitive or a class type, then switch to use Replace instead of Update",
$"- Execution times: {stopwatch.GetElapsedTimes()}",
$"- Updated attributes: [{attributes.ToString(", ")}]",
$"- Objects' data for replacing:\r\n\t" + objAttributes.Select(attribute => $"+ @{attribute.Name} ({attribute.Type.GetTypeName(true)}) => [{@object.GetAttributeValue(attribute) ?? "(null)"}]").ToString("\r\n\t") + "\r\n\t+ ExtendedProperties: " + @object.GetAttributeValue("ExtendedProperties")?.ToJson(null).ToString(Newtonsoft.Json.Formatting.None)
});
return;
}
// update individually
UpdateDefinition<T> updater = null;
var updated = "";
attributes.ForEach(name =>
{
var attribute = objAttributes.FirstOrDefault(a => a.Name.IsEquals(name));
if (attribute != null)
{
var value = @object.GetAttributeValue(attribute);
var isList = value != null && ((attribute.Type.IsGenericListOrHashSet() && attribute.Type.GenericTypeArguments[0].IsClassType()) || (attribute.Type.IsArray && attribute.Type.GetElementType().IsClassType()));
var type = isList
? attribute.Type.IsGenericListOrHashSet()
? attribute.Type.GenericTypeArguments[0]