public ActionResult <Company> Update(int companyId, [FromBody] Company company)
 {
     company.Id = companyId;
     if (_validator.Validate(company, _companyService, true))
     {
         var result = _companyService.Update(company);
         return(new OkObjectResult(result));
     }
     return(new BadRequestResult());
 }
Esempio n. 2
0
        public void Validator_WhenValidatorDoesNotExist_ShouldThrowNotSupportedException()
        {
            object obj = _fixture.Create <object>();

            _mockContainer.Setup(call => call.ResolveComponent(It.IsAny <IComponentRegistration>(), It.IsAny <IEnumerable <Parameter> >())).Returns(null);

            Action action = () => _validatorService.Validate(obj);

            action.Should().Throw <NotSupportedException>();
        }
Esempio n. 3
0
        public void Update_Fails_When_Validation_Fail()
        {
            var request = _fix.Create <Company>();

            _validator.Validate(request, _service).Returns(false);
            var controller = new CompanyController(_logger, _service, _validator);
            var result     = controller.Update(request.Id, request);

            result.Result.Should().BeOfType <BadRequestResult>();
        }
Esempio n. 4
0
 public virtual async Task <TEntity> CreateAsync(TEntity entity, string ruleset)
 {
     return(await ServiceHelper.TryCatchWithLogger(async() =>
     {
         await Task.Delay(1);
         entity = BeforeCreate(entity);
         _validationService.Validate(entity, ruleset);
         _repositoryAsync.Insert(entity);
         entity = AfterCreate(entity);
         return entity;
     }, _logger, LogCategories));
 }
Esempio n. 5
0
        private static void Main()
        {
            IContainer        container        = CreateContainer();
            IValidatorService validatorService = container.Resolve <IValidatorService>();

            Country country = new Country("CAN", "Canada");

            validatorService.Validate(country);

            User user = new User("Joe", "Bloggs", "*****@*****.**", country);

            validatorService.Validate(user);

            Console.WriteLine("Success!");
            Console.ReadLine();
        }
Esempio n. 6
0
        public async Task HandlePayment_ReturnSuccessfulPaymentResponse_WhenPaymentPassedAllChecks()
        {
            // Arrange
            var request = CreateMakePaymentCommand();

            var(payment, paymentResponse) = CreateSuccessfulPaymentAndPaymentResponse();

            A.CallTo(() => _validatorsEnumerator.Current).Returns(new CardNumberLengthValidator());
            A.CallTo(() => _validators.GetEnumerator()).Returns(_validatorsEnumerator);
            A.CallTo(() => _validatorService.Validate(_validators, request)).Returns((true, new List <ValidationError>()));
            A.CallTo(() => _bankService.ProcessPayment(request)).Returns(paymentResponse);
            A.CallTo(() => _paymentsService.CreateAsync(payment));
            A.CallTo(() => _paymentMapper.Map(payment)).Returns(paymentResponse);

            // Act
            var response = await _sut.Handle(request, new CancellationToken());

            // Assert
            var expectedPaymentResponse = new PaymentResponse
            {
                Id                = paymentResponse.Id,
                BankPaymentId     = paymentResponse.BankPaymentId,
                MerchantPaymentId = paymentResponse.MerchantPaymentId,
                BillingDetails    = paymentResponse.BillingDetails,
                Currency          = paymentResponse.Currency,
                Amount            = paymentResponse.Amount,
                Status            = paymentResponse.Status,
                ValidationErrors  = paymentResponse.ValidationErrors,
                Reason            = paymentResponse.Reason,
                TimeStamp         = DateTime.UtcNow
            };

            expectedPaymentResponse.Should().BeEquivalentTo(expectedPaymentResponse, x => x.Excluding(a => a.TimeStamp));
        }
