-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathActivityInputValidation.cs
More file actions
62 lines (54 loc) · 2.57 KB
/
Copy pathActivityInputValidation.cs
File metadata and controls
62 lines (54 loc) · 2.57 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
namespace Elsa.DevOps.AzureDevOps.Activities;
/// <summary>
/// Helpers for validating activity inputs. Use Try* in CanExecuteAsync; use Throw* in ExecuteAsync/GetConnection as a safety net.
/// </summary>
internal static class ActivityInputValidation
{
public static (bool Valid, string? Error) TryValidateRequired(string? value, string parameterName)
{
if (string.IsNullOrWhiteSpace(value))
return (false, $"'{parameterName}' must be specified and non-empty.");
return (true, null);
}
public static (bool Valid, string? Error) TryValidateUri(string? value, string parameterName)
{
var (requiredOk, requiredErr) = TryValidateRequired(value, parameterName);
if (!requiredOk) return (false, requiredErr);
if (!Uri.TryCreate(value!.Trim(), UriKind.Absolute, out var uri) || !uri.IsAbsoluteUri || (uri.Scheme != "http" && uri.Scheme != "https"))
return (false, $"'{parameterName}' must be a valid HTTP or HTTPS URL.");
return (true, null);
}
public static (bool Valid, string? Error) TryValidateNonNegative(int value, string parameterName)
{
if (value < 0)
return (false, $"'{parameterName}' must be non-negative.");
return (true, null);
}
public static (bool Valid, string? Error) TryValidatePositive(int value, string parameterName)
{
if (value <= 0)
return (false, $"'{parameterName}' must be greater than zero.");
return (true, null);
}
public static void ThrowIfNullOrEmpty(string? value, string parameterName)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException($"'{parameterName}' must be specified and non-empty.", parameterName);
}
public static void ThrowIfInvalidUri(string? value, string parameterName)
{
ThrowIfNullOrEmpty(value, parameterName);
if (!Uri.TryCreate(value!.Trim(), UriKind.Absolute, out var uri) || !uri.IsAbsoluteUri || (uri.Scheme != "http" && uri.Scheme != "https"))
throw new ArgumentException($"'{parameterName}' must be a valid HTTP or HTTPS URL.", parameterName);
}
public static void ThrowIfNegative(int value, string parameterName)
{
if (value < 0)
throw new ArgumentOutOfRangeException(parameterName, value, $"'{parameterName}' must be non-negative.");
}
public static void ThrowIfNegativeOrZero(int value, string parameterName)
{
if (value <= 0)
throw new ArgumentOutOfRangeException(parameterName, value, $"'{parameterName}' must be greater than zero.");
}
}