public void HeroRepository_Update_True()
        {
            var validationResult = new ValidationResult();
            //Arrange
            var returnSameHero = new Hero()
            {
                HeroName  = "test",
                HeroPrice = 15
            };
            //Arrange
            var returnNull = new Hero()
            {
                HeroName  = "test",
                HeroPrice = 15
            };

            //Act
            var repoSameHero = MockRepository.GenerateStub <IHeroRepository>();

            repoSameHero.Stub(s => s.GetByName(returnSameHero.HeroName)).Return(returnSameHero);

            var repoNull = MockRepository.GenerateStub <IHeroRepository>();

            repoNull.Stub(s => s.GetByName(returnNull.HeroName)).Return(null);

            validationResult.Add(new CreateAndUpdateHeroValidation(repoSameHero).Validate(returnSameHero));
            validationResult.Add(new CreateAndUpdateHeroValidation(repoNull).Validate(returnNull));

            //Assert
            Assert.IsTrue(validationResult.IsValid);
        }
Beispiel #2
0
        public ValidationResult Gravar(Aviao aviao)
        {
            //validate
            if (aviao.Modelo.IsNullOrEmptyOrWhiteSpace())
            {
                validationResult.Add("Modelo não preenchido");
                return(validationResult);
            }

            if (aviao.QuantidadeDePassageiros == 0)
            {
                validationResult.Add("Quantidade de Passageiros não preenchido");
                return(validationResult);
            }

            //add or update
            if (aviao.AviaoId == 0)
            {
                base.Adicionar(aviao);
            }
            else
            {
                base.Atualizar(aviao);
            }

            return(validationResult);
        }
Beispiel #3
0
        public void Hero_IsConsistent_False()
        {
            var validationResult = new ValidationResult();
            //Arrange
            var heroPriceBelow = new Hero()
            {
                HeroName  = "hfghf ",
                HeroPrice = 5
            };

            var hero = new Hero()
            {
                HeroName       = "hfga////////434hfgh",
                HeroPrice      = 26,
                HeroFreeToPlay = true
            };

            //Act
            heroPriceBelow.IsValid();
            validationResult.Add(heroPriceBelow.ValidationResult);

            hero.IsValid();
            validationResult.Add(hero.ValidationResult);

            //Assert
            Assert.IsFalse(validationResult.IsValid);

            Assert.IsTrue(validationResult.Erros.Any(a => a.Message == "Hero has invalid name. Please chose another."));
            Assert.IsTrue(validationResult.Erros.Any(a => a.Message == "Hero has invalid price. Please chose another."));
            Assert.IsTrue(validationResult.Erros.Any(a => a.Message == "Hero has invalid type. Please try again."));
        }
Beispiel #4
0
        public ValidationResult ValidateConditionsAreNotChanged(IReadOnlyList <Condition> newConditions,
                                                                IReadOnlyList <Condition> oldConditions)
        {
            var validationResult = new ValidationResult();

            if (newConditions.Count != oldConditions.Count)
            {
                validationResult.Add(CampaignConditionsValidationMessage);
                return(validationResult);
            }

            foreach (var condition in newConditions)
            {
                var oldCondition = oldConditions.FirstOrDefault(c => condition.Id == c.Id);
                if (oldCondition == null)
                {
                    validationResult.Add(CampaignConditionsValidationMessage);
                    return(validationResult);
                }

                validationResult.Add(ValidateConditionPropertiesAreNotChanged(condition, oldCondition));
            }

            return(validationResult);
        }
        public ValidationResult Gravar(Servico servico)
        {
            //validate
            if (servico.Nome.IsNullOrEmptyOrWhiteSpace())
            {
                validationResult.Add("Nome não preenchido");
                return(validationResult);
            }

            if (servico.Descricao.IsNullOrEmptyOrWhiteSpace())
            {
                validationResult.Add("Descricao não preenchido");
                return(validationResult);
            }

            //add or update
            if (servico.ServicoId == 0)
            {
                base.Adicionar(servico);
            }
            else
            {
                base.Atualizar(servico);
            }

            return(validationResult);
        }
        public ValidationResult ValidateHaveInvalidOrEmptyIds(IReadOnlyList <Guid> newIds, IReadOnlyList <Guid> oldIds)
        {
            var validationResult = new ValidationResult();

            var editedGuids = newIds.Where(id => id != Guid.Empty);

            if (editedGuids.Count() != editedGuids.Distinct().Count())
            {
                validationResult.Add(DublicatedContentsIds);
            }

            foreach (var newId in newIds)
            {
                // We add check for Id here because Id being Guid Empty is a valid case, it means a new content should be created
                if (newId == Guid.Empty)
                {
                    continue;
                }

                var oldContent = oldIds.FirstOrDefault(c => newId == c);

                if (oldContent == Guid.Empty)
                {
                    validationResult.Add(string.Format(CampaignEarnContentInvalidIdMessage, newId));
                }
            }

            return(validationResult);
        }