Esempio n. 7
0
        public async Task <IHttpActionResult> PostAsync([FromBody] IEvent @event)
        {
            return(await ActionHelper.TryCatchWithLoggerAsync(async() =>
            {
                _logger.WriteDebug(new LogMessage(string.Concat("VecompSoftware.DocSuiteWeb.WebAPI.Controllers.ServiceBus.TopicController.PostAsync(", @event != null, ")")), LogCategories);
                if (@event == null)
                {
                    _logger.WriteWarning(new LogMessage(string.Concat("Event received is invalid (json deserialization set null value) : ",
                                                                      GetType().ToString())), LogCategories);

                    return BadRequest("Event received is invalid (json deserialization set null value)");
                }

                _logger.WriteInfo(new LogMessage(string.Concat("Event received ", @event.ToString())), LogCategories);

                if (!_validationService.Validate(@event, _ruleset.INSERT))
                {
                    _logger.WriteWarning(new LogMessage(string.Concat("Service Bus validation error: ", GetType().ToString())), LogCategories);
                    return BadRequest("Service Bus validation error.");
                }

                ServiceBusMessage message = _mapper.Map(@event, new ServiceBusMessage());
                if (string.IsNullOrEmpty(message.ChannelName))
                {
                    throw new DSWException(string.Concat("Topic name to event [", @event.ToString(), "] is not mapped"), null, DSWExceptionCode.SC_Mapper);
                }
                ServiceBusMessage response = await _service.SendToTopicAsync(message);
                return Ok(response);
            }, BadRequest, Content, InternalServerError, _logger, LogCategories));
        }
Esempio n. 8
0
        public bool ChangePassword(RecoveryCode model)
        {
            _changePasswordValidators.Validate(model);

            var user = _accessTokenRepository.GetUserByEmail(model.Email);

            if (user == null)
            {
                throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Användare finns inte.");
            }

            model.UserId = user.Id;
            var recoverCode = _accessTokenRepository.CheckValidRecoverCode(model);

            if (recoverCode == null)
            {
                throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Ogiltig kod.");
            }

            if (recoverCode.ExpiredOn < DateTime.Now)
            {
                throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Koden har gått ut.");
            }

            var changePassword = ChangePasswordMapper(model);

            return(_accessTokenRepository.ChangePassword(changePassword, recoverCode.Id));
        }
Esempio n. 9
0
        /// <summary>
        /// Método encargado de actualizar una entidad en el repositorio del catálogo que lo usa. Invoca a la validación correspondiente antes de actualizar.
        /// </summary>
        /// <param name="_id"> Identificador de la entidad que será actualizada. </param>
        /// <param name="_entity"> Entidad que será actualizada en el repositorio </param>
        public void Update(Guid _id, TEntity _entity)
        {
            var DateServer = getterDateRepository.GetDateTime();

            validatorService.Validate(_entity);
            _entity.ModifiedDate = DateServer;
            updaterRepository.Update(_entity);
        }
Esempio n. 10
0
        public async Task <List <PetsResult> > GetPetNamesGroupedUponOwnerGender(string petType)
        {
            List <Person> persons = await _peopleApiClient.GetPersonData();

            var isValid = _validatorService.Validate(persons, out IList <string> errors);

            if (!isValid)
            {
                _logger.LogError("Person Pets data validation Failed.");
                foreach (var validationError in errors)
                {
                    _logger.LogError(validationError);
                }
                throw new ValidationException("Person Pets data validation Failed.");
            }

            var ownerPetsData =
                (from person in persons.Where(p => p.Pets != null)
                 from pet in person.Pets.Where(p => p.Species.Trim().ToLower() == petType.ToLower())
                 select new
            {
                Gender = person.Gender.ToTitleCase(),
                PetName = pet.Name.ToTitleCase()
            })
                .OrderByDescending(d => d.Gender)
                .ThenBy(d => d.PetName)
                .GroupBy(p => p.Gender, p => p.PetName,
                         (ownerGender, petNames) => new PetsResult()
            {
                OwnerGender = ownerGender,
                PetNames    = petNames.ToList()
            }).ToList();

            if (ownerPetsData.Count < 2)
            {
                if (ownerPetsData.Count == 1)
                {
                    var isExistingItemForMale = ownerPetsData[0].OwnerGender == Constants.Male;
                    ownerPetsData.Insert(
                        isExistingItemForMale ? 1 : 0,
                        new PetsResult
                    {
                        OwnerGender = isExistingItemForMale ? Constants.Female : Constants.Male,
                        PetNames    = new List <string>()
                    });
                }
                else
                {
                    ownerPetsData.Add(new PetsResult {
                        OwnerGender = Constants.Male, PetNames = new List <string>()
                    });
                    ownerPetsData.Add(new PetsResult {
                        OwnerGender = Constants.Female, PetNames = new List <string>()
                    });
                }
            }
            return(ownerPetsData);
        }
