1
|
1 using System;
|
|
2 using System.Collections.Generic;
|
|
3 using System.Linq;
|
|
4 using System.Text;
|
51
|
5 using System.Text.RegularExpressions;
|
66
|
6 using System.Diagnostics;
|
1
|
7
|
|
8 namespace Implab
|
|
9 {
|
|
10 public static class Safe
|
|
11 {
|
51
|
12 public static void ArgumentMatch(string param, string name, Regex rx) {
|
|
13 if (rx == null)
|
|
14 throw new ArgumentNullException("rx");
|
|
15 if (!rx.IsMatch(param))
|
90
|
16 throw new ArgumentException(String.Format("The prameter value must match {0}", rx), name);
|
51
|
17 }
|
|
18
|
|
19 public static void ArgumentNotEmpty(string param, string name) {
|
|
20 if (String.IsNullOrEmpty(param))
|
90
|
21 throw new ArgumentException("The parameter can't be empty", name);
|
|
22 }
|
|
23
|
|
24 public static void ArgumentNotEmpty<T>(T[] param, string name) {
|
|
25 if (param == null || param.Length == 0)
|
|
26 throw new ArgumentException("The array must be not emty");
|
51
|
27 }
|
|
28
|
|
29 public static void ArgumentNotNull(object param, string name) {
|
|
30 if (param == null)
|
|
31 throw new ArgumentNullException(name);
|
|
32 }
|
|
33
|
55
|
34 public static void ArgumentInRange(int arg, int min, int max, string name) {
|
|
35 if (arg < min || arg > max)
|
|
36 throw new ArgumentOutOfRangeException(name);
|
|
37 }
|
|
38
|
31
|
39 public static void Dispose<T>(T obj) where T : class
|
1
|
40 {
|
2
|
41 var disp = obj as IDisposable;
|
|
42 if (disp != null)
|
|
43 disp.Dispose();
|
1
|
44 }
|
66
|
45
|
|
46 [DebuggerStepThrough]
|
94
|
47 public static IPromise<T> InvokePromise<T>(Func<T> action) {
|
66
|
48 ArgumentNotNull(action, "action");
|
|
49
|
|
50 var p = new Promise<T>();
|
|
51 try {
|
|
52 p.Resolve(action());
|
|
53 } catch (Exception err) {
|
|
54 p.Reject(err);
|
|
55 }
|
|
56
|
|
57 return p;
|
|
58 }
|
|
59
|
|
60 [DebuggerStepThrough]
|
96
|
61 public static IPromise InvokePromise(Action action) {
|
95
|
62 ArgumentNotNull(action, "action");
|
|
63
|
|
64 var p = new Promise<object>();
|
|
65 try {
|
|
66 action();
|
|
67 p.Resolve();
|
|
68 } catch (Exception err) {
|
|
69 p.Reject(err);
|
|
70 }
|
|
71
|
|
72 return p;
|
|
73 }
|
|
74
|
|
75 [DebuggerStepThrough]
|
94
|
76 public static IPromise<T> InvokePromise<T>(Func<IPromise<T>> action) {
|
66
|
77 ArgumentNotNull(action, "action");
|
|
78
|
|
79 try {
|
94
|
80 return action() ?? Promise<T>.ExceptionToPromise(new Exception("The action returned null"));
|
66
|
81 } catch (Exception err) {
|
|
82 return Promise<T>.ExceptionToPromise(err);
|
|
83 }
|
|
84 }
|
1
|
85 }
|
|
86 }
|