Beispiel #1
0
        private void txtCNPJCPF_Validating(object sender, CancelEventArgs e)
        {
            string strCPF, strCNPJ = string.Empty;
            bool   exibeMsg = false;

            if (!string.IsNullOrEmpty(txtCNPJCPF.Text))
            {
                txtCNPJCPF.Text = txtCNPJCPF.Text.Trim().Replace(".", "").Replace("-", "").Replace("/", "");

                if (txtCNPJCPF.Text.Where(c => char.IsNumber(c)).Count() == 11)
                {
                    strCPF = Convert.ToInt64(txtCNPJCPF.Text).ToString(@"000\.000\.000\-00");
                    if (!ValidaCPF.IsCpf(strCPF))
                    {
                        exibeMsg = true;
                    }
                    else
                    {
                        txtCNPJCPF.Text = strCPF;
                    }
                }
                else if (txtCNPJCPF.Text.Where(c => char.IsNumber(c)).Count() >= 14)
                {
                    strCNPJ = Convert.ToInt64(txtCNPJCPF.Text).ToString(@"00\.000\.000\/0000\-00");
                    if (!ValidaCNPJ.IsCnpj(strCNPJ))
                    {
                        exibeMsg = true;
                    }
                    else
                    {
                        txtCNPJCPF.Text = strCNPJ;
                    }
                }
                else
                {
                    exibeMsg = true;
                }

                if (exibeMsg)
                {
                    epValidaDados.SetError(txtCNPJCPF, "CNPJ / CPF inválido.");
                    MessageBox.Show("CNPJ / CPF inválido.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
                else
                {
                    ClienteBLL = new ClienteBLL();
                    List <Cliente> cliList = ClienteBLL.getCliente(p => p.cnpj_cpf.Contains(txtCNPJCPF.Text));
                    if (cliList.Count() > 0)
                    {
                        if (cliList.FirstOrDefault().Id != Id)
                        {
                            epValidaDados.SetError(txtCNPJCPF, "CNPJ / CPF Já está cadastrado.");
                            MessageBox.Show("CNPJ / CPF Já está cadastrado.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            e.Cancel = true;
                        }
                    }
                }
            }
        }
 public static string ValidarCNPJEmpresa(string cnpj)
 {
     if (!ValidaCNPJ.IsCnpj(cnpj))
     {
         return("CNPJ não é válido");
     }
     return("");
 }
        public void Cadastrar()
        {
            PessoaJuridica pj = new PessoaJuridica();

            Console.Clear();
            Console.WriteLine("------------------------------");
            Console.WriteLine("CADASTRANDO PESSOA JURIDICA");
            Console.WriteLine("------------------------------");

            Console.WriteLine("Informe o ID");
            pj.Id = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Informe a razão social: ");
            pj.RazaoSocial = Console.ReadLine();

            Console.WriteLine("Informa o nome fantasia: ");
            pj.NomeFantasia = Console.ReadLine();

            bool isValidCnpj = false;

            while (!isValidCnpj)
            {
                Console.WriteLine("Informe o CNPJ: ");
                var cnpjDigitado = Console.ReadLine();
                if (ValidaCNPJ.IsCnpj(cnpjDigitado))
                {
                    pj.Cnpj     = cnpjDigitado;
                    isValidCnpj = true;
                }
                else
                {
                    Console.WriteLine("CNPJ Invalido! \n Por favor digite um CNPJ valido");
                }
            }

            Console.WriteLine("Informe Data abertura: (dd/mm/aaaa)\n");
            pj.DtAbertura = Convert.ToDateTime(Console.ReadLine());

            Console.WriteLine("Informe o logradouro: ");
            pj.Logradouro = Console.ReadLine();

            Console.WriteLine("Informe o numero do logradouro: ");
            pj.NumeroLogradouro = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Informe o nome da cidade: ");
            pj.Cidade = Console.ReadLine();

            Console.WriteLine("Informe a UF: ");
            pj.Uf = Console.ReadLine();

            _pessoaJuridicaDAO.CadastroPJuridica(pj);

            Console.WriteLine("Dados Salvos!");
        }
Beispiel #4
0
    public int ValidarForm()
    {
        Regex rg = new Regex(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");

        if (txtNome.Text == "" && txtTel.Text == "" && txtCNPJ.Text == "" && txtEmail.Text == "" && txtLog.Text == "" && txtSen.Text == "" && txtConsen.Text == "")
        {
            return(1);
        }
        else if (txtNome.Text == "")
        {
            return(2);
        }
        else if (txtTel.Text == "")
        {
            return(3);
        }
        else if (txtCNPJ.Text == "")
        {
            return(4);
        }
        else if (txtEmail.Text == "")
        {
            return(5);
        }
        else if (txtLog.Text == "")
        {
            return(6);
        }
        else if (txtSen.Text == "")
        {
            return(7);
        }
        else if (txtConsen.Text == "")
        {
            return(8);
        }
        if (ValidaCNPJ.IsCnpj(txtCNPJ.Text) == false)
        {
            return(9);
        }
        if (rg.IsMatch(txtEmail.Text) == false)
        {
            return(10);
        }
        if (txtSen.Text != txtConsen.Text)
        {
            return(11);
        }
        return(0);
    }
        public string Validar(tb_Empresa empresa)
        {
            if (!string.IsNullOrWhiteSpace(empresa.cnpj) && !ValidaCNPJ.IsCnpj(empresa.cnpj))
            {
                return("CNPJ Informado é inválido!.");
            }

            if (this.Tudo().FirstOrDefault(x => x.cnpj == empresa.cnpj &&
                                           // teste para desconsiderar a pesquisa pro próprio registro
                                           // ou seja, ele só dá mensagem por que acha o próprio cnpj da própria empresa que tá sendo editada...
                                           empresa.Id_Empresa != x.Id_Empresa
                                           ) != null)
            {
                return("CNPJ já cadastrado!");
            }

            if (string.IsNullOrWhiteSpace(empresa.nomefantasia))
            {
                return("Nome Fantasia não informado!");
            }

            if (string.IsNullOrWhiteSpace(empresa.razaosocial))
            {
                return("Razao social não informado!");
            }

            if (string.IsNullOrWhiteSpace(empresa.cnpj))
            {
                return("CNPJ não informado!");
            }

            if (string.IsNullOrWhiteSpace(empresa.endereco))
            {
                return("Endereço não informado!");
            }

            if (String.IsNullOrWhiteSpace(empresa.cidade))
            {
                return("Cidade não informado!");
            }

            if (string.IsNullOrWhiteSpace(empresa.estado))
            {
                return("Estado nao informado!");
            }

            return(string.Empty);
        }
Beispiel #6
0
        public ClienteValidator()
        {
            RuleFor(c => c)
            .NotNull()
            .OnAnyFailure((x) => throw new ArgumentException("Cliente inválido"));

            var InformeNome = "Informe o nome";

            RuleFor(c => c.Nome)
            .NotNull().WithMessage(InformeNome)
            .NotEmpty().WithMessage(InformeNome);

            var InformeEmail = "Informe o e-mail";

            RuleFor(c => c.Email)
            .NotNull().WithMessage(InformeEmail)
            .NotEmpty().WithMessage(InformeEmail);

            var InformeEndereco = "Informe o endereço";

            RuleFor(c => c.Enderecos)
            .NotNull().WithMessage(InformeEndereco)
            .Must(x => x.Count() > 0).WithMessage(InformeEndereco)
            .ForEach(x => x.SetValidator(new EnderecoValidator()));

            var InformeTelefone = "Informe um telefone";

            RuleFor(c => c.Telefones)
            .NotNull().WithMessage(InformeTelefone)
            .Must(x => x.Count() > 0).WithMessage(InformeTelefone)
            .ForEach(x => x.SetValidator(new TelefoneValidator()));

            When(c => c.Tipo == TipoPessoa.Fisica, () =>
            {
                RuleFor(c => c.CGC)
                .Must(c => ValidaCPF.IsCpf(c))
                .WithMessage("Informe um CPF válido");
            });

            When(c => c.Tipo == TipoPessoa.Juridica, () =>
            {
                RuleFor(c => c.CGC)
                .Must(c => ValidaCNPJ.IsCnpj(c))
                .WithMessage("Informe um CNPJ válido");
            });
        }
Beispiel #7
0
        protected override bool PreCondicional()
        {
            aEmpresa.cnpj = Utility.removerCaracteresEspeciais(aEmpresa.cnpj);
            aEmpresa.cep  = Utility.removerCaracteresEspeciais(aEmpresa.cep);

            if (aEmpresa.cnpj.Length == 11)
            {
                if (!ValidaCPF.IsCpf(aEmpresa.cnpj))
                {
                    addErro("CPF Inválido");
                    return(withoutError());
                }
            }

            if (aEmpresa.cnpj.Length == 14)
            {
                if (!ValidaCNPJ.IsCnpj(aEmpresa.cnpj))
                {
                    addErro("CNPJ Inválido");
                    return(withoutError());
                }
            }

            UserEmpresa associacao = aEmpresaUserRepository.Value.getUser(aUserId);

            if (associacao != null)
            {
                addErro("Já associado a uma empresa");
            }

            Empresa lEmpresaDup = aEmpresaRepository.Value.getCNPJ(aEmpresa.cnpj);

            if (lEmpresaDup != null)
            {
                addErro("Já existe uma empresa cadastrada com este documento");
            }

            User lUser = new UsersRepository().getId(aUserId);

            if (lUser != null && lUser.usermasterid.HasValue)
            {
                addErro("Usuário associado não pode criar empresa.");
            }

            return(withoutError());
        }
Beispiel #8
0
        public ForncecedorValidation()
        {
            RuleFor(f => f.Nome).NotEmpty().WithMessage("O campo {PropertyName} precisa ser fornecido")
            .Length(2, 100).WithMessage("O Campo {PropertyName} precisa ter entre {MinLength} e {MaxLength} caracteres");

            When(f => f.TipoFornecedor == TipoFornecedor.PessoFisica, () =>
            {
                RuleFor(f => f.Documento.Length).Equal(11)
                .WithMessage("O campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}.");
                RuleFor(f => ValidaCPF.IsCpf(f.Documento)).Equal(true)
                .WithMessage("O documento fornecido é inválido.");
            });

            When(f => f.TipoFornecedor == TipoFornecedor.PessoaJuridica, () =>
            {
                RuleFor(f => f.Documento.Length).Equal(14)
                .WithMessage("O campo Documento precisa ter {ComparisonValue} caracteres e foi fornecido {PropertyValue}.");
                RuleFor(f => ValidaCNPJ.IsCnpj(f.Documento)).Equal(true)
                .WithMessage("O documento fornecido é inválido.");
            });
        }
Beispiel #9
0
        public JsonResult cnpjReceita(string cnpj)
        {
            cnpj = Utility.removerCaracteresEspeciais(cnpj);

            if (ValidaCNPJ.IsCnpj(cnpj))
            {
                ConsultaReceita cs = new ConsultaReceita()
                {
                    cnpj = Regex.Replace(cnpj, @"\W+", "")
                };

                string link = "https://www.receitaws.com.br/v1/cnpj/" + cs.cnpj;

                WebRequest _request = WebRequest.Create(link);

                _request.Method = "GET";

                WebResponse response = _request.GetResponse();

                string responseText;

                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
                {
                    responseText = reader.ReadToEnd();
                }

                Empresa responseObject = JsonConvert.DeserializeObject <Empresa>(responseText);
                //return View("CadastrarCNPJ", responseObject);
                return(Json(responseObject));
            }
            else
            {
                aContextoExecucao.addErro("CNPJ Inválido para consulta");
                Response.StatusCode = 500; //Write your own error code
                Response.Write(JsonConvert.SerializeObject(aContextoExecucao.Messages));
                return(null);
            }
            //return Json(new Message("CNPJ Inválido para consulta", Message.kdType.Error));
        }
Beispiel #10
0
 public static Boolean cnpj(String cnpj)
 {
     return(ValidaCNPJ.IsCnpj(cnpj));
 }
Beispiel #11
0
        public EstabelecimentoModule() : base("/establishments")
        {
            Get["/"] = parameter =>
            {
                try
                {
                    mConn    = new MySqlConnection(stringConexao);
                    mAdapter = new MySqlDataAdapter("SELECT * FROM estabelecimento ORDER BY id", mConn);
                    DataSet myDataSet = new DataSet();
                    mAdapter.Fill(myDataSet, "estabelecimento");

                    foreach (DataRow item in myDataSet.Tables[0].Rows)
                    {
                        Estabelecimento estabelecimento = new Estabelecimento();
                        estabelecimento.id   = (Int64)item["id"];
                        estabelecimento.nome = item["nome"].ToString();
                        estabelecimento.cnpj = item["cnpj"].ToString();
                        estabelecimento.natureza_juridica = item["natureza_juridica"].ToString();
                        estabelecimento.situacao          = item["situacao"].ToString();
                        estabelecimentos.Add(estabelecimento);
                    }
                    mConn.Close();
                    return(Response.AsJson(estabelecimentos));
                }catch (InvalidCastException)
                {
                    return(HttpStatusCode.NoResponse);
                }
                catch (MySqlException)
                {
                    return(HttpStatusCode.NotAcceptable);
                }
            };

            Get["/{id}"] = parameter =>
            {
                try
                {
                    mConn    = new MySqlConnection(stringConexao);
                    mAdapter = new MySqlDataAdapter("SELECT * FROM estabelecimento WHERE id='" + parameter.id + "' ORDER BY id", mConn);
                    DataSet myDataSet = new DataSet();
                    mAdapter.Fill(myDataSet, "estabelecimento");

                    foreach (DataRow item in myDataSet.Tables[0].Rows)
                    {
                        Estabelecimento estabelecimento = new Estabelecimento();
                        estabelecimento.id   = (Int64)item["id"];
                        estabelecimento.nome = item["nome"].ToString();
                        estabelecimento.cnpj = item["cnpj"].ToString();
                        estabelecimento.natureza_juridica = item["natureza_juridica"].ToString();
                        estabelecimento.situacao          = item["situacao"].ToString();
                        estabelecimentos.Add(estabelecimento);
                    }
                    mConn.Close();
                    return(Response.AsJson(estabelecimentos));
                }catch (InvalidCastException)
                {
                    return(HttpStatusCode.NoResponse);
                }
                catch (MySqlException)
                {
                    return(HttpStatusCode.NotAcceptable);
                }
            };

            Post["/"] = parameters =>
            {
                try
                {
                    Estabelecimento estabelecimentotRequest = this.Bind();

                    if (estabelecimentotRequest == null)
                    {
                        return(HttpStatusCode.Unauthorized);
                    }

                    if (!ValidaCNPJ.IsCnpj(estabelecimentotRequest.cnpj.ToString()))
                    {
                        return(HttpStatusCode.UnsupportedMediaType);
                    }

                    //Console.WriteLine(Response.AsJson(jsonString));

                    mConn = new MySqlConnection(stringConexao);

                    mConn.Open();

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection  = mConn;
                    cmd.CommandText = "INSERT INTO estabelecimento(id, nome, cnpj, natureza_juridica, situacao)   VALUES(@param1,@param2,@param3,@param4,@param5)";

                    cmd.Parameters.AddWithValue("@param1", estabelecimentotRequest.id);
                    cmd.Parameters.AddWithValue("@param2", estabelecimentotRequest.nome);
                    cmd.Parameters.AddWithValue("@param3", estabelecimentotRequest.cnpj);
                    cmd.Parameters.AddWithValue("@param4", estabelecimentotRequest.natureza_juridica);
                    cmd.Parameters.AddWithValue("@param5", estabelecimentotRequest.situacao);

                    cmd.ExecuteNonQuery();

                    mConn.Close();
                    return(Response.AsJson(estabelecimentotRequest, HttpStatusCode.OK));
                }catch (InvalidCastException)
                {
                    return(HttpStatusCode.NoResponse);
                }
                catch (MySqlException)
                {
                    return(HttpStatusCode.NotAcceptable);
                }
            };

            Put["/{id}"] = parameter =>
            {
                return(HttpStatusCode.NoResponse);
            };

            Delete["/{id}"] = parameter =>
            {
                try
                {
                    if (parameter.id == null)
                    {
                        return(HttpStatusCode.Unauthorized);
                    }

                    mConn = new MySqlConnection(stringConexao);

                    mConn.Open();

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection  = mConn;
                    cmd.CommandText = "DELETE FROM estabelecimento WHERE id=@param1";

                    cmd.Parameters.AddWithValue("@param1", parameter.id);

                    cmd.ExecuteNonQuery();

                    mConn.Close();
                    return(Response.AsJson(HttpStatusCode.OK));
                }
                catch (InvalidCastException)
                {
                    return(HttpStatusCode.NoResponse);
                }
                catch (MySqlException)
                {
                    return(HttpStatusCode.NotAcceptable);
                }
            };
        }