Beispiel #7
0
        public virtual ValidationResult Add(TEntity entity)
        {
            if (!_validationResult.IsValid)
            {
                return(_validationResult);
            }

            var selfValidationEntity = entity as ISelfValidation;

            if (selfValidationEntity != null && !selfValidationEntity.IsValid)
            {
                return(selfValidationEntity.ValidationResult);
            }

            if (!_dapperRepository.Add(entity))
            {
                _validationResult.Add(string.Format("添加实体对象{0}失败", entity.GetType().FullName));
            }
            var baseEntity = entity as BaseEntity;

            if (baseEntity != null)
            {
                _validationResult.SetData(LsConstant.IdKey, baseEntity.Id);
            }

            return(_validationResult);
        }
Beispiel #8
0
        public ValidationResult Adicionar(TEntity entity, IDbTransaction transaction = null,
                                          int?commandTimeout = default(int?))
        {
            if (!_validationResult.IsValid)
            {
                return(ValidationResult);
            }

            var selfValidationEntity = entity as ISelfValidation;

            if (selfValidationEntity != null && !selfValidationEntity.IsValid)
            {
                return(selfValidationEntity.ValidationResult);
            }

            var adicionou = _repositorio.Adicionar(entity);

            if (adicionou == null)
            {
                _validationResult.Add(
                    new ValidationError(
                        "A Entidade que você está tentando gravar está nula, por favor tente novamente!" + entity));
            }
            return(_validationResult);
        }
Beispiel #9
0
        public void ValidatorResultFromMultipleFailureShouldReturnFalure()
        {
            var message1 = "message 1";
            var message2 = "message 2";
            var message3 = "message 3";
            var message4 = "message 4";

            var result1 = ValidationResult.Failure(message1);
            var result2 = ValidationResult.Failure(message2);
            var result3 = ValidationResult.Failure(message3);
            var result4 = ValidationResult.Failure(message4);

            var result = new ValidationResult();

            result.Add(result1);
            result.Add(result2);
            result.Add(result3);
            result.Add(result4);

            result.Should().BeOfType(typeof(ValidationResult));
            result.IsSuccess.Should().BeFalse();
            result.IsFailure.Should().BeTrue();
            result.ErrorCount.Should().Be(4);
            result.Errors.Should().Contain(message1);
            result.Errors.Should().Contain(message2);
            result.Errors.Should().Contain(message3);
            result.Errors.Should().Contain(message4);
        }
Beispiel #10
0
        public ValidationResult Gravar(Estado aviao)
        {
            //validate
            if (aviao.NomeUf.IsNullOrEmptyOrWhiteSpace())
            {
                validationResult.Add("Nome não preenchido");
                return(validationResult);
            }

            if (aviao.SiglaUf.IsNullOrEmptyOrWhiteSpace())
            {
                validationResult.Add("Sigla Uf não preenchido");
                return(validationResult);
            }

            //add or update
            if (aviao.EstadoId == 0)
            {
                base.Adicionar(aviao);
            }
            else
            {
                base.Atualizar(aviao);
            }

            return(validationResult);
        }
