aboutsummaryrefslogtreecommitdiffstats
path: root/src/server/Utilities/ExtensionMethods.cs
blob: d6bce941895397e14ee0373768d07854ac71f197 (plain) (blame)
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
using System;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;

namespace Dough.Utilities
{
    public static class ExtentionMethods
    {
        public static Guid ToGuidOrDefault(this string value)
        {
            if (value.IsMissing()) return default;
            try
            {
                return new Guid(value);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return default;
            }
        }

        public static DateTime ToDateTimeOrDefault(this string value)
        {
            if (value.IsMissing()) return default;
            try
            {
                return DateTime.Parse(value);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return default;
            }
        }

        public static bool IsMissing(this string value) => string.IsNullOrWhiteSpace(value);
        public static bool IsPresent(this string value) => !value.IsMissing();

        public static bool IsValidUrl(this string value)
        {
            return Uri.TryCreate(value, UriKind.Absolute, out var uriResult)
                   && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
        }

        public static string GetClaimValueOrDefault(this IPrincipal currentPrincipal, string claimName)
        {
            var identity = currentPrincipal.Identity as ClaimsIdentity;
            var claim = identity?.Claims.SingleOrDefault(c => c.Type == claimName);
            return claim?.Value;
        }
    }
}