-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTopicMappingService.cs
1182 lines (1034 loc) · 68 KB
/
TopicMappingService.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
/*==============================================================================================================================
| Author Ignia, LLC
| Client Ignia, LLC
| Project Topics Library
\=============================================================================================================================*/
using System.Collections;
using System.Reflection;
using OnTopic.Collections.Specialized;
using OnTopic.Internal.Reflection;
using OnTopic.Lookup;
using OnTopic.Mapping.Annotations;
using OnTopic.Mapping.Internal;
using OnTopic.Models;
using OnTopic.Repositories;
namespace OnTopic.Mapping {
/*============================================================================================================================
| CLASS: TOPIC MAPPING SERVICE
\---------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Provides a concrete implementation of the <see cref="ITopicMappingService"/> for mapping <see cref="Topic"/> instances
/// to data transfer objects (such as view models) based on set conventions and attribute-based hints.
/// </summary>
public class TopicMappingService : ITopicMappingService {
/*==========================================================================================================================
| PRIVATE VARIABLES
\-------------------------------------------------------------------------------------------------------------------------*/
readonly ITopicRepository _topicRepository;
readonly ITypeLookupService _typeLookupService;
static readonly TypeAccessor _topicTypeAccessor = TypeAccessorCache.GetTypeAccessor<Topic>();
/*==========================================================================================================================
| CONSTRUCTOR
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Establishes a new instance of a <see cref="TopicMappingService"/> with required dependencies.
/// </summary>
public TopicMappingService(ITopicRepository topicRepository, ITypeLookupService typeLookupService) {
Contract.Requires(topicRepository, "An instance of an ITopicRepository is required.");
Contract.Requires(typeLookupService, "An instance of an ITypeLookupService is required.");
_topicRepository = topicRepository;
_typeLookupService = typeLookupService;
}
/*==========================================================================================================================
| METHOD: MAP (DYNAMIC)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <inheritdoc />
[return: NotNullIfNotNull("topic")]
public async Task<object?> MapAsync(Topic? topic, AssociationTypes associations = AssociationTypes.All) =>
await MapAsync(topic, associations, new()).ConfigureAwait(false);
/// <summary>
/// Given a topic, will identify any View Models named, by convention, "{ContentType}TopicViewModel" and populate them
/// according to the rules of the mapping implementation.
/// </summary>
/// <remarks>
/// <para>
/// Because the class is using reflection to determine the target View Models, the return type is <see cref="Object"/>.
/// These results may need to be cast to a specific type, depending on the context. That said, strongly typed views
/// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known
/// upfront, and it is imperative that it be strongly typed, prefer <see cref="MapAsync{T}(Topic, AssociationTypes)"/>.
/// </para>
/// <para>
/// Because the target object is being dynamically constructed, it must implement a default constructor.
/// </para>
/// <para>
/// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with
/// recursion in case <see cref="Topic"/> is referred to multiple times (e.g., a <c>Children</c> collection with
/// <see cref="IncludeAttribute"/> set to include <see cref="AssociationTypes.Parents"/>).
/// </para>
/// </remarks>
/// <param name="topic">The <see cref="Topic"/> entity to derive the data from.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
/// <returns>An instance of the dynamically determined View Model with properties appropriately mapped.</returns>
private async Task<object?> MapAsync(
Topic? topic,
AssociationTypes associations,
MappedTopicCache cache,
string? attributePrefix = null
) {
/*------------------------------------------------------------------------------------------------------------------------
| Validate input
\-----------------------------------------------------------------------------------------------------------------------*/
if (topic is null) {
return null;
}
/*------------------------------------------------------------------------------------------------------------------------
| Lookup type
\-----------------------------------------------------------------------------------------------------------------------*/
var viewModelType = _typeLookupService.Lookup($"{topic.ContentType}TopicViewModel", $"{topic.ContentType}ViewModel");
if (viewModelType is null) {
throw new InvalidTypeException(
$"No class named '{topic.ContentType}TopicViewModel' could be located in any loaded assemblies. This is required " +
$"to map the topic '{topic.GetUniqueKey()}'."
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Perform mapping
\-----------------------------------------------------------------------------------------------------------------------*/
return await MapAsync(topic, viewModelType, associations, cache, attributePrefix).ConfigureAwait(false);
}
/// <summary>
/// Will map a given <paramref name="topic"/> to a given <paramref name="type"/>, according to the rules of the mapping
/// implementation.
/// </summary>
/// <remarks>
/// <para>
/// Because the class is using reflection to determine the target View Models, the return type is <see cref="Object"/>.
/// These results may need to be cast to a specific type, depending on the context. That said, strongly-typed views
/// should be able to cast the object to the appropriate View Model type. If the type of the View Model is known
/// upfront, and it is imperative that it be strongly-typed, prefer <see cref="MapAsync{T}(Topic, AssociationTypes)"/>.
/// </para>
/// <para>
/// Because the target object is being dynamically constructed, it must implement a default constructor.
/// </para>
/// <para>
/// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with
/// recursion in case <see cref="Topic"/> is referred to multiple times (e.g., a <c>Children</c> collection with
/// <see cref="IncludeAttribute"/> set to include <see cref="AssociationTypes.Parents"/>).
/// </para>
/// </remarks>
/// <param name="topic">The <see cref="Topic"/> entity to derive the data from.</param>
/// <param name="type">The <see cref="Type"/> that should be used for the View Model.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
/// <returns>An instance of the dynamically determined View Model with properties appropriately mapped.</returns>
private async Task<object?> MapAsync(
Topic? topic,
Type type,
AssociationTypes associations,
MappedTopicCache cache,
string? attributePrefix = null
) {
/*------------------------------------------------------------------------------------------------------------------------
| Validate input
\-----------------------------------------------------------------------------------------------------------------------*/
if (topic is null || type is null) {
return null;
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle cached objects
\-----------------------------------------------------------------------------------------------------------------------*/
var target = (object?)null;
if (cache.TryGetValue(topic.Id, type, out var cacheEntry)) {
target = cacheEntry.MappedTopic;
if (cacheEntry.GetMissingAssociations(associations) == AssociationTypes.None) {
return target;
}
//Call MapAsync() with target object to map missing attributes
return await MapAsync(topic, target, associations, cache, attributePrefix).ConfigureAwait(false);
}
/*------------------------------------------------------------------------------------------------------------------------
| Identify parameters
\-----------------------------------------------------------------------------------------------------------------------*/
var typeAccessor = TypeAccessorCache.GetTypeAccessor(type);
var properties = typeAccessor.GetMembers(MemberTypes.Property);
var parameters = typeAccessor.ConstructorParameters;
var arguments = new object?[parameters.Count];
var attributeArguments = (IDictionary<string, string?>)new Dictionary<string, string?>();
var parameterQueue = new Dictionary<int, Task<object?>>();
/*------------------------------------------------------------------------------------------------------------------------
| Pre-cache entry
>-------------------------------------------------------------------------------------------------------------------------
| In property mapping, we deal with circular references by returning a cached reference. That isn't practical with
| circular references in constructor mapping. To help avoid these, we register a pre-cache entry as IsInitializing, but
| without a mapped object; the TopicMappingCache is expected to throw an exception if an attempt to map that topic to that
| type occurs again prior to the constructor mapping being completed.
\-----------------------------------------------------------------------------------------------------------------------*/
cache.Preregister(topic.Id, type);
/*------------------------------------------------------------------------------------------------------------------------
| Handle AttributeDictionary constructor
>-------------------------------------------------------------------------------------------------------------------------
| A model may optionally expose a constructor with a single parameter accepting an AttributeDictionary. In this scenario,
| the TopicMappingService may optionally pass a lightweight AttributeDictionary, allowing the model's constructor to
| populate scalar values, instead of relying on reflection.
\-----------------------------------------------------------------------------------------------------------------------*/
if (parameters.Count is 1 && parameters[0].Type == typeof(AttributeDictionary)) {
// This strategy is only performant if there are quite a several scalar properties and they are well-covered by the
// attributes. As a fast heuristic to evaluate this, we expect five or more attributes and three or more compatible
// properties. In practice, this should be benefitial with any more than mapped attributes, but we also expect that most
// topics will have 2-3 excluded or unmapped attributes (e.g., Title, LastModified). With models, we can be a bit more
// intelligent, by excluding any members that are likely compatible with Topic properties, thus exluding e.g., Id, Key,
// WebPath, etc. This doesn't guarantee that the attributes map to the properties, but a more accurate evaluation would
// undermine the performance benefits of this optimization.
if (topic.Attributes.Count >= 5 && properties.Count(p => !p.MaybeCompatible) >= 3) {
var attributes = topic.Attributes.AsAttributeDictionary(true);
arguments[0] = attributes;
attributeArguments = attributes;
}
else {
parameters = new();
arguments = Array.Empty<object?>();
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle other constructors
>-------------------------------------------------------------------------------------------------------------------------
| A model may optionally expose a constructor with multiple parameters, which can be defined via reflection in the same
| way as properties would be. This is especially useful for records using the positional syntax (i.e., where properties
| are defined using the constructor). This also, optionally, provides the model with more control, where needed, over how
| it's constructed.
\-----------------------------------------------------------------------------------------------------------------------*/
else {
foreach (var parameter in parameters) {
parameterQueue.Add(parameter.ParameterInfo.Position, GetParameterAsync(topic, associations, parameter, cache, attributePrefix));
}
await Task.WhenAll(parameterQueue.Values).ConfigureAwait(false);
foreach (var parameter in parameterQueue) {
arguments[parameter.Key] = await parameter.Value.ConfigureAwait(false);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Initialize object
\-----------------------------------------------------------------------------------------------------------------------*/
target = Activator.CreateInstance(type, arguments);
Contract.Assume(
target,
$"The target type '{type}' could not be properly constructed, as required to map the topic '{topic.GetUniqueKey()}'."
);
/*------------------------------------------------------------------------------------------------------------------------
| Cache object
\-----------------------------------------------------------------------------------------------------------------------*/
cache.Register(topic.Id, associations, target);
/*------------------------------------------------------------------------------------------------------------------------
| Loop through properties, mapping each one
\-----------------------------------------------------------------------------------------------------------------------*/
var propertyQueue = new List<Task>();
var mappedParameters = parameters.Select(p => p.Name).Union(attributeArguments.Select(a => a.Key));
foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) {
if (!mappedParameters.Contains(property.Name, StringComparer.OrdinalIgnoreCase)) {
propertyQueue.Add(SetPropertyAsync(topic, target, associations, property, cache, attributePrefix, false));
}
}
await Task.WhenAll(propertyQueue.ToArray()).ConfigureAwait(false);
/*------------------------------------------------------------------------------------------------------------------------
| Return target
\-----------------------------------------------------------------------------------------------------------------------*/
return target;
}
/*==========================================================================================================================
| METHOD: MAP (T)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <inheritdoc />
public async Task<T?> MapAsync<T>(Topic? topic, AssociationTypes associations = AssociationTypes.All) where T : class {
if (typeof(Topic).IsAssignableFrom(typeof(T))) {
return topic as T;
}
return (T?)await MapAsync(topic, typeof(T), associations, new()).ConfigureAwait(false);
}
/*==========================================================================================================================
| METHOD: MAP (OBJECTS)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <inheritdoc />
public async Task<object?> MapAsync(Topic? topic, object target, AssociationTypes associations = AssociationTypes.All) {
Contract.Requires(target, nameof(target));
return await MapAsync(topic, target, associations, new()).ConfigureAwait(false);
}
/// <summary>
/// Given a topic and an instance of a DTO, will populate the DTO according to the default mapping rules.
/// </summary>
/// <param name="topic">The <see cref="Topic"/> entity to derive the data from.</param>
/// <param name="target">The target object to map the data to.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
/// <remarks>
/// This internal version passes a private cache of mapped objects from this run. This helps prevent problems with
/// recursion in case <see cref="Topic"/> is referred to multiple times (e.g., a <c>Children</c> collection with <see cref
/// ="IncludeAttribute"/> set to include <see cref="AssociationTypes.Parents"/>).
/// </remarks>
/// <returns>
/// The target view model with the properties appropriately mapped.
/// </returns>
private async Task<object> MapAsync(
Topic? topic,
object target,
AssociationTypes associations,
MappedTopicCache cache,
string? attributePrefix = null
) {
/*------------------------------------------------------------------------------------------------------------------------
| Validate input
\-----------------------------------------------------------------------------------------------------------------------*/
if (topic is null) {
return target;
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle topics
\-----------------------------------------------------------------------------------------------------------------------*/
if (target is Topic) {
return topic;
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle cached objects
>-------------------------------------------------------------------------------------------------------------------------
| If the cache contains an entry, check to make sure it includes all of the requested associations. If it does, return it.
| If it doesn't, determine the missing associations and request to have those mapped.
\-----------------------------------------------------------------------------------------------------------------------*/
if (cache.TryGetValue(topic.Id, target.GetType(), out var cacheEntry)) {
associations = cacheEntry.GetMissingAssociations(associations);
target = cacheEntry.MappedTopic;
if (associations is AssociationTypes.None) {
return cacheEntry.MappedTopic;
}
cacheEntry.AddMissingAssociations(associations);
}
else if (!topic.IsNew) {
cache.Register(
topic.Id,
associations,
target
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Loop through properties, mapping each one
\-----------------------------------------------------------------------------------------------------------------------*/
var taskQueue = new List<Task>();
var typeAccessor = TypeAccessorCache.GetTypeAccessor(target.GetType());
foreach (var property in typeAccessor.GetMembers(MemberTypes.Property)) {
taskQueue.Add(SetPropertyAsync(topic, target, associations, property, cache, attributePrefix, cacheEntry is not null));
}
await Task.WhenAll(taskQueue.ToArray()).ConfigureAwait(false);
/*------------------------------------------------------------------------------------------------------------------------
| Return result
\-----------------------------------------------------------------------------------------------------------------------*/
return target;
}
/*==========================================================================================================================
| PRIVATE: GET PARAMETER (ASYNC)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Given a <paramref name="parameter"/>, retrieves the appropriate value from the corresponding <paramref name="source"/>
/// topic, while honoring <paramref name="associations"/>.
/// </summary>
/// <param name="source">The <see cref="Topic"/> entity to derive the data from.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="parameter">Information related to the current parameter.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
private async Task<object?> GetParameterAsync(
Topic source,
AssociationTypes associations,
ParameterMetadata parameter,
MappedTopicCache cache,
string? attributePrefix = null
) {
/*------------------------------------------------------------------------------------------------------------------------
| Establish per-property variables
\-----------------------------------------------------------------------------------------------------------------------*/
var configuration = parameter.Configuration;
/*------------------------------------------------------------------------------------------------------------------------
| Bypass if mapping is disabled
\-----------------------------------------------------------------------------------------------------------------------*/
if (configuration.DisableMapping) {
return parameter.ParameterInfo.DefaultValue;
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle [MapToParent] attribute
\-----------------------------------------------------------------------------------------------------------------------*/
if (configuration.MapToParent) {
return await MapAsync(
source,
parameter.Type,
associations,
cache,
configuration.AttributePrefix + attributePrefix
).ConfigureAwait(false);
}
/*------------------------------------------------------------------------------------------------------------------------
| Determine value
\-----------------------------------------------------------------------------------------------------------------------*/
var value = await GetValue(source, parameter.Type, associations, parameter, cache, attributePrefix, false).ConfigureAwait(false);
if (value is null && parameter.IsList) {
return await getList(parameter.Type).ConfigureAwait(false);
}
return value;
/*------------------------------------------------------------------------------------------------------------------------
| Get List Function
\-----------------------------------------------------------------------------------------------------------------------*/
async Task<IList?> getList(Type targetType) {
var sourceList = GetSourceCollection(source, associations, parameter, attributePrefix);
var targetList = InitializeCollection(targetType);
if (sourceList is null || targetList is null) {
return (IList?)null;
}
await PopulateTargetCollectionAsync(sourceList, targetList, parameter, cache).ConfigureAwait(false);
return targetList;
}
}
/*==========================================================================================================================
| PRIVATE: SET PROPERTY (ASYNC)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Helper function that evaluates each property on the target object and attempts to retrieve a value from the source
/// <see cref="Topic"/> based on predetermined conventions.
/// </summary>
/// <param name="source">The <see cref="Topic"/> entity to derive the data from.</param>
/// <param name="target">The target object to map the data to.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="propertyAccessor">Information related to the current property.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
/// <param name="mapAssociationsOnly">Determines if properties not associated with associations should be mapped.</param>
private async Task SetPropertyAsync(
Topic source,
object target,
AssociationTypes associations,
MemberAccessor propertyAccessor,
MappedTopicCache cache,
string? attributePrefix = null,
bool mapAssociationsOnly = false
) {
/*------------------------------------------------------------------------------------------------------------------------
| Establish per-property variables
\-----------------------------------------------------------------------------------------------------------------------*/
var configuration = propertyAccessor.Configuration;
/*------------------------------------------------------------------------------------------------------------------------
| Bypass if mapping is disabled
\-----------------------------------------------------------------------------------------------------------------------*/
if (configuration.DisableMapping) {
return;
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle [MapToParent] attribute
\-----------------------------------------------------------------------------------------------------------------------*/
if (configuration.MapToParent) {
var targetProperty = propertyAccessor.GetValue(target);
if (targetProperty is not null) {
await MapAsync(
source,
targetProperty,
associations,
cache,
configuration.AttributePrefix + attributePrefix
).ConfigureAwait(false);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Determine value
\-----------------------------------------------------------------------------------------------------------------------*/
else {
var value = await GetValue(source, propertyAccessor.Type, associations, propertyAccessor, cache, attributePrefix, mapAssociationsOnly).ConfigureAwait(false);
if (value is null && propertyAccessor.IsList) {
await SetCollectionValueAsync(source, target, associations, propertyAccessor, cache, attributePrefix).ConfigureAwait(false);
}
else if (value != null && propertyAccessor.CanWrite) {
propertyAccessor.SetValue(target, value, true);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Validate fields
\-----------------------------------------------------------------------------------------------------------------------*/
propertyAccessor.Validate(target);
}
/*==========================================================================================================================
| PRIVATE: GET VALUE (ASYNC)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Helper function that retrieves a value from the source <see cref="Topic"/> based on predetermined conventions.
/// </summary>
/// <param name="source">The <see cref="Topic"/> entity to derive the data from.</param>
/// <param name="targetType">The <see cref="Type"/> of the target parameter or property.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="itemMetadata">Information related to the current parameter or property.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
/// <param name="mapAssociationsOnly">Determines if properties not associated with associations should be mapped.</param>
private async Task<object?> GetValue(
Topic source,
Type targetType,
AssociationTypes associations,
ItemMetadata itemMetadata,
MappedTopicCache cache,
string? attributePrefix = "",
bool mapAssociationsOnly = false
) {
/*------------------------------------------------------------------------------------------------------------------------
| Establish configuration
\-----------------------------------------------------------------------------------------------------------------------*/
var configuration = itemMetadata.Configuration;
/*------------------------------------------------------------------------------------------------------------------------
| Assign default value
\-----------------------------------------------------------------------------------------------------------------------*/
var value = (object?)null;
if (!mapAssociationsOnly && configuration.DefaultValue is not null) {
value = configuration.DefaultValue;
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle by type, attribute
\-----------------------------------------------------------------------------------------------------------------------*/
if (TryGetCompatibleProperty(source, targetType, itemMetadata, attributePrefix, out var compatibleValue)) {
value = compatibleValue;
}
else if (itemMetadata.IsConvertible) {
if (!mapAssociationsOnly) {
value = GetScalarValue(source, itemMetadata, attributePrefix);
}
}
else if (itemMetadata.IsList) {
return null;
}
else if (configuration.GetCompositeAttributeKey(attributePrefix) is "Parent") {
if (associations.HasFlag(AssociationTypes.Parents) && source.Parent is not null) {
value = await GetTopicReferenceAsync(source.Parent, targetType, itemMetadata, cache).ConfigureAwait(false);
}
}
else if (configuration.MapToParent) {
return null;
}
else if (itemMetadata.Type.IsClass && associations.HasFlag(AssociationTypes.References)) {
var topicReference = getTopicReference();
if (topicReference is not null) {
value = await GetTopicReferenceAsync(topicReference, targetType, itemMetadata, cache).ConfigureAwait(false);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Return value
\-----------------------------------------------------------------------------------------------------------------------*/
return value;
/*------------------------------------------------------------------------------------------------------------------------
| Get Topic Reference
\-----------------------------------------------------------------------------------------------------------------------*/
Topic? getTopicReference() {
// Check for standard topic reference
var topicReference = source.References.GetValue(configuration.GetCompositeAttributeKey(attributePrefix));
if (topicReference is not null) {
return topicReference;
}
int topicReferenceId;
if (configuration.GetCompositeAttributeKey(attributePrefix).EndsWith("Id", StringComparison.OrdinalIgnoreCase)) {
topicReferenceId = source.Attributes.GetInteger(configuration.GetCompositeAttributeKey(attributePrefix), 0);
}
else {
topicReferenceId = source.Attributes.GetInteger($"{configuration.GetCompositeAttributeKey(attributePrefix)}Id", 0);
}
if (topicReferenceId > 0) {
topicReference = _topicRepository.Load(topicReferenceId, source);
}
return topicReference;
}
}
/*==========================================================================================================================
| PRIVATE: GET SCALAR VALUE
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Gets a scalar property from a <see cref="Topic"/>.
/// </summary>
/// <remarks>
/// The <see cref="GetScalarValue(Topic, ItemMetadata, String)"/> method will attempt to retrieve the value from the
/// <paramref name="source"/> based on, in order, the <paramref name="source"/>'s <c>Get{Property}()</c> method,
/// <c>{Property}</c> property, and, finally, its <see cref="Topic.Attributes"/> collection (using <see cref="
/// TrackedRecordCollection{TItem, TValue, TAttribute}.GetValue(String, Boolean)"/>).
/// </remarks>
/// <param name="source">The source <see cref="Topic"/> from which to pull the value.</param>
/// <param name="itemMetadata">The <see cref="ItemMetadata"/> with details about the property's attributes.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
/// <autogeneratedoc />
private static object? GetScalarValue(Topic source, ItemMetadata itemMetadata, string? attributePrefix) {
/*------------------------------------------------------------------------------------------------------------------------
| Establish configuration
\-----------------------------------------------------------------------------------------------------------------------*/
var configuration = itemMetadata.Configuration;
/*------------------------------------------------------------------------------------------------------------------------
| Attempt to retrieve value from topic.Get{Property}()
\-----------------------------------------------------------------------------------------------------------------------*/
var typeAccessor = GetTopicAccessor(source.GetType());
var attributeValue = (string?)null;
var maybeCompatible = source.GetType() != typeof(Topic) || itemMetadata.MaybeCompatible;
/*------------------------------------------------------------------------------------------------------------------------
| Attempt to retrieve value from topic.{Property}
\-----------------------------------------------------------------------------------------------------------------------*/
if (maybeCompatible) {
attributeValue = typeAccessor.GetMethodValue(source, $"Get{configuration.GetCompositeAttributeKey(attributePrefix)}")?.ToString();
}
/*------------------------------------------------------------------------------------------------------------------------
| Attempt to retrieve value from topic.{Property}
\-----------------------------------------------------------------------------------------------------------------------*/
if (maybeCompatible && attributeValue is null) {
attributeValue = typeAccessor.GetPropertyValue(source, configuration.GetCompositeAttributeKey(attributePrefix))?.ToString();
}
/*------------------------------------------------------------------------------------------------------------------------
| Otherwise, attempt to retrieve value from topic.Attributes.GetValue({Property})
\-----------------------------------------------------------------------------------------------------------------------*/
if (attributeValue is null) {
attributeValue = source.Attributes.GetValue(
configuration.GetCompositeAttributeKey(attributePrefix),
configuration.DefaultValue?.ToString(),
configuration.InheritValue
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Return value
\-----------------------------------------------------------------------------------------------------------------------*/
return attributeValue;
}
/*==========================================================================================================================
| PRIVATE: INITIALIZE COLLECTION
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Given a collection type, attempts to initialize a compatible type.
/// </summary>
/// <param name="targetType">The <see cref="Type"/> of collection to initialize.</param>
private static IList? InitializeCollection(Type targetType) {
/*------------------------------------------------------------------------------------------------------------------------
| Attempt to create specific type
\-----------------------------------------------------------------------------------------------------------------------*/
if (!targetType.IsInterface && !targetType.IsAbstract) {
return (IList?)Activator.CreateInstance(targetType);
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle types that don't implement IList or IEnumerable
\-----------------------------------------------------------------------------------------------------------------------*/
if (!targetType.IsGenericType) {
return null;
}
/*------------------------------------------------------------------------------------------------------------------------
| Attempt to create generic list
\-----------------------------------------------------------------------------------------------------------------------*/
var parameters = targetType.GetGenericArguments();
if (parameters.Length != 1) {
return null;
}
var genericType = typeof(List<>);
var concreteType = genericType.MakeGenericType(parameters);
return (IList?)Activator.CreateInstance(concreteType);
}
/*==========================================================================================================================
| PRIVATE: SET COLLECTION VALUE
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Given a collection property, identifies a source collection, maps the values to DTOs, and attempts to add them to the
/// target collection.
/// </summary>
/// <remarks>
/// Given a collection <paramref name="memberAccessor"/> on a <paramref name="target"/> DTO, attempts to identify a source
/// collection on the <paramref name="source"/>. Collections can be mapped to <see cref="Topic.Children"/>, <see
/// cref="Topic.Relationships"/>, <see cref="Topic.IncomingRelationships"/> or to a nested topic (which will be part of
/// <see cref="Topic.Children"/>). By default, <see cref="TopicMappingService"/> will attempt to map based on the
/// property name, though this behavior can be modified using the <paramref name="memberAccessor"/>, based on annotations
/// on the <paramref name="target"/> DTO.
/// </remarks>
/// <param name="source">The source <see cref="Topic"/> from which to pull the value.</param>
/// <param name="target">The target DTO on which to set the property value.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="memberAccessor">The <see cref="MemberAccessor"/> with details about the property's attributes.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
private async Task SetCollectionValueAsync(
Topic source,
object target,
AssociationTypes associations,
MemberAccessor memberAccessor,
MappedTopicCache cache,
string? attributePrefix
) {
/*------------------------------------------------------------------------------------------------------------------------
| Ensure target list is created
\-----------------------------------------------------------------------------------------------------------------------*/
var targetList = (IList?)memberAccessor.GetValue(target);
if (targetList is null) {
targetList = InitializeCollection(memberAccessor.Type);
memberAccessor.SetValue(target, targetList);
}
Contract.Assume(
targetList,
$"The target list type, '{memberAccessor.Type}', could not be properly constructed, as required to " +
$"map the '{memberAccessor.Name}' property on the '{target?.GetType().Name}' object."
);
/*------------------------------------------------------------------------------------------------------------------------
| Establish source collection to store topics to be mapped
\-----------------------------------------------------------------------------------------------------------------------*/
var sourceList = GetSourceCollection(source, associations, memberAccessor, attributePrefix);
/*------------------------------------------------------------------------------------------------------------------------
| Validate that source collection was identified
\-----------------------------------------------------------------------------------------------------------------------*/
if (sourceList is null) return;
/*------------------------------------------------------------------------------------------------------------------------
| Map the topics from the source collection, and add them to the target collection
\-----------------------------------------------------------------------------------------------------------------------*/
await PopulateTargetCollectionAsync(sourceList, targetList, memberAccessor, cache).ConfigureAwait(false);
}
/*==========================================================================================================================
| PRIVATE: GET SOURCE COLLECTION
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Given a source topic and a property configuration, attempts to identify a source collection that maps to the property.
/// </summary>
/// <remarks>
/// Given a collection <paramref name="itemMetadata"/> on a target DTO, attempts to identify a source collection on the
/// <paramref name="source"/>. Collections can be mapped to <see cref="Topic.Children"/>, <see
/// cref="Topic.Relationships"/>, <see cref="Topic.IncomingRelationships"/> or to a nested topic (which will be part of
/// <see cref="Topic.Children"/>). By default, <see cref="TopicMappingService"/> will attempt to map based on the
/// property name, though this behavior can be modified using the <paramref name="itemMetadata"/>, based on annotations
/// on the target DTO.
/// </remarks>
/// <param name="source">The source <see cref="Topic"/> from which to pull the value.</param>
/// <param name="associations">Determines what associations the mapping should include, if any.</param>
/// <param name="itemMetadata">The <see cref="ItemMetadata"/> with details about the property's attributes.</param>
/// <param name="attributePrefix">The prefix to apply to the attributes.</param>
private IList<Topic> GetSourceCollection(
Topic source,
AssociationTypes associations,
ItemMetadata itemMetadata,
string? attributePrefix
) {
/*------------------------------------------------------------------------------------------------------------------------
| Establish source collection to store topics to be mapped
\-----------------------------------------------------------------------------------------------------------------------*/
var configuration = itemMetadata.Configuration;
var listSource = (IList<Topic>)Array.Empty<Topic>();
var collectionKey = configuration.CollectionKey;
var collectionType = configuration.CollectionType;
/*------------------------------------------------------------------------------------------------------------------------
| Handle children
\-----------------------------------------------------------------------------------------------------------------------*/
listSource = getCollection(
CollectionType.Children,
s => true,
() => source.Children.ToList()
);
/*------------------------------------------------------------------------------------------------------------------------
| Handle (outgoing) relationships
\-----------------------------------------------------------------------------------------------------------------------*/
listSource = getCollection(
CollectionType.Relationship,
source.Relationships.Contains,
() => source.Relationships.GetValues(collectionKey)
);
/*------------------------------------------------------------------------------------------------------------------------
| Handle nested topics, or children corresponding to the property name
\-----------------------------------------------------------------------------------------------------------------------*/
listSource = getCollection(
CollectionType.NestedTopics,
source.Children.Contains,
() => source.Children[collectionKey].Children
);
/*------------------------------------------------------------------------------------------------------------------------
| Handle (incoming) relationships
\-----------------------------------------------------------------------------------------------------------------------*/
listSource = getCollection(
CollectionType.IncomingRelationship,
source.IncomingRelationships.Contains,
() => source.IncomingRelationships.GetValues(collectionKey)
);
/*------------------------------------------------------------------------------------------------------------------------
| Handle other strongly typed source collections
\-----------------------------------------------------------------------------------------------------------------------*/
//The following allows a target collection to be mapped to an IList<Topic> source collection. This is valuable for custom,
//curated collections defined on e.g. derivatives of Topic, but which don't otherwise map to a specific collection type.
//For example, the ContentTypeDescriptor's AttributeDescriptors collection, which provides a rollup of
//AttributeDescriptors from the current ContentTypeDescriptor, as well as all of its ascendents.
if (listSource.Count == 0) {
var sourceProperty = TypeAccessorCache.GetTypeAccessor(source.GetType()).GetMember(configuration.GetCompositeAttributeKey(attributePrefix));
if (
sourceProperty?.GetValue(source) is IList sourcePropertyValue &&
sourcePropertyValue.Count > 0 &&
sourcePropertyValue[0] is Topic
) {
listSource = getCollection(
CollectionType.MappedCollection,
s => true,
() => sourcePropertyValue.Cast<Topic>().ToList()
);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle Metadata relationship
\-----------------------------------------------------------------------------------------------------------------------*/
if (listSource.Count == 0 && !String.IsNullOrWhiteSpace(configuration.MetadataKey)) {
var metadataKey = $"Root:Configuration:Metadata:{configuration.MetadataKey}:LookupList";
var metadataParent = _topicRepository.Load(metadataKey, source);
if (metadataParent is not null) {
listSource = metadataParent.Children.ToList();
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle flattening of children
\-----------------------------------------------------------------------------------------------------------------------*/
if (configuration.FlattenChildren) {
var flattenedList = new List<Topic>();
listSource.ToList().ForEach(t => FlattenTopicGraph(t, flattenedList));
listSource = flattenedList;
}
return listSource;
/*------------------------------------------------------------------------------------------------------------------------
| Provide local function for evaluating current collection
\-----------------------------------------------------------------------------------------------------------------------*/
IList<Topic> getCollection(CollectionType collection, Func<string, bool> contains, Func<IList<Topic>> getTopics) {
var targetAssociations = AssociationMap.Mappings[collection];
var preconditionsMet =
listSource.Count == 0 &&
(collectionType is CollectionType.Any || collectionType.Equals(collection)) &&
(collectionType is CollectionType.Children || collection is not CollectionType.Children) &&
(targetAssociations is AssociationTypes.None || associations.HasFlag(targetAssociations)) &&
contains(configuration.CollectionKey);
return preconditionsMet? getTopics() : listSource;
}
}
/*==========================================================================================================================
| PRIVATE: POPULATE TARGET COLLECTION
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Given a source list, will populate a target list based on the configured behavior of the target property.
/// </summary>
/// <param name="sourceList">The <see cref="IList{Topic}"/> to pull the source <see cref="Topic"/> objects from.</param>
/// <param name="targetList">The target <see cref="IList"/> to add the mapped <see cref="Topic"/> objects to.</param>
/// <param name="itemMetadata">The <see cref="ItemMetadata"/> with details about the property's attributes.</param>
/// <param name="cache">A cache to keep track of already-mapped object instances.</param>
private async Task PopulateTargetCollectionAsync(
IList<Topic> sourceList,
IList targetList,
ItemMetadata itemMetadata,
MappedTopicCache cache
) {
/*------------------------------------------------------------------------------------------------------------------------
| Establish configuration
\-----------------------------------------------------------------------------------------------------------------------*/
var configuration = itemMetadata.Configuration;
/*------------------------------------------------------------------------------------------------------------------------
| Determine the type of item in the list
\-----------------------------------------------------------------------------------------------------------------------*/
var listType = typeof(ITopicViewModel);
foreach (var type in targetList.GetType().GetInterfaces()) {
if (type.IsGenericType && typeof(IList<>) == type.GetGenericTypeDefinition()) {
//Uses last argument in case it's a KeyedCollection; in that case, we want the TItem type
listType = type.GetGenericArguments().Last();
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Queue up mapping tasks
\-----------------------------------------------------------------------------------------------------------------------*/
var taskQueue = new List<Task<object?>>();
foreach (var childTopic in sourceList) {
//Ensure the source topic isn't disabled; disabled topics should never be returned to the presentation layer unless
//explicitly requested by a top-level request.
if (childTopic.IsDisabled) {
continue;
}
//Skip nested topics; those should be explicitly mapped to their own collection or topic reference
if (childTopic.ContentType.Equals("List", StringComparison.OrdinalIgnoreCase)) {
continue;
}
//Ensure the source topic matches any [FilterByContentType()] settings
if (
configuration.ContentTypeFilter is not null &&
!childTopic.ContentType.Equals(configuration.ContentTypeFilter, StringComparison.OrdinalIgnoreCase)
) {
continue;
}
//Ensure the source topic matches any [FilterByAttribute()] settings
if (!configuration.SatisfiesAttributeFilters(childTopic)) {
continue;
}
//Map child topic to target DTO
var childDto = (object)childTopic;
if (!typeof(Topic).IsAssignableFrom(listType)) {
var mappingType = GetValidatedMappingType(configuration.MapAs, listType)?? GetValidatedMappingType(childTopic, listType);
if (mappingType is not null) {
taskQueue.Add(MapAsync(childTopic, mappingType, configuration.IncludeAssociations, cache));
}
}
else {
addToList(childDto);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Process mapping tasks
\-----------------------------------------------------------------------------------------------------------------------*/
while (taskQueue.Count > 0) {
var dtoTask = await Task.WhenAny(taskQueue).ConfigureAwait(false);
var dto = await dtoTask.ConfigureAwait(false);
taskQueue.Remove(dtoTask);
if (dto is not null) {
addToList(dto);
}
}