Skip to content

Commit eb2af4f

Browse files
committed
Fluent Extensions
1 parent 18f81d7 commit eb2af4f

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

src/Extensions/DictionaryExtensions.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,12 @@ public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValu
3535

3636
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> dict) =>
3737
dict.ToDictionary(x => x.Key, x => x.Value);
38+
39+
public static void AddIfNotDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
40+
where TValue : class
41+
{
42+
if (value != default)
43+
dictionary.Add(key, value);
44+
}
3845
}
3946
}

src/Extensions/Extensions.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66

77
<ItemGroup>
88
<PackageReference Include="EPPlus" Version="4.5.3.3" />
9+
<PackageReference Include="FluentValidation" Version="11.0.2" />
910
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
11+
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
1012
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="6.0.3" />
1113
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.3" />
1214
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using FluentValidation;
5+
using Microsoft.AspNetCore.Mvc;
6+
7+
namespace Extensions
8+
{
9+
public static class FluentValidatorExtensions
10+
{
11+
public static IRuleBuilderOptions<T, string> IsValidUrl<T>(this IRuleBuilder<T, string> ruleBuilder)
12+
{
13+
return ruleBuilder
14+
.Must(x => Uri.IsWellFormedUriString(x, UriKind.Absolute))
15+
.WithMessage("{PropertyName} is not a valid url");
16+
}
17+
18+
public static ValidationProblemDetails ToProblemDetails(this ValidationException ex)
19+
{ // scopiazzatissimo da nick chapsas
20+
var error = new ValidationProblemDetails
21+
{
22+
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
23+
Status = 400
24+
};
25+
26+
foreach (var validationFailure in ex.Errors)
27+
{
28+
if (error.Errors.ContainsKey(validationFailure.PropertyName))
29+
{
30+
error.Errors[validationFailure.PropertyName] = error.Errors[validationFailure.PropertyName].Concat(new[] { validationFailure.ErrorMessage }).ToArray();
31+
continue;
32+
}
33+
34+
error.Errors.Add(new KeyValuePair<string, string[]>(
35+
validationFailure.PropertyName,
36+
new[] { validationFailure.ErrorMessage }));
37+
}
38+
39+
return error;
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)