-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommonHelper.cs
More file actions
314 lines (257 loc) · 11.6 KB
/
CommonHelper.cs
File metadata and controls
314 lines (257 loc) · 11.6 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
namespace AspNetCore.Container;
/// <summary>
/// Represents a common helper
/// </summary>
public partial class AspNetCoreContainerHelper
{
#region Fields
//we use EmailValidator from FluentValidation. So let's keep them sync - https://github.com/JeremySkinner/FluentValidation/blob/master/src/FluentValidation/Validators/EmailValidator.cs
private const string EMAIL_EXPRESSION = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-||_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+([a-z]+|\d|-|\.{0,1}|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])?([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$";
private static readonly Regex _emailRegex;
#endregion
#region Ctor
static AspNetCoreContainerHelper()
{
_emailRegex = new Regex(EMAIL_EXPRESSION, RegexOptions.IgnoreCase);
}
#endregion
#region Methods
/// <summary>
/// Ensures the subscriber email or throw.
/// </summary>
/// <param name="email">The email.</param>
/// <returns></returns>
public static string EnsureSubscriberEmailOrThrow(string email)
{
string output = EnsureNotNull(email);
output = output.Trim();
output = EnsureMaximumLength(output, 255);
return !IsValidEmail(output) ? throw new Exception("Email is not valid.") : output;
}
/// <summary>
/// Verifies that a string is in valid e-mail format
/// </summary>
/// <param name="email">Email to verify</param>
/// <returns>true if the string is a valid e-mail address and false if it's not</returns>
public static bool IsValidEmail(string email)
{
if (string.IsNullOrEmpty(email))
return false;
email = email.Trim();
return _emailRegex.IsMatch(email);
}
/// <summary>
/// Verifies that string is an valid IP-Address
/// </summary>
/// <param name="ipAddress">IPAddress to verify</param>
/// <returns>true if the string is a valid IpAddress and false if it's not</returns>
public static bool IsValidIpAddress(string ipAddress) => IPAddress.TryParse(ipAddress, out IPAddress _);
/// <summary>
/// Generate random digit code
/// </summary>
/// <param name="length">Length</param>
/// <returns>Result string</returns>
public static string GenerateRandomDigitCode(int length)
{
using SecureRandomNumberGenerator random = new();
string str = string.Empty;
for (int i = 0; i < length; i++)
str = string.Concat(str, random.Next(10).ToString());
return str;
}
/// <summary>
/// Returns an random integer number within a specified rage
/// </summary>
/// <param name="min">Minimum number</param>
/// <param name="max">Maximum number</param>
/// <returns>Result</returns>
public static int GenerateRandomInteger(int min = 0, int max = int.MaxValue)
{
using SecureRandomNumberGenerator random = new();
return random.Next(min, max);
}
/// <summary>
/// Ensure that a string doesn't exceed maximum allowed length
/// </summary>
/// <param name="str">Input string</param>
/// <param name="maxLength">Maximum length</param>
/// <param name="postfix">A string to add to the end if the original string was shorten</param>
/// <returns>Input string if its length is OK; otherwise, truncated input string</returns>
public static string EnsureMaximumLength(string str, int maxLength, string? postfix = null)
{
if (string.IsNullOrEmpty(str))
return str;
if (str.Length <= maxLength)
return str;
int pLen = postfix?.Length ?? 0;
string result = str[..(maxLength - pLen)];
if (!string.IsNullOrEmpty(postfix))
result += postfix;
return result;
}
/// <summary>
/// Ensures that a string only contains numeric values
/// </summary>
/// <param name="str">Input string</param>
/// <returns>Input string with only numeric values, empty string if input is null/empty</returns>
public static string EnsureNumericOnly(string str)
=> string.IsNullOrEmpty(str) ? string.Empty : new string(str.Where(char.IsDigit).ToArray());
/// <summary>
/// Ensure that a string is not null
/// </summary>
/// <param name="str">Input string</param>
/// <returns>Result</returns>
public static string EnsureNotNull(string str)
=> str ?? string.Empty;
/// <summary>
/// Indicates whether the specified strings are null or empty strings
/// </summary>
/// <param name="stringsToValidate">Array of strings to validate</param>
/// <returns>Boolean</returns>
public static bool AreNullOrEmpty(params string[] stringsToValidate)
=> stringsToValidate.Any(string.IsNullOrEmpty);
/// <summary>
/// Compare two arrays
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="a1">Array 1</param>
/// <param name="a2">Array 2</param>
/// <returns>Result</returns>
public static bool ArraysEqual<T>(T[] a1, T[] a2)
{
//also see Enumerable.SequenceEqual(a1, a2);
if (ReferenceEquals(a1, a2))
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
return !a1.Where((t, i) => !comparer.Equals(t, a2[i])).Any();
}
/// <summary>
/// Sets a property on an object to a value.
/// </summary>
/// <param name="instance">The object whose property to set.</param>
/// <param name="propertyName">The name of the property to set.</param>
/// <param name="value">The value to set the property to.</param>
public static void SetProperty(object instance, string propertyName, object? value)
{
if (instance == null)
throw new ArgumentNullException(nameof(instance));
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
Type instanceType = instance.GetType();
PropertyInfo? pi = instanceType.GetProperty(propertyName);
if (pi == null)
throw new Exception("No property '{0}' found on the instance of type '{1}'.");
if (!pi.CanWrite)
throw new Exception("The property '{0}' on the instance of type '{1}' does not have a setter.");
if (value != null && !value.GetType().IsAssignableFrom(pi.PropertyType))
value = To(value, pi.PropertyType);
pi.SetValue(instance, value, Array.Empty<object>());
}
/// <summary>
/// Converts a value to a destination type.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="destinationType">The type to convert the value to.</param>
/// <returns>The converted value.</returns>
public static object? To(object? value, Type? destinationType)
=> To(value, destinationType, CultureInfo.InvariantCulture);
/// <summary>
/// Converts a value to a destination type.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="destinationType">The type to convert the value to.</param>
/// <param name="culture">Culture</param>
/// <returns>The converted value.</returns>
public static object? To(object? value, Type? destinationType, CultureInfo culture)
{
if (value == null || destinationType == null)
return null;
Type sourceType = value.GetType();
TypeConverter destinationConverter = TypeDescriptor.GetConverter(destinationType);
if (destinationConverter.CanConvertFrom(value.GetType()))
return destinationConverter.ConvertFrom(null, culture, value);
TypeConverter sourceConverter = TypeDescriptor.GetConverter(sourceType);
return sourceConverter.CanConvertTo(destinationType)
? sourceConverter.ConvertTo(null, culture, value, destinationType)
: destinationType.IsEnum && value is int @int
? Enum.ToObject(destinationType, @int)
: !destinationType.IsInstanceOfType(value) ? Convert.ChangeType(value, destinationType, culture) : value;
}
/// <summary>
/// Converts a value to a destination type.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <returns>The converted value.</returns>
public static T? To<T>(object? value) =>
//return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
(T?)To(value, typeof(T?));
/// <summary>
/// Convert enum for front-end
/// </summary>
/// <param name="str">Input string</param>
/// <returns>Converted string</returns>
public static string ConvertEnum(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
string result = string.Empty;
foreach (char c in str)
if (c.ToString() != c.ToString().ToLower())
result += " " + c.ToString();
else
result += c.ToString();
//ensure no spaces (e.g. when the first letter is upper case)
result = result.TrimStart();
return result;
}
/// <summary>
/// Get difference in years
/// </summary>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
public static int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
//source: http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c
//this assumes you are looking for the western idea of age and not using East Asian reckoning.
int age = endDate.Year - startDate.Year;
if (startDate > endDate.AddYears(-age))
age--;
return age;
}
/// <summary>
/// Get private fields property value
/// </summary>
/// <param name="target">Target object</param>
/// <param name="fieldName">Field name</param>
/// <returns>Value</returns>
public static object? GetPrivateFieldValue(object target, string fieldName)
{
if (target == null)
throw new ArgumentNullException(nameof(target), "The assignment target cannot be null.");
if (string.IsNullOrEmpty(fieldName))
throw new ArgumentException("The field name cannot be null or empty.", nameof(fieldName));
Type? t = target.GetType();
FieldInfo? fi = null;
while (t != null)
{
fi = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
if (fi != null)
break;
t = t.BaseType;
}
return fi == null ? throw new Exception($"Field '{fieldName}' not found in type hierarchy.") : fi.GetValue(target);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the default file provider
/// </summary>
public static IContainerFileProvider? DefaultFileProvider { get; set; }
#endregion
}