Esempio n. 1
0
        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);
            }
        }
Esempio n. 2
0
        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);
            }
        }
Esempio n. 3
0
 public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
 {
     if (string.IsNullOrWhiteSpace(Name))
     {
         yield return(BusinessErrors.FieldNullOrEmpty(nameof(Name)));
     }
 }
Esempio n. 4
0
        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)));
            }
        }
Esempio n. 5
0
 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);
     }
 }
Esempio n. 6
0
 public void RemoveAuthToken(string token)
 {
     if (_tokenCache.ContainsKey(token))
     {
         _tokenCache.Remove(token);
     }
     else
     {
         BusinessErrors.Add(new BusinessErrorSM(BusinessErrorCodes.DataNotFound, "Token not found"));
     }
 }
Esempio n. 7
0
        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);
        }
Esempio n. 8
0
        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)));
            }
        }
Esempio n. 9
0
        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));
        }
Esempio n. 10
0
        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);
        }
Esempio n. 11
0
        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);
        }
Esempio n. 12
0
        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);
        }
Esempio n. 13
0
        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);
        }
Esempio n. 14
0
        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);
        }
Esempio n. 15
0
        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());
        }
Esempio n. 16
0
        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);
                }
            }
        }
Esempio n. 17
0
        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));
        }
Esempio n. 18
0
        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);
        }
Esempio n. 19
0
        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);
        }
Esempio n. 20
0
 /// <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;
 }
Esempio n. 21
0
 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));
 }
Esempio n. 22
0
 /// <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;
 }
Esempio n. 23
0
 public static ValidationResult FieldNullOrEmpty(string name)
 {
     return(BusinessErrors.FieldNullOrEmpty(name).ValidateOnMember(name));
 }
Esempio n. 24
0
 /// <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;
 }
Esempio n. 25
0
 /// <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;
 }
Esempio n. 26
0
 /// <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;
 }