-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblems.cs
More file actions
570 lines (488 loc) · 18.3 KB
/
Copy pathProblems.cs
File metadata and controls
570 lines (488 loc) · 18.3 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
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
using System.Collections;
using System.Runtime.CompilerServices;
namespace RoyalCode.SmartProblems;
#pragma warning disable S4050 // implement operatiors == != Equals GetHashCode
/// <summary>
/// A collection of problems that occurred in the system.
/// </summary>
public sealed class Problems : ICollection<Problem>
{
#region Global Property
/// <summary>
/// <para>
/// An exception handler to convert exceptions to problems.
/// </para>
/// <para>
/// Is used in the <see cref="InternalError(Exception)"/> method.
/// </para>
/// <para>
/// Useful to customize the creation of problems from exceptions.
/// </para>
/// </summary>
public static IExceptionHandler? ExceptionHandler { get; set; }
/// <summary>
/// <para>
/// Options to customize the creation of problems from exceptions.
/// </para>
/// <para>
/// Used in the <see cref="InternalError(Exception)"/> method.
/// </para>
/// </summary>
public static ExceptionOptions ExceptionOptions { get; } = new();
#endregion
#region implicit operators
/// <summary>
/// Convert a problem to a collection of problems.
/// </summary>
/// <param name="problem"></param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Problems(Problem problem) => [problem];
/// <summary>
/// Convert a <see cref="Problem"/> to a <see cref="Task"/> of <see cref="Result"/>.
/// </summary>
/// <param name="problems"></param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Task<Result>(Problems problems) => Task.FromResult(new Result(problems));
/// <summary>
/// Add a problem to the collection of problems.
/// </summary>
/// <param name="collection">The collection of problems.</param>
/// <param name="problem">The problem to add.</param>
/// <returns>The same instance of the collection with the problem added.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Problems operator +(Problems collection, Problem problem)
{
collection.Add(problem);
return collection;
}
/// <summary>
/// Add a problem to the collection of problems.
/// </summary>
/// <param name="collection">The collection of problems.</param>
/// <param name="problems">Other collection of problems to add.</param>
/// <returns>The same instance of the collection with the problem added.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Problems operator +(Problems collection, IEnumerable<Problem> problems)
{
collection.AddRange(problems);
return collection;
}
#endregion
#region Factory Methods
/// <summary>
/// Create a new problem of NotFound category.
/// </summary>
/// <param name="detail">The detail of the problem, a description message for users.</param>
/// <param name="property">Optional, the property that the problem is related to.</param>
/// <param name="typeId">Optional, the type id of the problem, related to the problem details type.</param>
/// <returns>A new problem.</returns>
public static Problem NotFound(string detail, string? property = null, string? typeId = null)
{
return new Problem
{
Category = ProblemCategory.NotFound,
Detail = detail,
Property = property,
TypeId = typeId
};
}
/// <summary>
/// Create a new problem of InvalidParameter category.
/// </summary>
/// <param name="detail">The detail of the problem, a description message for users.</param>
/// <param name="property">Optional, the property that the problem is related to.</param>
/// <param name="typeId">Optional, the type id of the problem, related to the problem details type.</param>
/// <returns>A new problem.</returns>
public static Problem InvalidParameter(string detail, string? property = null, string? typeId = null)
{
return new Problem
{
Category = ProblemCategory.InvalidParameter,
Detail = detail,
Property = property,
TypeId = typeId
};
}
/// <summary>
/// Create a new problem of ValidationFailed category.
/// </summary>
/// <param name="detail">The detail of the problem, a description message for users.</param>
/// <param name="property">Optional, the property that the problem is related to.</param>
/// <param name="typeId">Optional, the type id of the problem, related to the problem details type.</param>
/// <returns>A new problem.</returns>
public static Problem ValidationFailed(string detail, string? property = null, string? typeId = null)
{
return new Problem
{
Category = ProblemCategory.ValidationFailed,
Detail = detail,
Property = property,
TypeId = typeId
};
}
/// <summary>
/// Create a new problem of Not Allowed category.
/// </summary>
/// <param name="detail">The detail of the problem, a description message for users.</param>
/// <param name="property">Optional, the property that the problem is related to.</param>
/// <param name="typeId">Optional, the type id of the problem, related to the problem details type.</param>
/// <returns>A new problem.</returns>
public static Problem NotAllowed(string detail, string? property = null, string? typeId = null)
{
return new Problem
{
Category = ProblemCategory.NotAllowed,
Detail = detail,
Property = property,
TypeId = typeId
};
}
/// <summary>
/// Create a new problem of InvalidState category.
/// </summary>
/// <param name="detail">The detail of the problem, a description message for users.</param>
/// <param name="property">Optional, the property that the problem is related to.</param>
/// <param name="typeId">Optional, the type id of the problem, related to the problem details type.</param>
/// <returns>A new problem.</returns>
public static Problem InvalidState(string detail, string? property = null, string? typeId = null)
{
return new Problem
{
Category = ProblemCategory.InvalidState,
Detail = detail,
Property = property,
TypeId = typeId
};
}
/// <summary>
/// Create a new problem of InternalServerError category.
/// </summary>
/// <param name="detail">The detail of the problem, a description message for users.</param>
/// <param name="typeId">Optional, the type id of the problem, related to the problem details type.</param>
/// <param name="property">Optional, the property that the problem is related to.</param>
/// <returns>A new problem.</returns>
public static Problem InternalError(string? detail, string? typeId = null, string? property = null)
{
return new Problem
{
Category = ProblemCategory.InternalServerError,
Detail = detail ?? R.InternalServerErrorMessage,
TypeId = typeId,
Property = property
};
}
/// <summary>
/// Create a new problem of InternalServerError category.
/// </summary>
/// <param name="exception">The exception that occurred. When null, a default message is used.</param>
/// <returns>A new problem.</returns>
public static Problem InternalError(Exception? exception = null) => InternalError(exception, ExceptionOptions);
/// <summary>
/// Create a new problem of InternalServerError category.
/// </summary>
/// <param name="exception">The exception that occurred.</param>
/// <param name="options">The options to customize the creation of problems from exceptions.</param>
/// <returns>A new problem.</returns>
public static Problem InternalError(Exception? exception, ExceptionOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (exception is null)
{
return new Problem
{
Category = ProblemCategory.InternalServerError,
Detail = options.DefaultExceptionMessage
};
}
if (ExceptionHandler?.TryHandle(exception, out var problem) is true)
return problem;
var detail = options.UseExceptionMessageAsDetail
? exception.Message
: options.DefaultExceptionMessage;
var property = exception is ArgumentException argumentException
? argumentException.ParamName
: null;
problem = new Problem
{
Category = ProblemCategory.InternalServerError,
Detail = detail,
Property = property
};
if (options.IncludeExceptionTypeName)
problem.With("exception", exception.GetType().FullName);
if (options.IncludeStackTrace)
problem.With("stack_trace", exception.StackTrace);
return problem;
}
/// <summary>
/// Create a new problem of Custom category.
/// </summary>
/// <param name="detail">The detail of the problem, a description message for users.</param>
/// <param name="typeId">Required, the type id of the problem, related to the problem details type.</param>
/// <param name="property">Optional, the property that the problem is related to.</param>
/// <returns>A new problem.</returns>
/// <exception cref="ArgumentException">
/// Callers must provide a type id for custom problems.
/// <br/>
/// The type id must be a valid URI part.
/// </exception>
public static Problem Custom(string detail, string typeId, string? property = null)
{
if (string.IsNullOrWhiteSpace(typeId))
throw new ArgumentException(R.TypeIdIsRequired, nameof(typeId));
// type must be a valid URI part
if (!Uri.IsWellFormedUriString(typeId, UriKind.Relative))
throw new ArgumentException(R.TypeIdMustBeValidUri, nameof(typeId));
return new Problem
{
Category = ProblemCategory.CustomProblem,
Detail = detail,
TypeId = typeId,
Property = property
};
}
/// <summary>
/// Create a builder for a problem.
/// </summary>
/// <param name="details"></param>
/// <returns></returns>
public static DetailBuilder Detail(string details) => new() { Details = details };
#endregion
#region ICollection Implementation
private Problem? firstProblem;
private Node? head;
private Node? tail;
/// <summary>
/// Get the problem at the specified index.
/// </summary>
/// <param name="index">The index of the problem.</param>
/// <returns>A problem at the specified index.</returns>
/// <exception cref="IndexOutOfRangeException">
/// Check if the index is out of range.
/// </exception>
public Problem this[int index]
{
get
{
#pragma warning disable S112
if (index < 0 || index >= Count)
throw new IndexOutOfRangeException();
if (index == 0)
return firstProblem!;
return head![index - 1];
}
}
/// <inheritdoc />
public IEnumerator<Problem> GetEnumerator()
{
if (firstProblem is not null)
{
yield return firstProblem;
}
if (head is null)
yield break;
var current = head;
while (current is not null)
{
yield return current.Problem;
current = current.Next;
}
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <inheritdoc />
public void Add(Problem item)
{
ArgumentNullException.ThrowIfNull(item);
Count++;
if (firstProblem is null)
{
firstProblem = item;
return;
}
if (head is null)
{
head = new(item);
tail = head;
}
else
{
tail = tail!.MakeNext(item);
}
}
/// <summary>
/// Add a range of problems to the collection.
/// </summary>
/// <param name="problems">A collection of problems to add.</param>
public void AddRange(IEnumerable<Problem> problems)
{
ArgumentNullException.ThrowIfNull(problems);
foreach (var problem in problems)
{
Add(problem);
}
}
/// <summary>
/// Not supported.
/// </summary>
/// <exception cref="NotSupportedException"></exception>
public void Clear()
{
throw new NotSupportedException();
}
/// <inheritdoc />
public bool Contains(Problem item)
{
return Equals(firstProblem, item) || head is not null && head.Contains(item);
}
/// <inheritdoc />
public void CopyTo(Problem[] array, int arrayIndex)
{
if (Count == 0)
return;
if (arrayIndex + Count > array.Length)
throw new ArgumentException(R.CopyToArgumentErrorMessage, nameof(array));
array[arrayIndex] = firstProblem!;
head?.CopyTo(array, arrayIndex + 1);
}
/// <summary>
/// Not supported.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
/// <exception cref="NotSupportedException"></exception>
public bool Remove(Problem item)
{
throw new NotSupportedException();
}
/// <inheritdoc />
public int Count { get; private set; }
/// <summary>
/// False, the collection is not read-only.
/// </summary>
public bool IsReadOnly => false;
private sealed class Node
{
public Problem Problem { get; }
public Node? Next { get; private set; }
public Node(Problem problem)
{
Problem = problem;
}
public Node MakeNext(Problem problem)
{
Next = new(problem);
return Next;
}
public bool Contains(Problem problem)
{
return Equals(Problem, problem) || Next is not null && Next.Contains(problem);
}
public void CopyTo(Problem[] array, int arrayIndex)
{
array[arrayIndex] = Problem;
Next?.CopyTo(array, arrayIndex + 1);
}
public Problem this[int index]
{
get
{
if (index == 0)
return Problem;
return Next![index - 1];
}
}
}
#endregion
/// <summary>
/// Creates an <see cref="InvalidOperationException"/> from the collection of problems.
/// The exception message will contain the details of all problems in the collection.
/// </summary>
/// <returns>A new instance of <see cref="InvalidOperationException"/>.</returns>
public InvalidOperationException ToException()
{
return new InvalidOperationException(string.Join("\n", this.Select(p => p.ToString())));
}
/// <summary>
/// Creates an <see cref="InvalidOperationException"/> from the collection of problems.
/// The exception message will be formatted using the provided pattern,
/// where the first argument is the details of all problems in the collection.
/// </summary>
/// <remarks>
/// The message pattern should contain a single placeholder (e.g., <c>"{0}"</c>, <c>"Errors: {0}"</c>),
/// </remarks>
/// <param name="messagePattern">The message pattern to format the exception message.</param>
/// <param name="separator">The separator to use between problem details in the message, optional, defaults to newline character.</param>
/// <returns>A new instance of <see cref="InvalidOperationException"/>.</returns>
public InvalidOperationException ToException(string messagePattern, string separator = "\n")
{
var message = string.Format(messagePattern, string.Join(separator, this.Select(p => p.ToString())));
return new InvalidOperationException(message);
}
/// <summary>
/// Execute the specified action for each problem in the collection.
/// </summary>
/// <param name="action">The action to execute for each problem.</param>
/// <returns>
/// The same instance of the collection, to allow method chaining.
/// </returns>
public Problems ForEach(Action<Problem> action)
{
ArgumentNullException.ThrowIfNull(action);
if (Count == 0)
return this;
action(firstProblem!);
if (Count == 1)
return this;
var current = head;
while (current is not null)
{
action(current.Problem);
current = current.Next;
}
return this;
}
/// <summary>
/// Execute the specified action for each problem in the collection, passing an additional parameter.
/// </summary>
/// <typeparam name="T">The type of the additional parameter.</typeparam>
/// <param name="param">The additional parameter to pass to the action.</param>
/// <param name="action">The action to execute for each problem, with the additional parameter.</param>
/// <returns>The same instance of the collection, to allow method chaining.</returns>
public Problems ForEach<T>(T param, Action<T, Problem> action)
{
ArgumentNullException.ThrowIfNull(param);
ArgumentNullException.ThrowIfNull(action);
if (Count == 0)
return this;
action(param, firstProblem!);
if (Count == 1)
return this;
var current = head;
while (current is not null) {
action(param, current.Problem);
current = current.Next;
}
return this;
}
/// <summary>
/// Convert the collection of problems to a <see cref="Result"/> instance.
/// </summary>
/// <returns></returns>
public Result AsResult()
{
return new Result(this);
}
/// <summary>
/// Convert the collection of problems to a <see cref="Result{TValue}"/> instance with the specified value.
/// </summary>
/// <typeparam name="TValue"></typeparam>
/// <returns></returns>
public Result<TValue> AsResult<TValue>()
{
return new Result<TValue>(this);
}
}