Beispiel #11
0
        private ValidationResult ValidateConnectionInfo(ConnectionInfo connectionInfo)
        {
            var validationResult = new ValidationResult();

            if (connectionInfo.GocdApiUri.IsTrimmedNullOrEmpty() || Uri.TryCreate(connectionInfo.GocdApiUri, UriKind.Absolute, out _) == false)
            {
                validationResult.Add("You must supply a valid url for the Gocd Api.", nameof(connectionInfo.GocdApiUri));
            }

            if (connectionInfo.GocdWebUri.IsTrimmedNullOrEmpty() || Uri.TryCreate(connectionInfo.GocdWebUri, UriKind.Absolute, out _) == false)
            {
                validationResult.Add("You must supply a valid url for the Gocd Website.", nameof(connectionInfo.GocdWebUri));
            }

            if (connectionInfo.Username.IsTrimmedNullOrEmpty())
            {
                validationResult.Add("You must supply a username.", nameof(connectionInfo.Username));
            }

            if (connectionInfo.Password.IsTrimmedNullOrEmpty())
            {
                validationResult.Add("You must supply a password.", nameof(connectionInfo.Password));
            }

            if (connectionInfo.PollingIntervalSeconds < 5)
            {
                validationResult.Add("Polling interval must be at least 5 seconds.", nameof(connectionInfo.PollingIntervalSeconds));
            }

            return(validationResult);
        }
        public ValidationResult ValidateUpdate(CampaignDetails newCampaign, CampaignDetails oldCampaign)
        {
            var validationResult = new ValidationResult();

            if (newCampaign.Conditions.Any())
            {
                validationResult.Add(_conditionValidationService.ValidateConditionsBonusTypes(newCampaign.Conditions));
                validationResult.Add(_conditionValidationService.ValidateConditionsPartnersIds(newCampaign.Conditions));
            }

            if (!validationResult.IsValid)
            {
                return(validationResult);
            }

            if (newCampaign.Contents.Any())
            {
                validationResult.Add(_contentValidationService
                                     .ValidateHaveInvalidOrEmptyIds(newCampaign.Contents.Select(c => c.Id).ToList(),
                                                                    oldCampaign.Contents.Select(c => c.Id).ToList()));
            }

            if (!validationResult.IsValid)
            {
                return(validationResult);
            }

            // Note: Removed old earn rules validation on edit allowing modification of the earn rule at any time
            //switch (oldCampaign.CampaignStatus)
            //{
            //    case CampaignStatus.Active:
            //        {
            //            validationResult.Add(ValidateUpdateForActiveCampaign(newCampaign, oldCampaign));
            //            break;
            //        }
            //    case CampaignStatus.Inactive:
            //        {
            //            validationResult.Add(ValidateUpdateForInactiveCampaign(newCampaign, oldCampaign));
            //            break;
            //        }
            //    case CampaignStatus.Completed:
            //        {
            //            validationResult.Add(ValidateUpdateForCompletedCampaigns(newCampaign, oldCampaign));
            //            break;
            //        }
            //    case CampaignStatus.Pending:
            //        {
            //            validationResult.Add(ValidateUpdateForPendingCampaigns(newCampaign, oldCampaign));
            //            break;
            //        }
            //    default:
            //        throw new ArgumentOutOfRangeException();
            //}

            return(validationResult);
        }
Beispiel #13
0
        /// <summary>
        /// validate Validation
        /// </summary>
        /// <param name="v">Validation</param>
        /// <returns>ValidationResult</returns>
        public static ValidationResult Validate(Validation v)
        {
            ValidationResult res = new ValidationResult();

            // nothing to validate
            if (v == null)
            {
                return(res);
            }

            // validate http status code
            if (v.StatusCode < 100 || v.StatusCode > 599)
            {
                res.Failed = true;
                res.ValidationErrors.Add("statusCode: invalid status code: " + v.StatusCode.ToString(CultureInfo.InvariantCulture));
            }

            // validate ContentType
            if (v.ContentType != null && v.ContentType.Length == 0)
            {
                res.Failed = true;
                res.ValidationErrors.Add("contentType: ContentType cannot be empty");
            }

            // validate ExactMatch
            if (v.ExactMatch != null && v.ExactMatch.Length == 0)
            {
                res.Failed = true;
                res.ValidationErrors.Add("exactMatch: exactMatch cannot be empty string");
            }

            //validate lengths
            res.Add(ValidateLength(v));

            // validate MaxMilliSeconds
            if (v.MaxMilliseconds != null && v.MaxMilliseconds <= 0)
            {
                res.Failed = true;
                res.ValidationErrors.Add("maxMilliseconds: maxMilliseconds cannot be less than zero");
            }

            // validate Contains
            res.Add(ValidateContains(v.Contains));

            // validate perfTarget
            res.Add(Validate(v.PerfTarget));

            // validate json object
            res.Add(Validate(v.JsonObject));

            // validate json array parameters
            res.Add(Validate(v.JsonArray));

            return(res);
        }
Beispiel #14
0
        private void ValidateIfEntitiesExists(Player player, Hero hero, ref ValidationResult validation)
        {
            if (player == null)
            {
                validation.Add(new ValidationError("Invalid Player"));
            }

            if (hero == null)
            {
                validation.Add(new ValidationError("Invalid Hero"));
            }
        }
