-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHierarchicalTopicMappingService{T}.cs
More file actions
219 lines (194 loc) · 11.9 KB
/
HierarchicalTopicMappingService{T}.cs
File metadata and controls
219 lines (194 loc) · 11.9 KB
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
/*==============================================================================================================================
| Author Ignia, LLC
| Client Ignia, LLC
| Project Topics Library
\=============================================================================================================================*/
using OnTopic.Mapping.Annotations;
using OnTopic.Models;
using OnTopic.Repositories;
namespace OnTopic.Mapping.Hierarchical {
/*============================================================================================================================
| CLASS: NAVIGATION MAPPING SERVICE
\---------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Implements a service that maps a limited-hierarchy of topics to a generic class representing the core properties
/// associated with a navigation item.
/// </summary>
/// <remarks>
/// <para>
/// Ideally, this functionality would be baked directly into the <see cref="ITopicMappingService"/> implementations, but
/// this introduces a number of technical issues that make this unfeasible for now. Instead, the <see
/// cref="IHierarchicalTopicMappingService{T}"/> handles this functionality for special cases, such as navigation, where
/// e.g. the full recursion of the <see cref="ITopicMappingService"/> is not preferrable for functional or performance
/// reasons.
/// </para>
/// <para>
/// In order to remain view model agnostic, the <see cref="HierarchicalTopicMappingService{T}"/> does not assume that a
/// particular view model will be used, and instead accepts a generic argument for any view model that implements the
/// interface <see cref="IHierarchicalTopicViewModel{T}"/>.
/// </para>
/// </remarks>
/// <typeparam name="T">A view model implementing the <see cref="IHierarchicalTopicViewModel{T}"/> interface.</typeparam>
public class HierarchicalTopicMappingService<T>
: IHierarchicalTopicMappingService<T>
where T : class, IHierarchicalTopicViewModel<T>, new()
{
/*==========================================================================================================================
| PRIVATE VARIABLES
\-------------------------------------------------------------------------------------------------------------------------*/
private readonly ITopicMappingService _topicMappingService;
/*==========================================================================================================================
| CONSTRUCTOR
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Initializes a new instance of a <see cref="HierarchicalTopicMappingService{T}"/> with necessary dependencies.
/// </summary>
/// <returns>A topic controller for loading OnTopic views.</returns>
public HierarchicalTopicMappingService(
ITopicRepository topicRepository,
ITopicMappingService topicMappingService
) {
TopicRepository = topicRepository;
_topicMappingService = topicMappingService;
}
/*==========================================================================================================================
| TOPIC REPOSITORY
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// Provides a reference to the Topic Repository in order to gain arbitrary access to the entire topic graph.
/// </summary>
/// <returns>The TopicRepository associated with the controller.</returns>
private ITopicRepository TopicRepository { get; }
/*==========================================================================================================================
| GET HIERARCHICAL ROOT
\-------------------------------------------------------------------------------------------------------------------------*/
/// <inheritdoc />
public Topic? GetHierarchicalRoot(Topic? currentTopic, int fromRoot = 2, string defaultRoot = "Root:Web") {
/*------------------------------------------------------------------------------------------------------------------------
| Establish variables
\-----------------------------------------------------------------------------------------------------------------------*/
var navigationRootTopic = currentTopic;
/*------------------------------------------------------------------------------------------------------------------------
| Handle default, if necessary
\-----------------------------------------------------------------------------------------------------------------------*/
if (navigationRootTopic is null) {
Contract.Assume<ArgumentNullException>(!String.IsNullOrEmpty(defaultRoot), nameof(defaultRoot));
navigationRootTopic = TopicRepository.Load(defaultRoot, currentTopic);
}
/*------------------------------------------------------------------------------------------------------------------------
| Handle error state
\-----------------------------------------------------------------------------------------------------------------------*/
if (navigationRootTopic is null) {
throw new ArgumentOutOfRangeException(
$"Neither the current route nor the {nameof(defaultRoot)} parameter of {defaultRoot} could be resolved to a topic."
);
}
/*------------------------------------------------------------------------------------------------------------------------
| Find navigation root
\-----------------------------------------------------------------------------------------------------------------------*/
while (navigationRootTopic is not null && DistanceFromRoot(navigationRootTopic) > fromRoot) {
navigationRootTopic = navigationRootTopic.Parent;
}
/*------------------------------------------------------------------------------------------------------------------------
| Return navigation root
\-----------------------------------------------------------------------------------------------------------------------*/
return navigationRootTopic;
}
/*==========================================================================================================================
| DISTANCE FROM ROOT
\-------------------------------------------------------------------------------------------------------------------------*/
/// <summary>
/// A helper function that will determine how far a given topic is from the root of a tree.
/// </summary>
/// <param name="sourceTopic">The <see cref="Topic"/> to pull the values from.</param>
private static int DistanceFromRoot(Topic sourceTopic) {
var distance = 1;
while (sourceTopic.Parent is not null) {
sourceTopic = sourceTopic.Parent;
distance++;
}
return distance;
}
/*==========================================================================================================================
| GET ROOT VIEW MODEL (ASYNC)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <inheritdoc />
public virtual async Task<T?> GetRootViewModelAsync(
Topic? sourceTopic,
int tiers = 1,
Func<Topic, bool>? validationDelegate = null
) => await GetViewModelAsync(sourceTopic, tiers, validationDelegate).ConfigureAwait(false);
/*==========================================================================================================================
| GET VIEW MODEL (ASYNC)
\-------------------------------------------------------------------------------------------------------------------------*/
/// <inheritdoc />
public async Task<T?> GetViewModelAsync(
Topic? sourceTopic,
int tiers = 1,
Func<Topic, bool>? validationDelegate = null
) {
/*------------------------------------------------------------------------------------------------------------------------
| Validate preconditions
\-----------------------------------------------------------------------------------------------------------------------*/
tiers--;
if (sourceTopic is null) {
return null;
}
/*------------------------------------------------------------------------------------------------------------------------
| Establish variables
\-----------------------------------------------------------------------------------------------------------------------*/
var taskQueue = new List<Task<T?>>();
var children = new List<T>();
var viewModel = (T?)null;
/*------------------------------------------------------------------------------------------------------------------------
| Establish default delegate
\-----------------------------------------------------------------------------------------------------------------------*/
if (validationDelegate is null) {
validationDelegate = (Topic) => true;
}
/*------------------------------------------------------------------------------------------------------------------------
| Map object
\-----------------------------------------------------------------------------------------------------------------------*/
viewModel = await _topicMappingService.MapAsync<T>(sourceTopic, AssociationTypes.None).ConfigureAwait(false);
Contract.Assume(
viewModel,
$"The 'ITopicMappingService' failed to return a {typeof(T)} model for the '{sourceTopic.GetUniqueKey()}' topic."
);
/*------------------------------------------------------------------------------------------------------------------------
| Request mapping of children
\-----------------------------------------------------------------------------------------------------------------------*/
if (tiers >= 0 && viewModel.Children.Count == 0) {
foreach (var topic in sourceTopic.Children.Where(t => t.IsVisible() && validationDelegate(t))) {
taskQueue.Add(GetViewModelAsync(topic, tiers, validationDelegate));
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Process children
\-----------------------------------------------------------------------------------------------------------------------*/
while (taskQueue.Count > 0 && viewModel.Children.Count == 0) {
var dtoTask = await Task.WhenAny(taskQueue).ConfigureAwait(false);
var dto = await dtoTask.ConfigureAwait(false);
taskQueue.Remove(dtoTask);
if (dto is not null) {
children.Add(dto);
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Add children to view model
\-----------------------------------------------------------------------------------------------------------------------*/
if (viewModel.Children.Count == 0) {
lock (viewModel) {
#pragma warning disable CA1508 // Avoid dead conditional code
if (viewModel.Children.Count == 0) {
children.ForEach(c => viewModel.Children.Add(c));
}
#pragma warning restore CA1508 // Avoid dead conditional code
}
}
/*------------------------------------------------------------------------------------------------------------------------
| Return view model
\-----------------------------------------------------------------------------------------------------------------------*/
return viewModel;
}
} //Class
} //Namespace