예제 #1
0
        protected void OnValidatePropertyValue(object oldValue, object newValue, Type valueType)
        {
            // strings are special case where null = empty, so no need to validate
            if (valueType == typeof(String))
            {
                if (String.IsNullOrEmpty((string)oldValue) && String.IsNullOrEmpty((string)newValue))
                {
                    return;
                }
            }

            if (Equals(oldValue, newValue))
            {
                return;
            }

            // process an async validation
            var veng    = (IHasValidationEngine)this;
            var inpmeta = (IHasPropertyMetadata)this;

            if (veng.InternalObservableValidationEngine.Object != null && inpmeta.InternalPropertyMetadata != null)
            {
                // TODO : refactor !
                CancelCurrentValidation();
                _cancellationTokenSource = new CancellationTokenSource();

                var validationParameter = new ValidationParameter(inpmeta.InternalPropertyMetadata, this, newValue, _cancellationTokenSource.Token);
                veng.InternalObservableValidationEngine.Object.Validate(validationParameter);
            }
        }
예제 #2
0
        public async ValueTask <CreateSessionResponse> HandleAsync(CreateSessionCommand command, CancellationToken cancellationToken = default)
        {
            ValidationParameter.FailIfNull(command);

            var customer = await _customerService.GetCustomerAsync(command.Username);

            // Do not allow create session if customer has blocked or not active account
            _customerService.ValidateCustomerAccountAsync(customer);

            // If customer has assigned other session remove them all
            await _sessionService.RemoveAllSession(command.Username);

            var sessionId = GenerateNewSession();

            var session = new Session(sessionId, customer);

            var expirationDate = session.GenerationDate;

            return(new CreateSessionResponse
            {
                IdSession = session.SessionId,
                Status = session.State,
                ExpirationTime = expirationDate
            });
        }
        private static string ToExceptionMessageComponent(
            this ValidationParameter validationParameter)
        {
            var result = Invariant($"  Specified '{validationParameter.Name}' is");

            if (validationParameter.ValueToStringFunc == null)
            {
                // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                if (validationParameter.Value == null)
                {
                    result = Invariant($"{result} '{NullValueToString}'");
                }
                else
                {
                    result = Invariant($"{result} '{validationParameter.Value}'");
                }
            }
            else
            {
                result = Invariant($"{result} {validationParameter.ValueToStringFunc()}");
            }

            result = Invariant($"{result}.");

            return(result);
        }
