/// <summary>Constructor</summary> /// <param name="errors">Validation errors</param> public ValidationExceptionOfT(IValidationErrorsOfT <T> errors) : base(errors) { Checker.ArgumentIsNull(errors, "errors"); Errors = errors; }
private IEnumerable <ValidationError> GetValidationErrors(object obj) { Checker.ArgumentIsNull(obj, "obj"); const BindingFlags BINDING_ATTR = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; // Properties var propertiesValidationErrors = GetPropertiesValidationErrors(obj, BINDING_ATTR); // Methods var methodsValidationErrors = from method in obj.GetType().GetMethods(BINDING_ATTR) let attribute = method .GetCustomAttributes <MethodValidateAttribute>(true) .SingleOrDefault() where attribute != null && !method.GetParameters().Any() && method.ReturnType == typeof(ValidationError) let result = (ValidationError)method.Invoke(obj, null) where result != null select result; return (propertiesValidationErrors .Concat(methodsValidationErrors) .Distinct()); }
/// <summary>Constructor</summary> /// <param name="errors">Validation errors</param> public ValidationException(IValidationErrors errors) : base(errors.ToExceptionMessage()) { Checker.ArgumentIsNull(errors, "errors"); Errors = errors; }
/// <summary>Checks whether object is valid</summary> /// <typeparam name="T">Object type to be validated</typeparam> /// <param name="obj">Object to be validated</param> public bool IsValid <T>(T obj) where T : class { Checker.ArgumentIsNull(obj, "obj"); var errors = Validate(obj); return(errors == null); }
private IEnumerable <ValidationError> GetPropertiesValidationErrors(object obj, BindingFlags bindingFlags) { Checker.ArgumentIsNull(obj, "obj"); foreach (var property in obj.GetType().GetProperties(bindingFlags)) { var validateAttribute = property .GetCustomAttributes <ValidateAttribute>(true) .SingleOrDefault(); if (validateAttribute != null) { var value = property.GetValue(obj, null); var isValid = validateAttribute.IsValid(value); if (!isValid) { yield return(new ValidationError(validateAttribute.Key ?? property.Name, validateAttribute.Message)); } } var validateComplexTypeAttribute = property .GetCustomAttributes <ComplexTypeValidateAttribute>(true) .SingleOrDefault(); if (validateComplexTypeAttribute != null) { var value = property.GetValue(obj, null); if (value != null) { var collectionValues = value as IEnumerable; if (collectionValues != null) { foreach (var collectionValue in collectionValues) { var validationErrors = GetValidationErrors(collectionValue); foreach (var validationError in validationErrors) { yield return(validationError); } } } else { var validationErrors = GetValidationErrors(value); foreach (var validationError in validationErrors) { yield return(validationError); } } } } } }
/// <summary>Constructor</summary> /// <param name="obj">Validated object</param> /// <param name="errors">Validation errors</param> public ValidationErrors(T obj, ValidationError[] errors) { Checker.ArgumentIsNull(obj, "obj"); Checker.ArgumentIsNull(errors, "errors"); Checker.Argument(errors.Length > 0, "errors.Length > 0"); Object = obj; Errors = errors; }
public static T[] GetCustomAttributes <T>(this MemberInfo methodInfo, bool inherit) where T : Attribute { Checker.ArgumentIsNull(methodInfo, "methodInfo"); return (methodInfo.GetCustomAttributes(typeof(T), inherit) .Cast <T>() .ToArray()); }
/// <summary>Constructor</summary> /// <param name="message">Validation message</param> /// <param name="enumType"><see cref="Enum"/> type</param> public EnumStringValidateAttribute(string message, Type enumType) : base(message) { Checker.ArgumentIsNull(enumType, "enumType"); Checker.Argument(enumType.IsEnum, "enumType.IsEnum"); EnumType = enumType; CanBeNull = false; }
private static void RegisterDependencies(IContainer container) { Checker.ArgumentIsNull(container, "container"); container.RegisterImplementation <IValidator, Validator.Validator>(Lifetime.PerContainer); container.RegisterImplementation <IUserService, UserService>(Lifetime.PerContainer); container.RegisterImplementation <ICategoryService, CategoryService>(Lifetime.PerContainer); container.RegisterImplementation <ITransactionService, TransactionService>(Lifetime.PerContainer); container.RegisterImplementation <ISummaryService, SummaryService>(Lifetime.PerContainer); }
/// <summary>Validates object and throw <see cref="ValidationExceptionOfT{T}"/> exception if validation failed</summary> /// <typeparam name="T">Object type to be validated</typeparam> /// <param name="obj">Object to be validated</param> public void CheckIsValid <T>(T obj) where T : class { Checker.ArgumentIsNull(obj, "obj"); var errors = Validate(obj); if (errors != null) { throw new ValidationExceptionOfT <T>(errors); } }
protected async Task <HttpResponseMessage> ExecuteAsync <TResponse>(Func <Task <TResponse> > action) { Checker.ArgumentIsNull(action, "action"); try { var serviceUser = User as ServiceUser; if (serviceUser == null || string.IsNullOrWhiteSpace(serviceUser.Id)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized, "User is not authorized.")); } var userService = Container.Get <IUserService>(); using (userService.LogIn(serviceUser.Id, true)) { var response = await action(); return(Request.CreateResponse(HttpStatusCode.OK, response)); } } catch (ValidationException ex) { var errors = ex.Errors.Errors .Select(e => new Error { Message = e.Message }) .ToArray(); return(Request.CreateResponse(HttpStatusCode.BadRequest, errors)); } catch (ValidationErrorException ex) { var error = new Error { Message = ex.Message }; return(Request.CreateResponse(HttpStatusCode.BadRequest, error)); } catch (Exception ex) { var error = new Error { Message = CreateErrorMessage(ex) }; return(Request.CreateResponse(HttpStatusCode.InternalServerError, error)); } }
/// <summary>Validates object and returns errors if validation failed</summary> /// <typeparam name="T">Object type to be validated</typeparam> /// <param name="obj">Object to be validated</param> public IValidationErrorsOfT <T> Validate <T>(T obj) where T : class { Checker.ArgumentIsNull(obj, "obj"); if (obj.GetType() != typeof(T)) { return(null); } var validationErrors = GetValidationErrors(obj) .ToArray(); return(validationErrors.Length > 0 ? new ValidationErrors <T>(obj, validationErrors) : null); }
protected string CreateErrorMessage(Exception exception) { Checker.ArgumentIsNull(exception, "exception"); var messageBuilder = new StringBuilder(exception.Message); var ex = exception; while (ex.InnerException != null) { messageBuilder.AppendLine(ex.InnerException.Message); ex = ex.InnerException; } return(messageBuilder.ToString()); }
public static string ToExceptionMessage(this IValidationErrors validateErrors) { Checker.ArgumentIsNull(validateErrors, "validateErrors"); var stringBuilder = new StringBuilder(); stringBuilder.Append("Invalid object: "); stringBuilder.AppendLine(validateErrors.Object.ToString()); stringBuilder.AppendLine("Errors: "); foreach (var error in validateErrors.Errors) { stringBuilder.Append("Key: "); stringBuilder.Append(error.Key); stringBuilder.Append(" Message: "); stringBuilder.AppendLine(error.Message); } return(stringBuilder.ToString()); }
protected async Task RethrowUniqueKeyExceptionAsync(string uniqueKeyName, Func <Exception> getException, Func <Task> action) { Checker.ArgumentIsWhitespace(uniqueKeyName, "uniqueKeyName"); Checker.ArgumentIsNull(getException, "getException"); Checker.ArgumentIsNull(action, "action"); try { await action(); } catch (DbUpdateException ex) { if (DoesExceptionContainText(ex, uniqueKeyName)) { throw getException(); } throw; } }
public static IQueryable <Transaction> ApplyDateCondition(IReadOnlyContainer container, IQueryable <Transaction> query, DateTime?from, DateTime?to) { Checker.ArgumentIsNull(container, "container"); Checker.ArgumentIsNull(query, "query"); if (!from.HasValue && !to.HasValue) { var firstDayOfCurrentMonth = container.Get <ITimeService>().FirstDayOfCurrentMonth; return(query.Where(t => t.Date >= firstDayOfCurrentMonth)); } if (from.HasValue) { query = query.Where(t => t.Date >= from.Value); } if (to.HasValue) { query = query.Where(t => t.Date <= to.Value); } return(query); }
public static void Register(IContainer container) { Checker.ArgumentIsNull(container, "container"); container.RegisterImplementation <ITimeService, TimeService>(Lifetime.PerContainer); }
protected BaseService(IReadOnlyContainer container) { Checker.ArgumentIsNull(container, "container"); Container = container; }
public static void Register(IContainer container) { Checker.ArgumentIsNull(container, "container"); container.RegisterImplementation <IPersistenceService, ExpenseAPIEntities>(Lifetime.PerCall); }