public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (string.IsNullOrWhiteSpace(Name)) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(Name))); } if (Id == Guid.Empty) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(Id))); } if (RestartOnFailInterval != null && RestartOnFailInterval <= TimeSpan.Zero) { yield return(TaskErrors.RestartOnFailIntervalMustBePositive); } if (RestartOnFailInterval == null && MaximumRestarts < 1) { yield return(TaskErrors.MaximumRestartsMustBeGreaterThanZero); } if (!Audience.IncludesServer && !Audience.IsAll && !Audience.Any()) { yield return(TaskErrors.NoAudienceGiven); } if (!Commands.Any()) { yield return(TaskErrors.NoCommandsGiven); } }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (string.IsNullOrWhiteSpace(Content)) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(Content))); } var jsonString = Content.Trim(); if (!jsonString.StartsWith("{") || !jsonString.EndsWith("}")) { yield return(BusinessErrors.ClientConfigurations.InvalidJson); } var parseSucceeded = false; try { JToken.Parse(Content); parseSucceeded = true; } catch (Exception) { // ignored } if (!parseSucceeded) { yield return(BusinessErrors.ClientConfigurations.InvalidJson); } }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (string.IsNullOrWhiteSpace(Name)) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(Name))); } }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (string.IsNullOrWhiteSpace(Username)) { yield return(BusinessErrorHelper.FieldNullOrEmpty(nameof(Username))); } if (string.IsNullOrWhiteSpace(OperatingSystem)) { yield return(BusinessErrorHelper.FieldNullOrEmpty(nameof(OperatingSystem))); } if (string.IsNullOrWhiteSpace(SystemLanguage)) { yield return(BusinessErrorHelper.FieldNullOrEmpty(nameof(SystemLanguage))); } else if (!CultureInfoExtensions.TryGet(SystemLanguage, out _)) { yield return(BusinessErrors.InvalidCultureName.ValidateOnMember(nameof(SystemLanguage))); } if (string.IsNullOrWhiteSpace(ClientPath)) { yield return(BusinessErrorHelper.FieldNullOrEmpty(nameof(ClientPath))); } if (string.IsNullOrWhiteSpace(HardwareId)) { yield return(BusinessErrorHelper.FieldNullOrEmpty(nameof(HardwareId))); } else if (!Hash.TryParse(HardwareId, out _)) { yield return(BusinessErrors.InvalidSha256Hash.ValidateOnMember(nameof(HardwareId))); } if (MacAddress == null) { yield return(BusinessErrorHelper.FieldNullOrEmpty(nameof(MacAddress))); } else if (MacAddress.Length != 6) { yield return(BusinessErrors.InvalidMacAddress.ValidateOnMember(nameof(MacAddress))); } if (ClientVersion == null) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(ClientVersion))); } if (Framework == null) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(Framework))); } }
public void AddAuthToken(AuthTokenSM authToken) { if (_tokenCache.ContainsKey(authToken.Token)) { BusinessErrors.Add(new BusinessErrorSM(BusinessErrorCodes.DataAlreadyExists, "Token already exists")); } else { _tokenCache.Add(authToken.Token, authToken.Expiry); } }
public void RemoveAuthToken(string token) { if (_tokenCache.ContainsKey(token)) { _tokenCache.Remove(token); } else { BusinessErrors.Add(new BusinessErrorSM(BusinessErrorCodes.DataNotFound, "Token not found")); } }
public async Task <bool> IsMemberExisted(string email) { if (string.IsNullOrWhiteSpace(email)) { var error = "Email is required."; throw new BusinessException(error, BusinessErrors.BadRequest(error)); } var member = await _memberDataAccessor.GetByEmail(email); return(member != null); }
public override IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { foreach (var validationResult in base.Validate(validationContext)) { yield return(validationResult); } if (string.IsNullOrWhiteSpace(Password)) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(Password))); } }
public async Task <SimpleResponse <Member> > Handle(GetMemberByEmailQuery request, CancellationToken cancellationToken) { var member = await _memberService.GetMemberByEmail(request.Email); if (member == null) { throw new BusinessException("Cannot find member for email {email}", BusinessErrors.ResourceNotFound("member", "Email is not found"), request.Email); } return(SimpleResponse <Member> .Create(member)); }
public AccountStatusIds?Convert(string accountStatus, ResolutionContext context) { if (accountStatus == null) { return(null); } if (!Enum.TryParse(accountStatus.Trim(), true, out AccountStatusIds accountStatusId)) { var error = "Invalid account status"; throw new BusinessException(error, BusinessErrors.BadRequest(error)); } return(accountStatusId); }
public async Task GivenGlobalExceptionHandler_WhenBusinessExceptionRaised_IfErrorIsResourceNotFound_ShouldSendResourceNotFound() { // assign var context = new DefaultHttpContext(); var parameters = new object[] { }; var ex = new BusinessException("Some Exception", BusinessErrors.ResourceNotFound("Not Found", "Not Found"), parameters); _requestDelegate.Invoke(Arg.Any <HttpContext>()).Returns(callInfo => throw ex); // act await _handler.Invoke(context); // assert AssertLogging(LogLevel.Warning, ex.Message, null); await AssertHttpResponse(context, HttpStatusCode.NotFound, ex.BusinessErrorMessage); }
public async Task GivenGlobalExceptionHandler_WhenBusinessExceptionRaised_IfErrorIsCritical_ShouldSendInternalServerError() { // assign var context = new DefaultHttpContext(); var parameters = new object[] { }; var ex = new BusinessException("Some Exception", BusinessErrors.Critical("Internal Server Error"), parameters); _requestDelegate.Invoke(Arg.Any <HttpContext>()).Returns(callInfo => throw ex); // act await _handler.Invoke(context); // assert AssertLogging(LogLevel.Error, ex.Message, ex); await AssertHttpResponse(context, HttpStatusCode.InternalServerError, ex.BusinessErrorMessage); }
public async Task <TaskTransmission> BizActionAsync(TaskTransmission inputData) { if (inputData.TaskReferenceId == Guid.Empty) { return(ReturnError <TaskTransmission>(BusinessErrors.FieldNullOrEmpty("TaskReferenceId"))); } if (inputData.CreatedOn == default) { return(ReturnError <TaskTransmission>(BusinessErrors.FieldNullOrEmpty("CreatedOn"))); } await _dbAccess.CreateAsync(inputData); return(inputData); }
public async Task GivenGlobalExceptionHandler_WhenExceptionRaised_IfInnerExceptionIsBadRequestBusinessException_ShouldSendBadRequest() { // assign var context = new DefaultHttpContext(); var businessException = new BusinessException("Some Bad Request", BusinessErrors.BadRequest("Bad Request")); var ex = new Exception("Some Exception", businessException); _requestDelegate.Invoke(Arg.Any <HttpContext>()).Returns(callInfo => throw ex); // act await _handler.Invoke(context); // assert AssertLogging(LogLevel.Warning, businessException.Message, null); await AssertHttpResponse(context, HttpStatusCode.BadRequest, businessException.BusinessErrorMessage); }
public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var errors = _validators .Select(v => v.Validate(request)) .SelectMany(v => v.Errors) .Where(e => e != null) .Select(e => e.ErrorMessage) .ToList(); if (errors.Any()) { var builder = new StringBuilder(); errors.ForEach(e => builder.AppendLine(e)); var errorMessage = builder.ToString(); throw new BusinessException(errorMessage, BusinessErrors.BadRequest(errorMessage)); } return(next()); }
public virtual IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { if (string.IsNullOrEmpty(Username)) { yield return(BusinessErrors.FieldNullOrEmpty(nameof(Username))); } else { if (Username.Length > LengthConsts.AccountUsernameMaxLength) { yield return(BusinessErrors.Account.UsernameTooLong); } if (!Regex.IsMatch(Username, "^[a-zA-Z0-9]+$")) { yield return(BusinessErrors.Account.InvalidCharsInUsername); } } }
public async Task <SimpleResponse <Account> > Handle(SignUpAccountCommand request, CancellationToken cancellationToken) { var member = await _memberService.GetMemberById(request.MemberId); if (member == null) { throw new BusinessException( "Member {memberId} is invalid.", BusinessErrors.BadRequest("Invalid member details."), request.MemberId); } var account = await _accountService.SignUpAccount(member); await _userUnitOfWork.SaveChangesAsync(cancellationToken); account = await _accountService.GetAccountById(account.Id); return(SimpleResponse <Account> .Create(account)); }
public async Task <Member> SignUpMember(Member member) { if (!member.IsNew) { throw new BusinessException("Member {memberId} is not marked as new.", BusinessErrors.Critical("Member is not marked as new."), member.Id); } var memberExisted = await IsMemberExisted(member.Email); if (memberExisted) { var error = $"Cannot sign up member for email {member.Email}."; throw new BusinessException(error, BusinessErrors.BadRequest(error)); } await _memberDataAccessor.Create(member); return(member); }
public async Task <Account> SignUpAccount(Member member) { var strategy = await _accountSignUpStrategyDataAccessor.GetDefaultStrategy(); var result = _accountSignUpEvaluator.Evaluate(member, strategy); if (!result.IsSuccess) { throw new BusinessException("Sign up account failed for member {memberId}. {error}", BusinessErrors.BadRequest(result.ReasonPhase), member.Id, result.ReasonPhase); } var accountNumberSeq = await _accountDataAccessor.GetNextAccountNumberSeq(); var accountNumber = $"ZIP{accountNumberSeq:D10}"; var account = _accountFactory.Create(accountNumber, member.Id); await _accountDataAccessor.Create(account); return(account); }
/// <summary> /// Initializes a new instance of the <see cref="BusinessValidationException"/> class. /// </summary> /// <param name="exception">The exception.</param> /// <param name="businessErrors">The business errors.</param> /// public BusinessValidationException(Exception exception, BusinessErrors businessErrors) : base(businessErrors.GetDescription(), exception) { ErrorCode = businessErrors; }
protected BusinessValidationException(SerializationInfo info, StreamingContext context) : base(info, context) { this.DataElement = info.GetString(nameof(DataElement)); this.ErrorCode = (BusinessErrors)info.GetValue(nameof(ErrorCode), typeof(BusinessErrors)); this._errorCodeDescription = info.GetString(nameof(ErrorCodeDescription)); }
/// <summary> /// Initializes a new instance of the <see cref="BusinessValidationException"/> class. /// </summary> /// <param name="errorCode">The error code.</param> /// public BusinessValidationException(BusinessErrors errorCode) : this(errorCode, (string)null) { ErrorCode = errorCode; }
public static ValidationResult FieldNullOrEmpty(string name) { return(BusinessErrors.FieldNullOrEmpty(name).ValidateOnMember(name)); }
/// <summary> /// Initializes a new instance of the <see cref="BusinessValidationException"/> class. /// </summary> /// <param name="errorCode">The error code.</param> /// <param name="dataElement">The data element.</param> /// public BusinessValidationException(BusinessErrors errorCode, string dataElement) : base(errorCode.GetDescription()) { DataElement = dataElement; ErrorCode = errorCode; }
/// <summary> /// Initializes a new instance of the <see cref="BusinessValidationException"/> class. /// </summary> /// <param name="message">The message.</param> /// <param name="innerException">The inner exception.</param> /// <param name="dataElement">The data element.</param> /// <param name="errorCode">The error code.</param> /// public BusinessValidationException(string message, Exception innerException, string dataElement, BusinessErrors errorCode) : base(errorCode.GetDescription(), innerException) { DataElement = dataElement; ErrorCode = errorCode; }
/// <summary> /// Initializes a new instance of the <see cref="BusinessValidationException"/> class. /// </summary> /// <param name="info">The information.</param> /// <param name="context">The context.</param> /// <param name="dataElement">The data element.</param> /// <param name="errorCode">The error code.</param> /// protected BusinessValidationException(SerializationInfo info, StreamingContext context, string dataElement, BusinessErrors errorCode) : base(info, context) { DataElement = dataElement; ErrorCode = errorCode; }