コード例 #1
0
    public static int Insert(Cidades cidades)
    {
        int retorno = 0;

        try
        {
            IDbConnection objConnection;
            IDbCommand    objCommand;

            string sql = "insert into cid_cidade(cid_nome, est_id) values(?cid_nome, ?est_id); select last_insert_id();";
            objConnection = Mapped.Connection();
            objCommand    = Mapped.Command(sql, objConnection);

            objCommand.Parameters.Add(Mapped.Parameter("?cid_nome", cidades.Cid_nome));

            // FK
            objCommand.Parameters.Add(Mapped.Parameter("?est_id", cidades.Est_id.Est_id));

            retorno = Convert.ToInt32(objCommand.ExecuteScalar());
            objConnection.Close();
            objConnection.Dispose();
            objCommand.Dispose();
        }
        catch (Exception ex)
        {
            retorno = -2;
        }
        return(retorno);
    }
コード例 #2
0
        public void AlterarCidades(Cidades cidade)
        {
            var             stringConexao = System.Configuration.ConfigurationManager.ConnectionStrings["CidadeConexao"].ConnectionString;
            MySqlConnection conn          = new MySqlConnection(stringConexao);

            try
            {
                string sql  = "update cidades set codigo_ibge = @codigo_ibge, uf = @uf, nome = @nome, lng = @lng, lat = @lat, reg = @reg where id = @id";
                var    comm = new MySqlCommand(sql, conn);
                comm.Parameters.AddWithValue("@id", cidade.Id);
                comm.Parameters.AddWithValue("@reg", cidade.Regiao);
                comm.Parameters.AddWithValue("@nome", cidade.Nome);
                comm.Parameters.AddWithValue("@uf", cidade.UF);
                comm.Parameters.AddWithValue("@codigo_ibge", cidade.CodigoIbge);
                comm.Parameters.AddWithValue("@lat", cidade.Lat);
                comm.Parameters.AddWithValue("@lng", cidade.Lng);
                conn.Open();
                comm.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
コード例 #3
0
        protected void btnExcluirCidade_Click(object sender, EventArgs e)
        {
            if (txtNovaCidade.Text.Equals(""))
            {
                lblAlertaCidade.Visible = true;
                lblAlertaCidade.Text    = "O campo acima deve estar preenchido com o nome da cidade a ser excluida";
            }

            else
            {
                cidade = controle.pesquisaCidade(txtNovaCidade.Text);

                if (cidade == null)
                {
                    lblAlertaCidade.Visible = true;
                    lblAlertaCidade.Text    = "Para exclusão de cidade a mesma deve existir na base de dados";
                }

                else
                {
                    controle.excluirCidade(cidade);
                    btnVoltar_Click(sender, e);
                }
            }
        }
コード例 #4
0
        protected void btnSalvarCidade_Click(object sender, EventArgs e)
        {
            if (txtNovaCidade.Text.Equals(""))
            {
                lblAlertaCidade.Visible = true;
                lblAlertaCidade.Text    = "O campo acima deve estar preenchido com o nome da cidade a ser incluida";
            }

            else
            {
                cidade = controle.pesquisaCidade(txtNovaCidade.Text);

                if (cidade == null)
                {
                    cidade = new Cidades();
                    controle.salvarCidade(cidade);
                    cidade.cidade    = txtNovaCidade.Text;
                    cidade.id_Estado = ddlEstado.SelectedIndex;
                    controle.salvaAtualiza();
                    btnVoltar_Click(sender, e);
                }

                else
                {
                    lblAlertaCidade.Visible = true;
                    lblAlertaCidade.Text    = "Para inclusão de cidade a mesma não deve existir na base de dados";
                }
            }
        }
コード例 #5
0
        public async Task <IActionResult> Post(Cidades model)
        {
            try
            {
                var cidades = await _repo.GetCidadeID(model.idCidade);

                if (cidades == null)
                {
                    _repo.Add(model);
                    if (await _repo.SaveChangeAsync())
                    {
                        return(Ok("Cidade cadastrada com sucesso!"));
                    }
                }
                else
                {
                    return(BadRequest($"Erro: Essa cidade já está cadastrado!"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest($"Erro: {ex}"));
            }
            return(BadRequest("Erro: Não Salvou!!"));
        }
コード例 #6
0
        public async Task <ActionResult> Put(int id, Cidades model)
        {
            if (model.idCidade == 0)
            {
                model.idCidade = id;
            }
            try
            {
                var cidades = await _repo.GetCidadeID(id);

                if (cidades != null)
                {
                    _repo.Update(model);

                    if (await _repo.SaveChangeAsync())
                    {
                        return(Ok("Cidade atualizada com sucesso!"));
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest($"Erro: {ex}"));
            }
            return(BadRequest("Cidade não encontrada!"));
        }
コード例 #7
0
 //retornando rota, puxando dados do body
 public IActionResult Cadastrar([FromBody] Cidades cidade)
 {
     //chamando metodo
     cidades.Cadastrar(cidade);
     //criando rota de retorno, nome da rota, parametro, formato dos dados
     return(CreatedAtRoute("cidadeAtual", new { id = cidade.Id }, cidade));
 }
コード例 #8
0
        public Logradouros BuscarEndereco(int cep)
        {
            // http://viacep.com.br/ws/04140000/json
            WebApiClient client = new WebApiClient("http://viacep.com.br");
            string       s      = String.Format("ws/{0:00000000}/json", cep);
            ViaCep       viacep = client.GetJson <ViaCep>(s);

            if (viacep != null && viacep.Localidade != null)
            {
                Cidades cidade = new Cidades
                {
                    DescCidade = RemoveDiacritics(viacep.Localidade).ToUpper(),
                    FlgEstado  = viacep.Uf
                };
                Bairros bairro = new Bairros
                {
                    DescBairro = RemoveDiacritics(viacep.Bairro).ToUpper(),
                    Cidades    = cidade
                };
                int         primeiroEspaco = viacep.Logradouro.IndexOf(' ');
                Logradouros logradouro     = new Logradouros
                {
                    DescLogradouro = RemoveDiacritics(viacep.Logradouro.Substring(primeiroEspaco + 1)).ToUpper(),
                    Bairros        = bairro,
                    NumCep         = cep,
                    DescTipo       = RemoveDiacritics(viacep.Logradouro.Substring(0, primeiroEspaco)).ToUpper()
                };
                return(logradouro);
            }
            return(null);
        }
コード例 #9
0
        // GET: Admin/Cidades/Delete/5
        //public ActionResult Delete(int? id)
        //{
        //    if (id == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    Cidades cidades = db.Cidades.Find(id);
        //    if (cidades == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(cidades);
        //}

        // POST: Admin/Cidades/Delete/5
        //[HttpPost, ActionName("Delete")]
        //[ValidateAntiForgeryToken]
        public JsonResult DeleteConfirmed(int id)
        {
            var response = new
            {
                success  = true,
                messages = "Registro excluido!"
            };

            try
            {
                Cidades cidades = db.Cidades.Find(id);
                db.Cidades.Remove(cidades);
                db.SaveChanges();
            }
            catch
            {
                response = new
                {
                    success  = false,
                    messages = "Algo de ERRADO aconteceu, procure o Administrador!"
                };
            }

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
コード例 #10
0
        private void carregarInfCliente()
        {
            #region Carregar dados do cliente nos itens do groupBox
            try
            {
                Clientes c = clientesDAO.select(Convert.ToInt16(dataGridView.CurrentRow.Cells["ID"].Value.ToString()));
                textNome.Text = c.Nome;
                textNome.Focus();
                textEmail.Text = c.Email;

                if (c.Cpf == null)
                {
                    checkEmpresa.Checked = true;
                    maskedDocumento.Text = c.Cnpj;
                }
                else
                {
                    checkEmpresa.Checked = false;
                    maskedDocumento.Text = c.Cpf;
                }

                Cidades cid = cidadesDAO.selectCidade(c.Cidade.Id);
                comboUF.SelectedValue = cid.Estado.Id;

                comboCidade.SelectedValue = c.Cidade.Id;
                textEndereco.Text         = c.Endereco;
                textTel.Text  = c.Telefone;
                textTel2.Text = c.Telefone2;
            }
            catch
            {
            }
            #endregion
        }
コード例 #11
0
        private void FrmAltAlunos_Load(object sender, EventArgs e)
        {
            #region Carregar os Estados
            try
            {
                Estados estados = new Estados();
                comboEstado.DataSource    = estados.selectArray("order by sigla");
                comboEstado.DisplayMember = "sigla";
                comboEstado.ValueMember   = "id_estado";
            }
            catch
            {
            }
            #endregion

            #region Carregar as Cidades
            try
            {
                Cidades   cidades = new Cidades();
                ArrayList array   = cidades.selectArray("where idEstado = " + Convert.ToInt16(comboEstado.SelectedIndex + 1) + " order by nome");
                comboCidade.DataSource    = array;
                comboCidade.DisplayMember = "nome";
                //comboCidade.ValueMember = "idEstado";
                comboCidade.ValueMember = "id";
            }
            catch
            {
            }
            #endregion

            comboEstado.SelectedIndex = idEstado;
            comboCidade.SelectedValue = idCidade;
        }
コード例 #12
0
 //não precisaria ser IActionResult, poderia ser void
 //IActionResult vamos cadastrar e fazer um requisição Get, para ver o que foi cadastrado
 //FromBody é o tipo de dado que vc envia, só nao será enviado o id pois é automatico
 public IActionResult Post([FromBody] Cidades cidades)
 {
     dao.Cadastro(cidades);
     //__criando ponto de ancoragem, após ele cadastrar os dados
     //este item é válido somente se quiser saber oq foi cadastrado
     return(CreatedAtRoute("CidadeAtual", new { id = cidades.Id }, cidades));
 }
コード例 #13
0
        private void carregarInfFornecedor()
        {
            #region Carregar dados do fornecedor nos itens do groupBox
            try
            {
                Fornecedores f = fornecedoresDAO.select(Convert.ToInt16(dataGridView.CurrentRow.Cells["ID"].Value.ToString()));
                textNome.Text = f.Nome;
                textNome.Focus();
                textEmail.Text = f.Email;

                if (f.Cnpj.Length < 18)
                {
                    textDocumento.Text = "";
                }
                else
                {
                    textDocumento.Text = f.Cnpj;
                }

                Cidades cid = cidadesDAO.selectCidade(f.Cidade.Id);
                textUF.Text = cid.Estado.Nome;

                textCidade.Text   = f.Cidade.Nome;
                textEndereco.Text = f.Endereco;
                textTel.Text      = f.Telefone;
                textTel2.Text     = f.Telefone2;
            }
            catch
            {
            }
            #endregion
        }
コード例 #14
0
        public ActionResult Create([Bind(Include = "CidadesId,Nome,EstadosId")] Cidades cidades)
        {
            if (ModelState.IsValid)
            {
                db.Cidades.Add(cidades);
                try
                {
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                catch (System.Exception ex)
                {
                    if (ex.InnerException != null &&
                        ex.InnerException.InnerException != null &&
                        ex.InnerException.InnerException.Message.Contains("_Index"))
                    {
                        ModelState.AddModelError(string.Empty, "Não é possível inserir duas cidades com o mesmo nome!");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.Message);
                    }

                    ViewBag.EstadosId = new SelectList(db.Estados, "EstadosId", "Nome", cidades.EstadosId);
                    return(View(cidades));
                }
            }

            return(View(cidades));
        }
コード例 #15
0
        private void carregarInfTrabalhador()
        {
            #region Carregar dados do trabalhador nos itens do groupBox
            try
            {
                Trabalhadores t = trabalhadoresDAO.select(Convert.ToInt16(dataGridView.CurrentRow.Cells["ID"].Value.ToString()));
                textNome.Text = t.Nome;
                textNome.Focus();
                textEmail.Text       = t.Email;
                maskedDocumento.Text = t.Cpf;

                Cidades cid = cidadesDAO.selectCidade(t.Cidade.Id);
                comboUF.SelectedValue = cid.Estado.Id;

                comboServico.Text         = t.Servico;
                comboCidade.SelectedValue = t.Cidade.Id;
                textEndereco.Text         = t.Endereco;
                textTel.Text  = t.Telefone;
                textTel2.Text = t.Telefone2;
            }
            catch
            {
            }
            #endregion
        }
コード例 #16
0
        private void txtIdCidade_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtIdCidade.Text))
            {
                return;
            }
            if (Convert.ToInt32("0" + txtIdCidade.Text) < 1)
            {
                return;
            }
            Cidades cid = CtrlCidade.BuscarPorID(Convert.ToInt32(txtIdCidade.Text)) as Cidades;

            if (cid == null)
            {
                MessageBox.Show("Nenhum resultado");
                txtCidade.Text      = "";
                txtIdCidade.Text    = "";
                txtUF.Text          = "";
                txtCidade.Enabled   = true;
                txtUF.Enabled       = true;
                txtIdCidade.Enabled = true;
                txtIdCidade.Focus();
            }
            else
            {
                txtCidade.Text    = cid.cidade;
                txtUF.Text        = cid.Estado.uf;
                txtUF.Enabled     = false;
                txtCidade.Enabled = false;
                txtIdCidade.Focus();
            }
        }
コード例 #17
0
        public override object BuscarPorID(object id)
        {
            // Instanciando a conexão
            using (SqlConnection conexao = Conecta.CreateConnection())
            {
                SqlDataAdapter da;
                string         sql = @"select * from cidades where codigo = @codigo";

                SqlCommand comando = new SqlCommand(sql, conexao);

                comando.Parameters.AddWithValue("@codigo", id);

                conexao.Open();
                da = new SqlDataAdapter(comando);

                DataTable dtCidade = new DataTable();
                da.Fill(dtCidade);
                EstadosDAO daoEstado = new EstadosDAO();
                cidade = null;
                foreach (DataRow row in dtCidade.Rows)
                {
                    Cidades cid = new Cidades();
                    cid.codigo      = Convert.ToInt32(row["codigo"]);
                    cid.cidade      = Convert.ToString(row["cidade"]);
                    cid.Estado      = daoEstado.BuscarPorID(Convert.ToInt32(row["codEstado"])) as Estados;
                    cid.dtCadastro  = Convert.ToDateTime(row["dtCadastro"]);
                    cid.dtAlteracao = Convert.ToDateTime(row["dtAlteracao"]);
                    cid.usuario     = Convert.ToString(row["usuario"]);

                    this.cidade = cid;
                }
                conexao.Close();
                return(cidade);
            }
        }
コード例 #18
0
        public JsonResult Cidades(int?id)
        {
            id = id == null ? 1 : id;
            Cidades ListaDeCidades = new Cidades();

            return(Json(ListaDeCidades.ListarCidades(false).Where(cidade => cidade.IDEstado == id), JsonRequestBehavior.AllowGet));
        }
コード例 #19
0
 private void Excluir(object objParam)
 {
     if (objParam != null)
     {
         if (MessageBox.Show("Tem Certeza que deseja excluir o registro selecionado?", "Atenção", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
         {
             Retorno objRetorno;
             using (var objBLL = new Cidades())
             {
                 objRetorno = objBLL.ExcluirCidade((int)objParam);
             }
             if (objRetorno.intCodigoErro == 0)
             {
                 objCidade = null;
                 ClearAllErrorsAsync();
                 base.enStatusTelaAtual = enStatusTela.Navegacao;
                 Pesquisar(null);
             }
             else
             {
                 MessageBox.Show(objRetorno.strMsgErro, "Atenção", MessageBoxButton.OK, Util.GetMessageImage(objRetorno.intCodigoErro));
             }
         }
     }
 }
コード例 #20
0
        public async Task <IActionResult> PostCidades([FromBody] Cidades cidades)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Cidades.Add(cidades);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (CidadesExists(cidades.CidadeId))
                {
                    return(new StatusCodeResult(StatusCodes.Status409Conflict));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetCidades", new { id = cidades.CidadeId }, cidades));
        }
コード例 #21
0
        private void Salvar(object objParam)
        {
            var focusedElement = Keyboard.FocusedElement as FrameworkElement;

            if (focusedElement is TextBox)
            {
                var expression = focusedElement.GetBindingExpression(TextBox.TextProperty);
                if (expression != null && expression.ParentBinding.UpdateSourceTrigger == System.Windows.Data.UpdateSourceTrigger.LostFocus)
                {
                    expression.UpdateSource();
                }
            }

            Validate();
            if (!HasErrors)
            {
                Retorno objRetorno;
                using (var objBLL = new Cidades())
                {
                    objRetorno = objBLL.SalvarCidade(objCidade, FrameworkUtil.objConfigStorage.objFuncionario.fun_codigo);
                }
                if (objRetorno.intCodigoErro == 0)
                {
                    objCidade = null;
                    ClearAllErrorsAsync();
                    base.enStatusTelaAtual = enStatusTela.Navegacao;
                    Pesquisar(null);
                }
                else
                {
                    MessageBox.Show(objRetorno.strMsgErro, "Atenção", MessageBoxButton.OK, Util.GetMessageImage(objRetorno.intCodigoErro));
                }
            }
        }
コード例 #22
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Descricao")] Cidades cidades)
        {
            if (id != cidades.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(cidades);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CidadesExists(cidades.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(cidades));
        }
コード例 #23
0
        public async Task <IActionResult> PutCidades([FromRoute] int id, [FromBody] Cidades cidades)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != cidades.CidadeId)
            {
                return(BadRequest());
            }

            _context.Entry(cidades).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CidadesExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #24
0
        private void carregarInfCliente()
        {
            #region Carregar dados do cliente nos itens do groupBox
            try
            {
                Clientes c = clientesDAO.select(Convert.ToInt16(dataGridView.CurrentRow.Cells["ID"].Value.ToString()));
                textNome.Text = c.Nome;
                textNome.Focus();
                textEmail.Text = c.Email;

                if (c.Cpf == null)
                {
                    textDocumento.Text = c.Cnpj;
                    label2.Text        = "CNPJ";
                }
                else
                {
                    textDocumento.Text = c.Cpf;
                    label2.Text        = "CPF";
                }

                Cidades cid = cidadesDAO.selectCidade(c.Cidade.Id);
                textUF.Text = cid.Estado.Nome;

                textCidade.Text   = c.Cidade.Nome;
                textEndereco.Text = c.Endereco;
                textTel.Text      = c.Telefone;
                textTel2.Text     = c.Telefone2;
            }
            catch
            {
            }
            #endregion
        }
コード例 #25
0
        private void carregarInfTrabalhador()
        {
            #region Carregar dados do trabalhador nos itens do groupBox
            try
            {
                Trabalhadores t = trabalhadoresDAO.select(Convert.ToInt16(dataGridView.CurrentRow.Cells["ID"].Value.ToString()));

                textNome.Text = t.Nome;
                textNome.Focus();
                textEmail.Text = t.Email;

                if (t.Cpf.Length < 14)
                {
                    textDocumento.Text = "";
                }
                else
                {
                    textDocumento.Text = t.Cpf;
                }

                Cidades cid = cidadesDAO.selectCidade(t.Cidade.Id);
                textUF.Text = cid.Estado.Nome;

                textServico.Text  = t.Servico;
                textCidade.Text   = t.Cidade.Nome;
                textEndereco.Text = t.Endereco;
                textTel.Text      = t.Telefone;
                textTel2.Text     = t.Telefone2;
            }
            catch
            {
            }
            #endregion
        }
コード例 #26
0
        public async Task <bool> SalvarCidade(string webApi, Cidades cidade)
        {
            try
            {
                string validacao = ValidarSalvar(cidade);
                if (string.IsNullOrEmpty(validacao))
                {
                    if (cidade.idCidade > 0)
                    {
                        resultado = await PutCidadeAsync(webApi, cidade);

                        return(resultado);
                    }
                    else
                    {
                        resultado = await PostCidadeAsync(webApi, cidade);

                        return(resultado);
                    }
                }
                else
                {
                    resultado = false;
                    throw new ArgumentException(validacao);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #27
0
        private void txtCep_TextChanged(object sender, EventArgs e)
        {
            string cep = ((MaskedTextBox)sender).Text.Replace("-", "").Trim();

            if (cep.Length != 8)
            {
                return;
            }

            var endereco = new Endereco();

            if (!endereco.SearchByCep(cep, null))
            {
                cmbEstado.Focus();
                return;
            }

            if (!string.IsNullOrEmpty(endereco.Uf))
            {
                try
                {
                    cmbEstado.SelectedIndexChanged -= cmbEstado_SelectedIndexChanged;
                    cmbEstado.SelectedIndex         = Estados.FindIndex(estado => estado.Uf == endereco.Uf) + 1;
                    CarregarCidades(endereco.Uf);
                    if (endereco.IdCidade != 0)
                    {
                        cmbCidade.SelectedIndex = Cidades.FindIndex(cidade => cidade.Id == endereco.IdCidade) + 1;
                    }
                }
                finally
                {
                    cmbEstado.SelectedIndexChanged += cmbEstado_SelectedIndexChanged;
                }
            }

            if (!string.IsNullOrEmpty(endereco.TipoLogradouro))
            {
                cmbTipoLogradouro.Text = endereco.TipoLogradouro;
                txtLogradouro.Focus();
            }

            if (!string.IsNullOrEmpty(endereco.Logradouro))
            {
                txtLogradouro.Text = endereco.Logradouro;
                txtComplemento.Focus();
            }

            if (!string.IsNullOrEmpty(endereco.Complemento))
            {
                txtComplemento.Text = endereco.Complemento;
                txtBairro.Focus();
            }

            if (!string.IsNullOrEmpty(endereco.Bairro))
            {
                txtBairro.Text = endereco.Bairro;
                txtNumero.Focus();
            }
        }
コード例 #28
0
        public ActionResult DeleteConfirmed(int id)
        {
            Cidades cidades = db.Cidades.Find(id);

            db.Cidades.Remove(cidades);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
コード例 #29
0
        public void Deletar(int id)
        {
            Cidades x = ctx.Cidades.Find(id);

            ctx.Cidades.Remove(x);

            ctx.SaveChanges();
        }
コード例 #30
0
        public ActionResult Detalhar(long id)
        {
            Cidades cidade = db.Cidades.Find(id);

            ViewBag.IDCidade = new SelectList(db.Cidades, "IDCidade", "Nome");

            return(View(cidade));
        }