Esempio n. 11
0
        public ActionResult Post(string tfn)
        {
            if (string.IsNullOrEmpty(tfn))
            {
                return(Ok(Enum.GetName(ValidationResponse.Invalid)));
            }

            return(Ok(Enum.GetName(_validator.Validate(tfn))));
        }
        public async Task <PaymentResponse> Handle(MakePaymentCommand request, CancellationToken cancellationToken)
        {
            // Create ID for internal MakePayment event
            var id = Guid.NewGuid().ToString();

            // Server side validations
            var(isValid, validationErrors) = _validatorService.Validate(_validators, request);

            if (!isValid)
            {
                return(new PaymentResponse
                {
                    Id = id,
                    Status = "failure",
                    ValidationErrors = validationErrors,
                    Reason = "Failed to validate payment details"
                });
            }

            // Forward payment request
            var response = await _bankService.ProcessPayment(request);

            if (response == null)
            {
                return(new PaymentResponse
                {
                    Id = id,
                    Status = "failure",
                    ValidationErrors = validationErrors,
                    Reason = "Failed to process payment details"
                });
            }

            var payment = new Payment()
            {
                Id                = id,
                BankPaymentId     = response.BankPaymentId,
                MerchantPaymentId = request.MerchantPaymentId,
                BillingDetails    = request.BillingDetails,
                Currency          = request.Currency,
                Amount            = request.Amount,
                Status            = response.Status,
                Reason            = response.Reason,
                ValidationErrors  = response.ValidationErrors,
                Timestamp         = DateTime.UtcNow,
            };

            // Save payment event to payments DB (failure or success)
            await _paymentsService.CreateAsync(payment);

            // Map from payment to PaymentResponse object
            var paymentResponse = _paymentMapper.Map(payment);

            return(paymentResponse);
        }
Esempio n. 13
0
        private IEnumerable <int> GetNumbers(string input)
        {
            var numbers   = _inputProcessorService.ProcessInput(input);
            var exception = _validatorService.Validate(numbers);

            if (exception != null)
            {
                throw exception;
            }
            return(numbers);
        }
Esempio n. 14
0
        public object ValidateAndCreateAccessToken(AudienceCredentials credentials)
        {
            User audience = null;

            _loginUserValidators.Validate(credentials);
            audience = _accessTokenRepository.ValidateLoginUserCedential(credentials);

            var userByEmail = _accessTokenRepository.GetUserByEmail(credentials.Username);

            if (audience != null)
            {
                if (!audience.IsVerified)
                {
                    var loginErrorResponse = new EmailUnverifiedResponse
                    {
                        UserId     = audience.Id,
                        IsVerified = audience.IsVerified,
                        Message    = "Din emailadress är inte verifierad än. Vill du att vi skickar ett nytt mail?"
                    };
                    var validateLoginErrorResponse = new LoginUnVerifiedEmailResponse
                    {
                        data = loginErrorResponse
                    };
                    return(validateLoginErrorResponse);
                }

                credentials.Id      = audience.Id;
                audience.DeviceId   = credentials.DeviceId;
                audience.DeviceType = credentials.DeviceType;

                var loginMap = LoginMapper(credentials);
                _accessTokenRepository.UpdateDeviceDetail(loginMap);
                return(TokenMapper(audience, _accessTokenRepository.CreateToken(audience)));
            }
            else if (userByEmail != null)
            {
                if (string.IsNullOrEmpty(userByEmail.Password) && !string.IsNullOrEmpty(userByEmail.AuthId))
                {
                    var facebookUserErrorMessage = new FacebookLoginErrorResponse
                    {
                        Message = "Du är registrerad med Facebook. Försök att logga in med Facebook."
                    };
                    return(facebookUserErrorMessage);
                }
                else
                {
                    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Ogilitia inloggningsuppgifter.");
                }
            }
            else
            {
                throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Ogilitia inloggningsuppgifter.");
            }
        }
Esempio n. 15
0
 public IPerson CreateTestPerson(IValidationResult result, IValidatorService validator, string firstName, string lastName, string emailId)
 {
     result = validator.Validate(firstName, lastName, emailId);
     if (result.IsSuccess == true)
     {
         return new Person(firstName, lastName, emailId);
     }
     else
     {
         throw new ValidationException() { Invalid = result.InvalidFields, };
     }
 }
