// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.IO;
namespace TheArtOfDev.HtmlRenderer.Core.Utils
{
///
/// Static class that contains argument-checking methods
///
public static class ArgChecker
{
///
/// Validate given condition is true, otherwise throw exception.
///
/// Exception type to throw.
/// Condition to assert.
/// Exception message in-case of assert failure.
public static void AssertIsTrue(bool condition, string message) where TException : Exception, new()
{
// Checks whether the condition is false
if (!condition)
{
// Throwing exception
throw (TException)Activator.CreateInstance(typeof(TException), message);
}
}
///
/// Validate given argument isn't Null.
///
/// argument to validate
/// Name of the argument checked
/// if is Null
public static void AssertArgNotNull(object arg, string argName)
{
if (arg == null)
{
throw new ArgumentNullException(argName);
}
}
///
/// Validate given argument isn't .
///
/// argument to validate
/// Name of the argument checked
/// if is
public static void AssertArgNotNull(IntPtr arg, string argName)
{
if (arg == IntPtr.Zero)
{
throw new ArgumentException("IntPtr argument cannot be Zero", argName);
}
}
///
/// Validate given argument isn't Null or empty.
///
/// argument to validate
/// Name of the argument checked
/// if is Null or empty
public static void AssertArgNotNullOrEmpty(string arg, string argName)
{
if (string.IsNullOrEmpty(arg))
{
throw new ArgumentNullException(argName);
}
}
///
/// Validate given argument isn't Null.
///
/// Type expected of arg
/// argument to validate
/// Name of the argument checked
/// if is Null
/// arg cast as T
public static T AssertArgOfType(object arg, string argName)
{
AssertArgNotNull(arg, argName);
if (arg is T)
{
return (T)arg;
}
throw new ArgumentException(string.Format("Given argument isn't of type '{0}'.", typeof(T).Name), argName);
}
///
/// Validate given argument isn't Null or empty AND argument value is the path of existing file.
///
/// argument to validate
/// Name of the argument checked
/// if is Null or empty
/// if arg file-path not exist
public static void AssertFileExist(string arg, string argName)
{
AssertArgNotNullOrEmpty(arg, argName);
if (false == File.Exists(arg))
{
throw new FileNotFoundException(string.Format("Given file in argument '{0}' not exist.", argName), arg);
}
}
}
}