Beispiel #15
0
 private void ValidateBuyItem(Player player, Hero hero, ref ValidationResult validation)
 {
     if (player.PlayerHeroes.Where(t => t.HeroId == hero.HeroId).ToList().Count > 0)
     {
         validation.Add(new ValidationError("You already have this hero. Please chose another"));
     }
     else
     {
         if (player.PlayerMoney < hero.HeroPrice && hero.HeroFreeToPlay == false)
         {
             validation.Add(new ValidationError("You don't have money to buy this hero. Please chose another"));
         }
     }
 }
        public void HeroAppService_Add_True()
        {
            var validationResult = new ValidationResult();
            var viewModel        = new HeroViewModel()
            {
                HeroName  = "test",
                HeroPrice = 23,
                HeroType  = new HeroTypeViewModel()
                {
                    HeroTypeName = "test"
                }
            };

            var repo = MockRepository.GenerateStub <IHeroRepository>();

            repo.Stub(s => s.GetByName(viewModel.HeroName)).Return(null);

            var repoType = MockRepository.GenerateStub <IHeroTypeRepository>();

            repoType.Stub(s => s.GetByName(viewModel.HeroType.HeroTypeName)).Return(new HeroType());

            var appService = new HeroAppService(new HeroService(repo, repoType));

            validationResult.Add(appService.Add(viewModel));

            Assert.IsTrue(validationResult.IsValid);
        }
        public void HeroAppService_UpdateKeyValue_True()
        {
            var validationResult = new ValidationResult();
            var viewModel        = new HeroViewModel()
            {
                HeroName  = "test",
                HeroPrice = 5,
                HeroType  = new HeroTypeViewModel()
                {
                    HeroTypeName = "test"
                }
            };
            var keyValue = new Dictionary <string, string>();

            keyValue.Add("HeroName", "asd");
            keyValue.Add("HeroDeleted", "true");

            var repo = MockRepository.GenerateStub <IHeroRepository>();

            repo.Stub(s => s.GetByName(viewModel.HeroName)).Return(null);

            var repoType = MockRepository.GenerateStub <IHeroTypeRepository>();

            repoType.Stub(s => s.GetByName("test")).Return(new HeroType());

            var appService = new HeroAppService(new HeroService(repo, repoType));

            validationResult.Add(appService.Update(viewModel, keyValue));

            Assert.IsTrue(validationResult.IsValid);
        }
Beispiel #18
0
        public ValidationResult AdicionarAtividadeFila(string nomeFila, long atividadeId)
        {
            var retorno         = new ValidationResult();
            var fila            = _servicoFila.ObterFilasPorNome(nomeFila);
            var valorEncontrado = false;

            if (fila != null)
            {
                if (fila.Any())
                {
                    valorEncontrado = true;
                }
            }

            if (!valorEncontrado)
            {
                retorno.Add(
                    new ValidationError(
                        "Não foi possível vincular a atividade a uma determinada fila: nenhuma fila retornada com o nome:" +
                        nomeFila));
                return(retorno);
            }

            var atividadeFila = new AtividadeFila(atividadeId, fila.FirstOrDefault().Id);

            retorno = Adicionar(atividadeFila);
            return(retorno);
        }
Beispiel #19
0
        public ValidationResult EnviarEmail(string url, string emailUsuario)
        {
            var contaPadrao = _configuracaoContasEmailsServico.ObterContaPadrao();
            ValidationResult retorno;

            if (contaPadrao == null)
            {
                retorno = new ValidationResult();
                retorno.Add(new ValidationError("Conta Padrão não cadastrada na Ferramenta"));
                return(retorno);
            }

            var destinatario = new List <string> {
                emailUsuario
            };

            var emailServico = new EnvioEmail();
            var html         = new StringBuilder();

            html.Append("<p><strong>Ol&aacute;,</strong></p>");
            html.Append(
                "<p>Obrigado por entrar em contato sobre a atualiza&ccedil;&atilde;o da sua senha.Para prosseguir basta <span style='color: #ff0000;'><a href='" +
                url + "' style='color: #ff0000;'>clicar aqui</a>.</span></p>");
            html.Append("<p>Caso n&atilde;o tenha solicitado a troca de senha por favor ignore este email.</p>");
            html.Append("<p>Att.</p>");

            retorno = emailServico.Enviar(contaPadrao.Email, contaPadrao.Descricao, contaPadrao.UsuarioEmail,
                                          contaPadrao.SenhaEmail, contaPadrao.NecessarioSsl, contaPadrao.PortaServidorSaida,
                                          contaPadrao.ServidorSmtp, "Atualização de Senha", html.ToString(), destinatario, null,
                                          null, null, null);

            return(retorno);
        }