예제 #4
0
        /// <summary>
        /// Asynchronously validates the property.
        /// </summary>
        private void AsynchronouslyValidateProperty(ValidationParameter validationParameter)
        {
            var tsk = Task <ValidateCoreResult> .Factory.StartNew(() =>
            {
                var validateCoreResult = ValidateCore(validationParameter);

                // optional properties
                ClearErrorMessage(validateCoreResult.ToClearProperties);

                // main property
                ClearErrorMessage(new[] { validateCoreResult.Property });
                if (!validateCoreResult.IsValid)
                {
                    AppendErrorMessage(validateCoreResult.Property, validateCoreResult.ErrorMessage);
                }

                return(validateCoreResult);
            });

            tsk.ContinueWith(t =>
            {
                var validateCoreResult = t.Result;
                OnRaiseErrorsChangedEvent(validateCoreResult.Property,
                                          validateCoreResult.ToClearProperties.ToArray());
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
예제 #5
0
        protected override void OnValidate(ValidationParameter validationParameter)
        {
            // Example of Synchronous validation
            SynchronouslyValidateProperty(validationParameter);

            // Example of asynchronous validation
            //AsynchronouslyValidateProperty(validationParameter);
        }
예제 #6
0
 private ValidationResult <TestObject> ProhibitQuit <TestObject>(ValidationParameter <TestObject> validationParameter) where TestObject : new()
 {
     return(new ValidationResult <TestObject>
     {
         IsValid = false,
         Error = "Cannot quit - you must trade when holding at least 5 cards"
     });
 }
예제 #7
0
 private ValidationResult <bool> Decline(ValidationParameter <bool> validationParameter)
 {
     return(new ValidationResult <bool>
     {
         Object = false,
         IsValid = true,
     });
 }
예제 #8
0
 private ValidationResult <TestObject> ResponseNotRecognised <TestObject>(ValidationParameter <TestObject> validationParameter) where TestObject : new()
 {
     return(new ValidationResult <TestObject>
     {
         IsValid = false,
         Error = "Response not recognised.Please try again."
     });
 }
예제 #9
0
 private ValidationResult <TestObject> Quit <TestObject>(ValidationParameter <TestObject> validationParameter) where TestObject : new()
 {
     return(new ValidationResult <TestObject>
     {
         IsValid = true,
         IsRequired = false
     });
 }
예제 #10
0
 private ValidationResult <bool> Accept(ValidationParameter <bool> validationParameter)
 {
     return(new ValidationResult <bool>
     {
         Object = true,
         IsValid = true,
     });
 }
예제 #11
0
 private Deployment CreateDeployment(int[] matches, ValidationParameter <Deployment> validationParameter)
 {
     return(new Deployment
     {
         Armies = matches[0],
         From = Array.Find(validationParameter.Countries, c => c.Name == (CountryName)matches[1]),
         To = Array.Find(validationParameter.Countries, c => c.Name == (CountryName)matches[2]),
     });
 }
예제 #12
0
        private ValidationResult <int> ValidateNumberOfPlayers(ValidationParameter <int> validationParameter)
        {
            var responseValidation = new ResponseValidationBuilder <int, int>()
                                     .ValidationParameter(validationParameter)
                                     .MatchBuilder(GetIntegerMatches)
                                     .TestObjectBuilder((matches, vp) => matches[0])
                                     .ErrorChecks(
                Check.ValidNumberOfPlayers)
                                     .Build();

            return(responseValidation.Validate());
        }
예제 #13
0
        protected override void OnValidate(ValidationParameter validationParameter)
        {
            // Note that propertyValue is not used here. The fluent validation engine will
            // bind directly to view model properties in order to get their values.

            var propertyName     = validationParameter.PropertyMetadata.Name;
            var propertyInstance = validationParameter.PropertyInstance;

            // notifies that the property is currently validating its value
            propertyInstance.IsValidating = true;

            // if there is no rules attached to the property then just ignore it.
            if (_compiledRules.ContainsKey(propertyName) == false)
            {
                return;
            }

            // Cancellation ability
            var cancellationToken = validationParameter.CancellationToken;

            // retrieve all evaluable rules
            var validationTasks = (from cr in _compiledRules[propertyName] select cr.Evaluate(cancellationToken)).ToList();

            Trace.WriteLine("OnStartValidating " + propertyName);

            // process evaluation of the rules
            StartValidationTasks(validationTasks);

            Task.Factory.ContinueWhenAll(validationTasks.ToArray()
                                         , terminatedTasks =>
            {
                try
                {
                    // waits for terminated tasks in order to detect eventual exceptions.
                    Task.WaitAll(terminatedTasks.Cast <Task>().ToArray());

                    OnValidationTerminated(propertyName, terminatedTasks.ToList());
                    propertyInstance.IsValidating = false;
                }
                catch (AggregateException ae)
                {
                    propertyInstance.IsValidating = false;

                    // TODO : propagate exception notification to the UI !!
                    throw ae.Flatten();
                }
            }, cancellationToken
                                         , TaskContinuationOptions.None
                                         , TaskScheduler.FromCurrentSynchronizationContext());
        }
예제 #14
0
        public async ValueTask <GetCustomerDetailsRs> HandleAsync([NotNull] GetCustomerDetailsRq command, CancellationToken cancellationToken = default)
        {
            ValidationParameter.FailIfNull(command);

            var customerAccount = await _customerService.GetCustomerAsync(command.Username);

            return(new GetCustomerDetailsRs
            {
                Fullname = customerAccount.FirstName + " " + customerAccount.LastName,
                Username = customerAccount.Username,
                Email = customerAccount.Email,
                Status = customerAccount.Status
            });
        }
예제 #15
0
        private ValidationResult <List <Card> > ValidateCardTrade(ValidationParameter <List <Card> > validationParameter)
        {
            var responseValidation = new ResponseValidationBuilder <List <Card>, int>()
                                     .ValidationParameter(validationParameter)
                                     .MatchBuilder(GetIntegerMatches)
                                     .TestObjectBuilder((matches, vp)
                                                        => vp.Cards.Where(c => matches.Contains((int)c.CountryName)).ToList())
                                     .ErrorChecks(
                Check.ThreeSelectedFromOwnCards,
                Check.ValidSet)
                                     .Build();

            return(responseValidation.Validate());
        }
예제 #16
0
        public async ValueTask HandleAsync(RegisterCustomer command, CancellationToken cancellationToken = default)
        {
            ValidationParameter.FailIfNull(command);

            var customerExist = await _customerService.CheckIfExist(command.Username);

            if (customerExist)
            {
                throw new CoreException(ErrorCode.UsernameExist, $"Name of {command.Username} is in use. Choose another one.");
            }

            await _customerService.RegisterAsync(command.FirstName, command.LastName, command.Username, command.Email, command.PhoneNumber);

            //if (_options.Value.SendRealEmail)
            //    await _emailHelper.SendEmail(command.Email, "content todo");
        }
예제 #17
0
        private ValidationResult <Deployment> ValidateFortificationParameters(ValidationParameter <Deployment> validationParameter)
        {
            var responseValidation = new ResponseValidationBuilder <Deployment, int>()
                                     .ValidationParameter(validationParameter)
                                     .MatchBuilder(GetIntegerMatches)
                                     .TestObjectBuilder(CreateDeployment)
                                     .ErrorChecks(
                Check.ValidCountryIds,
                Check.PlayerHoldsAttackingCountry,
                Check.PlayerHoldsDeploymentCountry,
                Check.DeploymentToNeighbouringCountry,
                Check.SufficientArmies)
                                     .Build();

            return(responseValidation.Validate());
        }
예제 #18
0
        public async ValueTask HandleAsync(AddProductCommand command, CancellationToken cancellationToken = default)
        {
            ValidationParameter.FailIfNull(command);


            if (string.IsNullOrWhiteSpace(command.Request.Name))
            {
                throw new CoreException(ErrorCode.IncorrectArgument, $"Value of {nameof(command.Request.Name)} in invalid.");
            }

            await CheckIfExistAsync(_context, command.Request.Name);

            var category = await _context.Categories.SingleOrDefaultAsync(x => x.Name == command.Request.CategoryName);

            await _productHelper.AddProductAsync(_context, command.Request.Name, command.Request.Amount, command.Request.Description,
                                                 category);
        }
예제 #19
0
        private ValidationResult <Deployment> ValidateArmyTransfer(ValidationParameter <Deployment> validationParameter)
        {
            var responseValidation = new ResponseValidationBuilder <Deployment, int>()
                                     .ValidationParameter(validationParameter)
                                     .MatchBuilder(GetIntegerMatches)
                                     .TestObjectBuilder((matches, vp) => new Deployment
            {
                Armies = matches[0],
                From   = vp.PreviousDeployment.From,
                To     = vp.PreviousDeployment.To
            })
                                     .ErrorChecks(
                Check.SufficientArmies)
                                     .Build();

            return(responseValidation.Validate());
        }
예제 #20
0
파일: Attack.cs 프로젝트: stephenjukes/Risk
        private ValidationResult <Deployment> ValidatePreviousAttackParameters(ValidationParameter <Deployment> validationParameter)
        {
            var previousDeployment = validationParameter.PreviousDeployment;

            var responseValidation = new ResponseValidationBuilder <Deployment, int>()
                                     .ValidationParameter(validationParameter)
                                     .TestObjectBuilder((matches, vp) => vp.PreviousDeployment)
                                     .ErrorChecks(
                Check.PreviousAttackParametersExist,
                Check.SufficientArmies)
                                     .Build();

            _textbox.Write($"Repeating attack with {previousDeployment.Armies} armies from {previousDeployment.From.Name} to {previousDeployment.To.Name}");
            _textbox.Write();

            return(responseValidation.Validate());
        }
예제 #21
0
        /// <summary>
        /// Synchronously validates the property.
        /// </summary>
        private void SynchronouslyValidateProperty(ValidationParameter validationParameter)
        {
            var validateCoreResult = ValidateCore(validationParameter);

            // optional properties
            ClearErrorMessage(validateCoreResult.ToClearProperties);

            // main property
            ClearErrorMessage(new[] { validateCoreResult.Property });
            if (!validateCoreResult.IsValid)
            {
                AppendErrorMessage(validateCoreResult.Property, validateCoreResult.ErrorMessage);
            }

            // always notify that the error has changed to tell the ui to refresh
            OnRaiseErrorsChangedEvent(validateCoreResult.Property, validateCoreResult.ToClearProperties.ToArray());
        }
예제 #22
0
        public HttpResponseMessage CheckLoginEmail(ValidationParameter parameter)
        {
            var transaction = new TransactionalInformation();
            var exists      = docDataService.CheckLoginEmail(parameter.ID, parameter.Type, parameter.ContentToValidate, connectionString, SessionToken, out transaction);

            if (transaction.ReturnStatus)
            {
                if (exists)
                {
                    return(Request.CreateResponse(HttpStatusCode.NotAcceptable));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }

            return(Request.CreateResponse(HttpStatusCode.BadRequest));
        }
예제 #23
0
        public async ValueTask HandleAsync(ChangeStatusCommand command, CancellationToken cancellationToken = default)
        {
            var request = command.ChangeStatusRequest;

            ValidationParameter.FailIfNullOrEmpty(request.Username);
            ValidationParameter.FailIfNullOrEmpty(request.Status.ToString());

            var customer = await _customerService.GetCustomerAsync(request.Username);

            if (customer.Status.Equals(request.Status))
            {
                return;
            }

            customer.Status = request.Status;

            await _rentalContext.SaveChangesAsync(cancellationToken);
        }
예제 #24
0
        public async ValueTask HandleAsync(ChangePasswordCommand command, CancellationToken cancellationToken = default)
        {
            ValidationParameter.FailIfNull(command);

            // to do get session which will be get from headers, implementation after add headers

            var customer = await _customerService.GetCustomerAsync(command.Username);

            _customerService.ValidateCustomerAccountAsync(customer);

            var activeUserPassword = await _passwordHelper.GetActivePassword(customer);

            //compare old password and new password. New password can not be exactly same like old password
            _passwordHelper.ComaprePasswords(activeUserPassword, command.NewPassword);

            await _passwordHelper.RemoveOldPassword(command.Username);

            await _passwordHelper.SetPassword(command.NewPassword, customer);
        }
예제 #25
0
파일: Customer.cs 프로젝트: angn92/Rental
 public void SetUsername(string username)
 {
     ValidationParameter.FailIfNullOrEmpty(username);
     Username = username;
 }
예제 #26
0
파일: Customer.cs 프로젝트: angn92/Rental
 public void SetLastName(string lastName)
 {
     ValidationParameter.FailIfNullOrEmpty(lastName);
     LastName = lastName;
 }
예제 #27
0
파일: Customer.cs 프로젝트: angn92/Rental
 public void SetFirstName(string firstName)
 {
     ValidationParameter.FailIfNullOrEmpty(firstName);
     FirstName = firstName;
 }
예제 #28
0
        public async Task RegisterAccount([FromBody][NotNull] RegisterCustomer command)
        {
            ValidationParameter.FailIfNull(command);

            await _commandDispatcher.DispatchAsync(command);
        }
예제 #29
0
        private ValidateCoreResult ValidateCore(ValidationParameter validationParameter)
        {
            var propertyMetadata = validationParameter.PropertyMetadata;
            var propertyValue    = validationParameter.PropertyValue;

            var validateCoreResult = new ValidateCoreResult {
                Property = propertyMetadata.Name, IsValid = true
            };

            if (propertyMetadata.Name == "Code")
            {
                if (string.IsNullOrEmpty((string)propertyValue))
                {
                    validateCoreResult.IsValid      = false;
                    validateCoreResult.ErrorMessage = "Code is required";
                }

                var value = (string)propertyValue;
                if (value != null && value.Length > 3)
                {
                    validateCoreResult.IsValid      = false;
                    validateCoreResult.ErrorMessage = "Code must not exceed 3 characters.";
                }
            }

            if (propertyMetadata.Name == "Age")
            {
                if (propertyValue != null)
                {
                    var age = (int)propertyValue;
                    if (age < 1 || age > 50)
                    {
                        validateCoreResult.IsValid      = false;
                        validateCoreResult.ErrorMessage = "Age must be between 1 and 50.";
                    }
                }
            }

            if (propertyMetadata.Name == "Country")
            {
                var country = (Country)propertyValue;
                if (country != null && country.Id != 4)
                {
                    validateCoreResult.IsValid      = false;
                    validateCoreResult.ErrorMessage = "Country other than Madagascar is not allowed.";
                }
            }

            if (propertyMetadata.Name == "DateOfBirth")
            {
                if (propertyValue != null)
                {
                    var dateOfBirth = (DateTime)propertyValue;
                    if (dateOfBirth >= _viewModel.DateOfHire.Value)
                    {
                        validateCoreResult.IsValid      = false;
                        validateCoreResult.ErrorMessage = "Date of Birth must preced the Date of Hire";
                    }

                    validateCoreResult.ToClearProperties = new List <string> {
                        "DateOfHire"
                    };
                }
            }

            if (propertyMetadata.Name == "DateOfHire")
            {
                if (propertyValue != null)
                {
                    var dateOfHire = (DateTime)propertyValue;
                    if (dateOfHire <= _viewModel.DateOfBirth.Value)
                    {
                        validateCoreResult.IsValid      = false;
                        validateCoreResult.ErrorMessage = "Date of Birth must preced the Date of Hire";
                    }

                    validateCoreResult.ToClearProperties = new List <string> {
                        "DateOfBirth"
                    };
                }
            }

            return(validateCoreResult);
        }