Safe.cs
86 lines
| 2.7 KiB
| text/x-csharp
|
CSharpLexer
/ Implab / Safe.cs
cin
|
r1 | using System; | ||
using System.Collections.Generic; | ||||
using System.Linq; | ||||
using System.Text; | ||||
cin
|
r51 | using System.Text.RegularExpressions; | ||
cin
|
r66 | using System.Diagnostics; | ||
cin
|
r1 | |||
namespace Implab | ||||
{ | ||||
public static class Safe | ||||
{ | ||||
cin
|
r51 | public static void ArgumentMatch(string param, string name, Regex rx) { | ||
if (rx == null) | ||||
throw new ArgumentNullException("rx"); | ||||
if (!rx.IsMatch(param)) | ||||
cin
|
r90 | throw new ArgumentException(String.Format("The prameter value must match {0}", rx), name); | ||
cin
|
r51 | } | ||
public static void ArgumentNotEmpty(string param, string name) { | ||||
if (String.IsNullOrEmpty(param)) | ||||
cin
|
r90 | throw new ArgumentException("The parameter can't be empty", name); | ||
} | ||||
public static void ArgumentNotEmpty<T>(T[] param, string name) { | ||||
if (param == null || param.Length == 0) | ||||
cin
|
r119 | throw new ArgumentException("The array must be not emty", name); | ||
cin
|
r51 | } | ||
public static void ArgumentNotNull(object param, string name) { | ||||
if (param == null) | ||||
throw new ArgumentNullException(name); | ||||
} | ||||
cin
|
r55 | public static void ArgumentInRange(int arg, int min, int max, string name) { | ||
if (arg < min || arg > max) | ||||
throw new ArgumentOutOfRangeException(name); | ||||
} | ||||
cin
|
r31 | public static void Dispose<T>(T obj) where T : class | ||
cin
|
r1 | { | ||
cin
|
r2 | var disp = obj as IDisposable; | ||
if (disp != null) | ||||
disp.Dispose(); | ||||
cin
|
r1 | } | ||
cin
|
r66 | |||
[DebuggerStepThrough] | ||||
cin
|
r94 | public static IPromise<T> InvokePromise<T>(Func<T> action) { | ||
cin
|
r66 | ArgumentNotNull(action, "action"); | ||
var p = new Promise<T>(); | ||||
try { | ||||
p.Resolve(action()); | ||||
} catch (Exception err) { | ||||
p.Reject(err); | ||||
} | ||||
return p; | ||||
} | ||||
[DebuggerStepThrough] | ||||
cin
|
r96 | public static IPromise InvokePromise(Action action) { | ||
cin
|
r95 | ArgumentNotNull(action, "action"); | ||
cin
|
r119 | var p = new Promise(); | ||
cin
|
r95 | try { | ||
action(); | ||||
p.Resolve(); | ||||
} catch (Exception err) { | ||||
p.Reject(err); | ||||
} | ||||
return p; | ||||
} | ||||
[DebuggerStepThrough] | ||||
cin
|
r94 | public static IPromise<T> InvokePromise<T>(Func<IPromise<T>> action) { | ||
cin
|
r66 | ArgumentNotNull(action, "action"); | ||
try { | ||||
cin
|
r94 | return action() ?? Promise<T>.ExceptionToPromise(new Exception("The action returned null")); | ||
cin
|
r66 | } catch (Exception err) { | ||
return Promise<T>.ExceptionToPromise(err); | ||||
} | ||||
} | ||||
cin
|
r1 | } | ||
} | ||||