Beispiel #20
0
        public dynamic Adicionar(Lotacao lotacao)
        {
            ///ValidationResult.Add(_servico.Adicionar(lotacao, _uow.BeginTransaction()));

            // ValidationResult.Add(lotacao.ValidationResult);

            //if (!lotacao.IsValid)
            //    return lotacao.ValidationResult;
            ValidationResult.Clear();



            var lotacaoAdicionada = _servico.Adicionar(lotacao, _uow.BeginTransaction());

            ValidationResult.Add(_servico.ValidationResult);

            if (_servico.ValidationResult.IsValid)
            {
                _uow.Commit();
            }
            else
            {
                _uow.Rollback();
            }

            return(lotacaoAdicionada);
        }
Beispiel #21
0
        ///<summary>
        /// validate JsonArray.ByIndex
        ///</summary>
        ///<param name="byIndexList">list of JsonPropertyByIndex</param>
        /// <returns>ValidationResult</returns>
        public static ValidationResult Validate(List <JsonPropertyByIndex> byIndexList)
        {
            ValidationResult res = new ValidationResult();

            // null check
            if (byIndexList == null || byIndexList.Count == 0)
            {
                return(res);
            }

            // validate parameters
            foreach (var f in byIndexList)
            {
                // validate index
                if ((f.Index) < 0)
                {
                    res.Failed = true;
                    res.ValidationErrors.Add("index: index cannot be less than 0");
                }

                // validate field, value, validation
                if (f.Field == null && f.Value == null && f.Validation == null)
                {
                    res.Failed = true;
                    res.ValidationErrors.Add("field: all fields cannot be null");
                }

                // validate recursively
                res.Add(Validate(f.Validation));
            }

            return(res);
        }
Beispiel #22
0
        public override ValidationResult ValidarAdicicao(Justificativa entity)
        {
            ValidationResult result = new ValidationResult();

            try
            {
                entity.DataInclusao = DateTime.Now;
                entity.Acao         = null; entity.Motivo = null;
                MotivoAcao motivo = _motivoAcaoService.BuscarPorId(entity.IdMotivo);
                MotivoAcao acao   = _motivoAcaoService.BuscarPorId(entity.IdAcao);
                if ((motivo?.ValidarObrigatoriedadeComplementoDescricao()).GetValueOrDefault() && string.IsNullOrEmpty(entity.MotivoJustificativa))
                {
                    throw new Exception("Descrição do motivo é obrigatória");
                }
                if ((acao?.ValidarObrigatoriedadeComplementoDescricao()).GetValueOrDefault() && string.IsNullOrEmpty(entity.AcaoJustificativa))
                {
                    throw new Exception("Descrição da ação é obrigatória");
                }
            }
            catch (Exception e)
            {
                result.Add(e.Message);
            }

            return(result);
        }
Beispiel #23
0
 public ValidationResult SaveChanges()
 {
     try
     {
         var dados = this.dbContext.SaveChanges();
     }
     //EntityValidationException
     //catch (Microsoft.EntityFrameworkCore.DbUpdateException   exValidation)
     //{
     //    var erros = exValidation.Entries.ToList();
     //    if (erros.Any())
     //    {
     //        erros.ForEach(e => e.ValidationErrors.ToList().ForEach(ev => validationResult.Add($"Erro de Validção ao Gravar: {ev.ErrorMessage}")));
     //    }
     //    else
     //    {
     //        validationResult.Add(exValidation.Message);
     //    }
     //}
     catch (Exception ex)
     {
         validationResult.Add(ex.Message);
     }
     return(validationResult);
 }
        public void SaveAll()
        {
            if (string.IsNullOrWhiteSpace(_projectPath))
            {
                throw new Exception("Project path cannot be empty");
            }

            if (!Validate())
            {
                // We show errors but continue save operation
                OpenSpecialWindow("Output", EditWindowType.Output);
            }

            var project = AssembleStoreProject();
            var renames = FindAllRenames();

            try
            {
                _projectLoader.SaveAll(project, _projectPath, renames);
                ResetDirty();
            }
            catch (Exception exc)
            {
                var cr = new ValidationOutputItem {
                    LocationType = ValidationLocationType.Project, Message = "Operation Save All failed: " + exc.Message,
                    Type         = ValidationResultTypes.Error
                };

                ValidationResult.Add(cr);
                OpenSpecialWindow("Output", EditWindowType.Output);
            }
        }