Esempio n. 16
0
        /// <summary>
        /// Método que que se encarga de registrar una entidad en el repositorio del catálogo que lo usa, antes de invocar al guardado del repositorio se ejecuta la validación correspondiente.
        /// </summary>
        /// <param name="_entity">Entidad que se va a registrar en el repositorio</param>
        /// <returns>Retorna el Guid del registro creado.</returns>
        public Guid Create(TEntity _entity)
        {
            var DateServer = getterDateRepository.GetDateTime();

            validatorService.Validate(_entity);
            _entity.AddedDate    = DateServer;
            _entity.ModifiedDate = DateServer;
            _entity.IsActive     = true;
            Guid id = creatorRepository.Create(_entity);

            return(id);
        }
Esempio n. 17
0
 public IPerson CreateTestPerson(IValidationResult result, IValidatorService validator, string firstName, string lastName, DateTime dateOfBirth)
 {
     result = validator.Validate(firstName, lastName, dateOfBirth);
     if (result.IsSuccess == true)
     {
         return(new Person(firstName, lastName, dateOfBirth));
     }
     else
     {
         throw new ValidationException()
               {
                   Invalid = result.InvalidFields,
               };
     }
 }
Esempio n. 18
0
        public async Task ProcessStage1(Guid importId, ExecutionContext executionContext)
        {
            await _validatorService.Validate(importId, executionContext)
            .OnSuccessDo(async result =>
            {
                await _dataImportService.Update(importId,
                                                rowsPerBatch: result.RowsPerBatch,
                                                totalRows: result.ImportableRowCount,
                                                numBatches: result.NumBatches,
                                                geographicLevels: result.GeographicLevels);
            })
            .OnFailureDo(async errors =>
            {
                await _dataImportService.FailImport(importId, errors);

                _logger.LogError($"Import {importId} FAILED ...check log");
            });
        }
        public async Task ProcessStage1(ImportMessage message, ExecutionContext executionContext)
        {
            var subjectData = await GetSubjectDataFromMainDataFile(message);

            await _validatorService.Validate(subjectData, executionContext, message)
            .OnSuccessDo(async result =>
            {
                message.RowsPerBatch = result.RowsPerBatch;
                message.TotalRows    = result.FilteredObservationCount;
                message.NumBatches   = result.NumBatches;
                await _batchService.UpdateStoredMessage(message);
            })
            .OnFailureDo(async errors =>
            {
                await _batchService.FailImport(message.Release.Id,
                                               message.DataFileName,
                                               errors);

                _logger.LogError($"Import FAILED for {message.DataFileName}...check log");
            });
        }
Esempio n. 20
0
        public bool AddUserCardDetails(UserCardDetailModel model)
        {
            try
            {
                _userCardDetailValidators.Validate(model);
                var errorMessage        = string.Empty;
                var userCardDetailModel = new UserCardDetailModel();
                var user = _accessTokenRepository.GetUser(model.UserId.Value);

                if (user == null)
                {
                    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Användare finns inte.");
                }

                //var cardExist = _userRepository.GetUserCardDetailByCardNumber(model.CardNumber, model.UserId.Value);

                //if (cardExist != null)
                //    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Kortnummer finns redan.");


                //if (response.CvcCheck.ToLower() != "pass")
                //    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Card is not valid.");

                //var isValidCard = CreditCardHelper.IsCardNumberValid(model.CardNumber, out errorMessage);
                //if (!isValidCard)
                //    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", errorMessage);


                var updateCard = UpdateUserCard(model);
                if (!updateCard)
                {
                    var customers = new StripeCustomerService();

                    StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripPublishKey"]);
                    var tokenService = new StripeTokenService();

                    var token = tokenService.Create(new StripeTokenCreateOptions {
                        Card = new StripeCreditCardOptions {
                            Cvc = model.CVC.ToString(), Number = model.CardNumber.Replace(" ", ""), ExpirationMonth = model.ExpiredMonth, ExpirationYear = model.ExpiredYear
                        }
                    });

                    StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripSecretKey"]);
                    var customerId = customers.Create(new StripeCustomerCreateOptions {
                        SourceToken = token.Id
                    });
                    var cardType           = CreditCardHelper.GetCardType(model.CardNumber);
                    StripeCardService card = new StripeCardService();
                    var cardToken          = CreditCardHelper.GetCardTokens(token.StripeCard.Brand);
                    var response           = card.Create(customerId.Id, new StripeCardCreateOptions {
                        SourceToken = cardToken
                    });

                    var userCardDetails = new UserCardDetails
                    {
                        UserId       = model.UserId,
                        CardNumber   = _cryptoGraphy.EncryptString(model.CardNumber),
                        CardType     = cardType.ToString(),
                        ExpiredMonth = model.ExpiredMonth,
                        ExpiredYear  = model.ExpiredYear,
                        CVC          = model.CVC,
                        CreditCardId = customerId.Id,
                        PhoneNumber  = model.PhoneNumber,
                        CreatedDate  = DateTime.Now,
                        ModifiedDate = DateTime.Now
                    };
                    var userCardDetailId = _userRepository.AddUserCardDetails(userCardDetails);
                }
            }
            catch (StripeException ex)
            {
                switch (ex.StripeError.ErrorType)
                {
                case "card_error":
                    throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", ex.StripeError.Message);

                case "api_connection_error":
                    break;

                case "api_error":
                    break;

                case "authentication_error":
                    break;

                case "invalid_request_error":
                    break;

                case "rate_limit_error":
                    break;

                case "validation_error":
                    break;

                default:
                    // Unknown Error Type
                    break;
                }
            }
            return(true);
        }