Beispiel #25
0
 public ValidationResult Validate(User userToValidate)
 {
     var result =  new ValidationResult();
     if(String.IsNullOrEmpty(userToValidate.LastName))
     {
         result.Add("Last Name Required");
     }
     if (String.IsNullOrEmpty(userToValidate.FirstName))
     {
         result.Add("First Name Required");
     }
     //        if (String.IsNullOrEmpty(userToValidate.Username))
     //        {
     //            result.Add("Username Required");
     //        }
     return result;
 }
Beispiel #26
0
 /// <summary>
 /// Validate this instance.
 /// </summary>
 protected override void Validate()
 {
     // TODO: Put magic strings into resources file
     if (string.IsNullOrEmpty(Message) || Message.Trim().Length == 0)
     {
         ValidationResult.Add($"Invalid Logging Message");
     }
 }
        public void ValidationResult_AddInfo_HasErrorShouldReturnFalse()
        {
            ValidationResult sut = new ValidationResult();

            sut.Add(new ValidationMessage(String.Empty, ValidationLevel.Info));

            Assert.That(sut.HasErrors, Is.EqualTo(false));
        }
        public void ValidationResult_AddFehler_HasErrorShouldReturnTrue()
        {
            ValidationResult sut = new ValidationResult();

            sut.Add(new ValidationMessage(String.Empty, ValidationLevel.Error));

            Assert.That(sut.HasErrors, Is.EqualTo(true));
        }
        private ValidationResult ValidateUpdateForCompletedCampaigns(CampaignDetails campaign, CampaignDetails oldCampaign)
        {
            var validationResult = new ValidationResult();

            if (!campaign.Name.Equals(oldCampaign.Name, StringComparison.Ordinal))
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.Name)));
            }

            if (!campaign.Description.Equals(oldCampaign.Description, StringComparison.Ordinal))
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.Description)));
            }

            if (!campaign.FromDate.Equals(oldCampaign.FromDate))
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.FromDate)));
            }

            if ((oldCampaign.ToDate == null && campaign.ToDate != null) ||
                (oldCampaign.ToDate != null && campaign.ToDate == null) ||
                (oldCampaign.ToDate != null && campaign.ToDate != null && !campaign.ToDate.Value.Equals(oldCampaign.ToDate.Value)))
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.ToDate)));
            }

            if (campaign.Reward != oldCampaign.Reward)
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.Reward)));
            }

            if (campaign.AmountInTokens != oldCampaign.AmountInTokens)
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.AmountInTokens)));
            }

            if (campaign.AmountInCurrency != oldCampaign.AmountInCurrency)
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.AmountInCurrency)));
            }

            if (campaign.IsEnabled != oldCampaign.IsEnabled)
            {
                validationResult.Add(string.Format(CampaignPropertyValidationMessage, nameof(campaign.IsEnabled)));
            }

            validationResult.Add(_conditionValidationService.ValidateConditionsAreNotChanged(campaign.Conditions,
                                                                                             oldCampaign.Conditions));

            return(validationResult);
        }
Beispiel #30
0
        public ValidationResult SetConnectionInfo(ConnectionInfo connectionInfo)
        {
            var validationResult = new ValidationResult();

            if (connectionInfo.GocdApiUri.IsTrimmedNullOrEmpty() || Uri.TryCreate(connectionInfo.GocdApiUri, UriKind.Absolute, out _) == false)
            {
                validationResult.Add("You must supply a valid url for the Gocd Api.", nameof(connectionInfo.GocdApiUri));
            }

            if (connectionInfo.GocdWebUri.IsTrimmedNullOrEmpty() || Uri.TryCreate(connectionInfo.GocdWebUri, UriKind.Absolute, out _) == false)
            {
                validationResult.Add("You must supply a valid url for the Gocd Website.", nameof(connectionInfo.GocdWebUri));
            }

            if (connectionInfo.Username.IsTrimmedNullOrEmpty())
            {
                validationResult.Add("You must supply a username.", nameof(connectionInfo.Username));
            }

            if (connectionInfo.Password.IsTrimmedNullOrEmpty())
            {
                validationResult.Add("You must supply a password.", nameof(connectionInfo.Password));
            }

            if (connectionInfo.PollingIntervalSeconds < 5)
            {
                validationResult.Add("Polling interval must be at least 5 seconds.", nameof(connectionInfo.PollingIntervalSeconds));
            }

            if (validationResult.IsValid == false)
            {
                return(validationResult);
            }

            Properties.Settings.Default.GocdApiUri = connectionInfo.GocdApiUri;
            Properties.Settings.Default.GocdWebUri = connectionInfo.GocdWebUri;
            Properties.Settings.Default.IgnoreCertificateErrors = connectionInfo.IgnoreCertificateErrors;
            Properties.Settings.Default.Password = connectionInfo.Password;
            Properties.Settings.Default.PollingIntervalSeconds = connectionInfo.PollingIntervalSeconds;
            Properties.Settings.Default.Username = connectionInfo.Username;
            Properties.Settings.Default.Save();
            Restart();

            return(validationResult);
        }
        private void CheckAmbiguities(ValidationResult result)
        {
            if(_element.Style.ContainerStyle != null &&
               _element.Style.ContainerStyleSelector != null)
            {
                result.Add(
                    Error.StyleSelectorAmbiguity(_element, _element.Type, "ContainerStyle")
                    );
            }

            if(_element.Style.HeaderTemplate != null &&
               _element.Style.HeaderTemplateSelector != null)
            {
                result.Add(
                    Error.TemplateSelectorAmbiguity(_element, _element.Type, "HeaderTemplate")
                    );
            }
        }
Beispiel #32
0
 public ValidationResult Deletar(Produto produto)
 {
     ValidationResult.Add(_servico.Deletar(produto, _uow.BeginTransaction()));
     if (ValidationResult.IsValid)
     {
         _uow.Commit();
     }
     return(ValidationResult);
 }
        /// <summary>
        /// Проверка валидности и отозванности с использованием пользовательской политики проверки
        /// </summary>
        /// <returns>Список сообщений/ошибок о валидности и/или отозвонности сертификата</returns>
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            //создаем цепочку сертификата
            X509Chain ch = new X509Chain();
            //отозванность сертификата хотим получать онлайн
            ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
            //хотим проверить всю цепочку сертификатов
            ch.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
            //проверка валидности самая полная
            ch.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;
            //строим цепочку на основе сертификата
            ch.Build(certificate.CertificateX509);

            result.Add("Проверка цепочки сертификатов:");
            result.AddNewLine();

            bool isValid = true;
            foreach (X509ChainElement element in ch.ChainElements)
            {
                bool verify = element.Certificate.Verify();

                isValid = isValid && verify;

                result.Add("  Субъект", element.Certificate.Subject);
                result.Add("  Издатель", element.Certificate.Issuer);
                result.Add("  Отпечаток", element.Certificate.Thumbprint);
                result.Add("  Серийный номер", element.Certificate.SerialNumber);
                result.Add("  Срок действия", String.Format("c {0} по {1}", element.Certificate.NotBefore, element.Certificate.NotAfter));
                result.Add(verify, "  Валиден", verify.ToString());
                result.AddNewLine();
            }

            result.Add(isValid, "Результат проверки цепочки", isValid ? "Сертификат прошел проверку" : "Сертификат НЕ прошел проверку");

            return result;
        }
        /// <summary>
        /// Проверка валидности и отозванности с использованием базовой политики проверки
        /// </summary>
        /// <returns>Список сообщений/ошибок о валидности и/или отозвонности сертификата</returns>
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            bool isValid = certificate.NotBefore < DateTime.Now && DateTime.Now < certificate.NotAfter;
            result.Add(isValid, "Срок действия", String.Format("{0} ({1} - {2})", isValid ? "действителен" : "истек", certificate.NotBefore.ToShortDateString(), certificate.NotAfter.ToShortDateString()));

            result.AddNewLine();

            bool isVerified = certificate.CertificateX509.Verify();
            result.Add(isVerified, "Базовая проверка", isVerified ? "сертификат действителен и не отозван (прошел стандартную проверку)" : "сертификат НЕ валиден (НЕ прошел стандартную проверку)");

            return result;
        }
        /// <summary>
        /// Проверка файла с подписью на валидность подписи
        /// </summary>
        /// <returns>Сообщения (или ошибки) о проверки подписи</returns>
        public ValidationResult Verify()
        {
            var result = new ValidationResult();

            if (this.Signature == null)
            {
                result.AddError("Отсутствует файл с подписью!");
                return result;
            }

            //Создаем пакет с подписью для проверки самой подписи
            SignedCms cms = null;

            if (this.Detached)
            {//отсоединенная подпись

                //создаем контейнер с оригинальными данными, подпись которых будет проверяться
                ContentInfo content = new ContentInfo(this.Original);

                //формируем пакет с оригинальными данными и параметрами подписи
                cms = new SignedCms(content, true);
            }
            else
            {// присоединенная подпись

                //формируем пустой пакет с данными
                //так как в случае присоединенной подписи
                //данные содержатся в самом подписанном файле
                cms = new SignedCms();
            }

            try
            {
                //декодируем файл, содержащий подпись
                //если вылетает ошибка - значит подпись не верна!!!
                cms.Decode(this.Signature);

                //возможно, информация о подписаниях отсутствует
                if (cms.SignerInfos.Count <= 0)
                {
                    result.AddError("Нет информации о подписях (возможно файл не подписан)");
                    return result;
                }

                result.AddInfo("Электронная Подпись Вернa.");
                result.AddNewLine();
                result.Add("Файл подписан следующим(и) сертификатом(и):");

                foreach (SignerInfo si in cms.SignerInfos)
                {
                    var certificate = new Certificate(si.Certificate);
                    if (_certificate == null)
                        _certificate = certificate;

                    result.AddNewLine();
                    result.Add(certificate.SerialNumber + " [" + certificate.Thumbprint + "]");
                    result.Add(certificate.SubjectCommonName);

                    //дергаем время подписания документа текущей подписью
                    for (int i = 0; i < si.SignedAttributes.Count; i++)
                    {
                        if (si.SignedAttributes[i].Oid.Value == "1.2.840.113549.1.9.5") // Oid время подписания
                        {
                            Pkcs9SigningTime pkcs9_time = new Pkcs9SigningTime(si.SignedAttributes[i].Values[0].RawData);
                            result.Add("Дата и Время подписания:  " + pkcs9_time.SigningTime.ToString());
                            break;
                        }
                    }
                }
            }
            catch
            {
                result.AddError("Подпись НЕ верна!");
            }

            return result;
        }
        /// <summary>
        /// Проверка сертификата на квалифицированность
        /// </summary>
        /// <returns>Список сообщений/ошибок о квалифицированности сертификата</returns>
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            bool isQualified = true;

            result.Add("Проверка квалифицированного сертификатов:");
            result.AddNewLine();

            string subjectCommonName = certificate.SubjectCommonName;

            if (subjectCommonName == "")
            {
                result.AddError("  Не задано наименование (CN) Субъекта");
                isQualified = false;
            }

            if (certificate.Organization == "")
            {
                result.AddError("  Не задана организация (O) Субъекта");
                isQualified = false;
            }

            if (certificate.Locality == "")
            {
                result.AddError("  Не задана расположение (L) Субъекта");
                isQualified = false;
            }

            if (certificate.Email == "")
            {
                result.AddError("  Не задан e-mail (E) Субъекта");
                isQualified = false;
            }

            if (certificate.INN.Trim().Length != 12)
            {
                result.AddError("  ИНН Субъекта должен состоять из 12 знаков");
                isQualified = false;
            }

            if (String.IsNullOrEmpty(certificate.OGRN))
            {
                result.AddError("  Не задан ОГРН Субъекта");
                isQualified = false;
            }

            int CN_fio = 0;
            int CN_org = 0;

            string[] splits = subjectCommonName.Split(new string[1] { " " }, StringSplitOptions.RemoveEmptyEntries);

            if (splits.Length == 3)
            {
                CN_fio += 3;

                if (splits[2].EndsWith("вич") || splits[2].EndsWith("вна"))
                    CN_fio += 1;
            }
            else CN_org += 2;

            if (subjectCommonName.Contains("\""))
                CN_org += 3;
            else CN_fio += 1;

            if (subjectCommonName.ToLower().Contains("ооо") || subjectCommonName.ToLower().Contains("зао") || subjectCommonName.ToLower().Contains("оао") || subjectCommonName.ToLower().Contains("пао") || subjectCommonName.ToLower().StartsWith("ип"))
                CN_org += 2;

            if (CN_fio > CN_org && String.IsNullOrEmpty(certificate.SNILS))
            {
                result.AddError("  Не задан СНИЛС Субъекта");
                isQualified = false;
            }

            result.Add(isQualified, "Результат проверки квалифицированного сертификата", isQualified ? "Сертификат является Квалифицированным" : "Сертификат НЕ является Квалифицированным");

            return result;
        }
        public ValidationResult Validate(ICertificate certificate)
        {
            var result = new ValidationResult();

            if (certificate == null)
                return result;

            result.Add("Отпечаток сертификата", certificate.Thumbprint);
            result.Add("Серийный номер сертификата", certificate.SerialNumber);

            result.AddNewLine(2);
            result.AddRange(new CertificateCommonValidator().Validate(certificate));

            result.AddNewLine(2);
            result.AddRange(new CertificateChainValidator().Validate(certificate));

            result.AddNewLine(2);
            result.AddRange(new CertificateQualifiedValidator().Validate(certificate));

            return result;
        }