Esempio n. 21
0
 private Task <bool> Validate(SimpleTask simpleTask)
 {
     return(new TaskFactory().StartNew(() => _validatorService.Validate(simpleTask)));
 }
Esempio n. 22
0
        public object ValidateAndCreateUser(RegisterModel model)
        {
            var  message  = string.Empty;
            User authUser = null;

            //_userRegistrationValidators.Validate(model);

            if (!string.IsNullOrEmpty(model.AuthId))
            {
                var oAuthIdExist = false;
                var emailIdExist = false;
                _accessTokenRepository.CheckOAuthUserExistsAndCheckEmailExists(model.AuthId, model.UserName, out oAuthIdExist, out emailIdExist);
                if (emailIdExist)
                {
                    var user = _accessTokenRepository.GetUserByEmail(model.UserName);
                    if (user != null)
                    {
                        model.Id = user.Id;
                        var loginMap = LoginWithFacebookMapperForOAuthUserEmail(model);
                        _accessTokenRepository.OAuthEmailUserUpdate(loginMap);
                        authUser = user;
                        var emailToken = TokenMapper(authUser as User, _accessTokenRepository.CreateToken(authUser));
                        return(emailToken);
                    }
                }
                else
                {
                    var user = UserAudienceCredentialsMapper(model);
                    user.IsVerified = true;
                    user.UserCode   = Convert.ToString(Guid.NewGuid());
                    SaveUserCode(user.UserCode);
                    var userId = _accessTokenRepository.CreateNewUser(user);
                    user.Id  = userId;
                    authUser = user;
                    message  = "Användare tillagd.";
                    var emailToken = TokenMapper(authUser as User, _accessTokenRepository.CreateToken(authUser), message);
                    return(emailToken);
                }
            }
            else
            {
                _userRegistrationValidators.Validate(model);
                var user = UserAudienceCredentialsMapper(model);
                user.UserCode = Convert.ToString(Guid.NewGuid());
                SaveUserCode(user.UserCode);
                var userId = _accessTokenRepository.CreateNewUser(user);
                user.Id  = userId;
                authUser = user;
                message  = "Användare tillagd.";
            }
            var webUrl = ConfigurationManager.AppSettings["WebUrl"];

            var fields = new StringDictionary
            {
                { "signUpUrl", string.Format("{0}{1}{2}{3}", Convert.ToString(webUrl), "/Email/ConfirmEmail?id=", _cryptoGraphy.EncryptString(Convert.ToString(authUser.Id)), "&email=" + _cryptoGraphy.EncryptString(authUser.Email)) }
            };

            message = "Vi har sänt dig ett verifikationsemail, vänligen verifiera din emailadress.";

            var htmlBody = _fm.ReadFileContents(GetMailerTemplatePath("html", "CreateUser")).ReplaceMatch(fields);

            _emailNotifier.SendEmail(authUser.Email, htmlBody, "Verify Link");
            var registerResponse = new RegisterResponse
            {
                UserId  = authUser.Id,
                Message = message
            };

            //var token = TokenMapper(authUser as User, _accessTokenRepository.CreateToken(authUser));
            //token.Message = message;
            return(registerResponse);
        }