Beispiel #1
0
        public void Gravar()
        {
            string titulo = @"PLACA;MODELO;COR;ANO;MARCA;COMBUSTÍVEL;CÂMBIO;OBSERVAÇÃO;USUÁRIO;DATA;HORÁRIO";

            string registro = string.Format(
                "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
                Placa, Modelo, Cor, Ano.ToString(), Marca, Combustivel.ToString(),
                Cambio.ToString(), Observacao.Replace(";", ""),
                Environment.UserName,
                DateTime.Now.ToString("dd/MM/yyyy;HH:mm:ss"));

            bool flag = File.Exists(caminho);

            StreamWriter escritor = new StreamWriter(caminho, true);

            if (!flag)
            {
                escritor.WriteLine(titulo);
            }

            escritor.WriteLine(registro);

            escritor.Close();
            // throw new NotImplementedException();
        }
        public CombustivelColecao ConsultarPorId(int IDCADCOMBUSTIVEL)
        {
            try
            {
                CombustivelColecao combustivelColecao = new CombustivelColecao();

                acessoDadosSqlServer.LimparParametros();
                acessoDadosSqlServer.AdicionarParametros("@IDCADCOMBUSTIVEL", IDCADCOMBUSTIVEL);

                DataTable dataTableCombustivel = acessoDadosSqlServer.ExecutarConsulta(CommandType.StoredProcedure, "uspCADCOMBUSTIVELConsultarPorID");
                foreach (DataRow dataRowLinha in dataTableCombustivel.Rows)
                {
                    Combustivel combustivel = new Combustivel();

                    combustivel.IDCADCOMBUSTIVEL = Convert.ToInt32(dataRowLinha["IDCADCOMBUSTIVEL"]);
                    combustivel.CADCOMBUSTIVEL   = Convert.ToString(dataRowLinha["CADCOMBUSTIVEL"]);

                    combustivelColecao.Add(combustivel);
                }

                return(combustivelColecao);
            }
            catch (Exception exception)
            {
                throw new Exception("Não foi possível consultar o combustível por código. Detalhes: " + exception.Message);
            }
        }
Beispiel #3
0
        public void Gravar()
        {
            //Definir a linha de título do arquivo
            string titulo = @"PLACA;MODELO;COR;ANO;MARCA;COMBUSTÍVEL;CÂMBIO;OBSERVAÇÃO;USUÁRIO;DATA;HORÁRIO";

            //Definir o registro que será gravado
            string registro = string.Format(
                "{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
                Placa, Modelo, Cor, Ano.ToString(),
                Marca, Combustivel.ToString(),
                Cambio.ToString(), Observacao.Replace(";", ""),
                Environment.UserName,
                DateTime.Now.ToString("dd/MM/yyyy;HH:mm:ss")
                );

            //Verificar se o arquivo já existe
            bool flag = File.Exists(caminho);

            //Definir o objeto StreamWriter
            StreamWriter escritor = new StreamWriter(caminho, true);

            //Se o arquivo não existir, criar o arquivo e
            //escrever o título na primeira linha
            if (!flag)
            {
                escritor.WriteLine(titulo);
            }

            //Escrever o registro no arquivo
            escritor.WriteLine(registro);

            //Fechar a comunicação com o arquivo
            escritor.Close();
        }
        public List <AutonomiaInfo> GetAutonomia(DateTime dataMes, Veiculo veiculo)
        {
            //retrocede 3 meses
            DateTime dataMesInicial = dataMes.AddMonths(-3);

            List <AutonomiaInfo> list = new List <AutonomiaInfo>();


            // Loop para buscar abastecimento de 3 meses anteriores
            for (int i = 0; i < 3; i++)
            {
                using (var context = new Context())
                {
                    Combustivel combustivelVeiculo = context.Combustiveis.Where(w => w.Id.Equals(veiculo.Combustivel)).FirstOrDefault();

                    //busca o abastecimento do veiculo conforme range de data
                    List <DGridAbastecimentoInfo> abastecimento = context.Abastecimentos.Where(w => (w.Data.Month.Equals(dataMesInicial.Month) && w.Data.Year.Equals(dataMesInicial.Year) && w.Veiculo.Placa.Equals(veiculo.Placa))).
                                                                  Select(s => new DGridAbastecimentoInfo
                    {
                        Data        = s.Data,
                        Combustivel = context.Combustiveis.Where(w2 => w2.Id.Equals(s.CombustivelId)).Select(s2 => s2.Tipo).FirstOrDefault(),
                        KM          = s.KM,
                        Quantidade  = s.Quantidade,
                        Valor       = s.Valor
                    }).OrderBy(or => or.Data).ToList();

                    list.Add(CalculoAutonomiaDoMes(dataMesInicial, abastecimento, combustivelVeiculo.Tipo));

                    dataMesInicial = dataMesInicial.AddMonths(1);
                }
            }

            return(list);
        }
        public List <Combustivel> Listar()
        {
            try
            {
                AbrirConexao();

                var strQuery = "SELECT * FROM Combustivel";
                Cmd = new MySqlCommand(strQuery, minhaConexao);
                Dr  = Cmd.ExecuteReader();


                List <Combustivel> lista = new List <Combustivel>();
                while (Dr.Read())
                {
                    Combustivel c = new Combustivel();
                    c.IdCombustivel = Convert.ToInt32(Dr["IdCombustivel"]);
                    c.Nome          = Convert.ToString(Dr["Nome"]).ToUpper();

                    lista.Add(c);
                }
                Dr.Close();
                Dr.Dispose();
                return(lista);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                FecharConexao();
            }
        }
Beispiel #6
0
        public List <Combustivel> listar()
        {
            List <Combustivel> lista = new List <Combustivel>();
            Combustivel        combustivel;

            combustivel           = new Combustivel();
            combustivel.ID        = 1;
            combustivel.descricao = "Gasolina";
            lista.Add(combustivel);

            combustivel           = new Combustivel();
            combustivel.ID        = 2;
            combustivel.descricao = "Álcool";
            lista.Add(combustivel);

            combustivel           = new Combustivel();
            combustivel.ID        = 3;
            combustivel.descricao = "Diesel";
            lista.Add(combustivel);

            combustivel           = new Combustivel();
            combustivel.ID        = 4;
            combustivel.descricao = "GN";
            lista.Add(combustivel);
            return(lista);
        }
Beispiel #7
0
 private void btnCalcular_Click(object sender, EventArgs e)
 {
     try
     {
         Controle    controle    = new Controle();
         Combustivel combustivel = new Combustivel(1, 1);
         combustivel.CustoEtanol   = Convert.ToDouble(txbPrecoAlcool.Text);
         combustivel.KmEtanol      = Convert.ToDouble(txbKmPorLitroAlcool.Text);
         combustivel.CustoGasolina = Convert.ToDouble(txbPrecoGasolina.Text);
         combustivel.KmGasolina    = Convert.ToDouble(txbKmPorLitroGasolina.Text);
         combustivel.Km_dia        = Convert.ToInt32(txbDias.Text);
         combustivel.Rodagem       = Convert.ToDouble(txbKmTotal.Text);
         lblResultado.Text         = $" {combustivel}                    R$ {Convert.ToString(controle.CalcularEtanol(combustivel).ToString("F2", CultureInfo.InvariantCulture))}                      R$   {Convert.ToString(controle.CalcularGasolina(combustivel).ToString("F2", CultureInfo.InvariantCulture))}";
     }
     catch (FormatException error)
     {
         MessageBox.Show("Erro de formatação: " + error.Message);
     }
     catch (OverflowException error)
     {
         MessageBox.Show("Erro: " + error.Message);
     }
     catch (Exception error)
     {
         MessageBox.Show("Erro inesperado: " + error.Message);
     }
     if (lblResultado.Text == "")
     {
         MessageBox.Show("Erro, tente novamente");
     }
 }
Beispiel #8
0
        public List <Combustivel> Listar()
        {
            try
            {
                using (Conexao contexto = new Conexao())
                {
                    var strQuery = "SELECT * FROM Combustivel";
                    contexto.Dr = contexto.ExecutaComandoComRetorno(strQuery);
                    List <Combustivel> lista = new List <Combustivel>();
                    while (contexto.Dr.Read())
                    {
                        Combustivel c = new Combustivel();
                        c.IdCombustivel = Convert.ToInt32(contexto.Dr["IdCombustivel"]);
                        c.Nome          = Convert.ToString(contexto.Dr["Nome"]).ToUpper();

                        lista.Add(c);
                    }

                    return(lista);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        //Construtor
        public FrmCombustivelCadastrar(AcaoNaTela acaoNaTela, Combustivel combustivel)
        {
            InitializeComponent();
            this.acaoNaTelaSelecionada = acaoNaTela;

            if (acaoNaTela == AcaoNaTela.Inserir)
            {
                this.Text = "Inserir Combustível";
            }
            else if (acaoNaTela == AcaoNaTela.Alterar)
            {
                this.Text = "Alterar Combustível";

                textBoxCodigo.Text      = combustivel.IDCADCOMBUSTIVEL.ToString();
                textBoxCombustivel.Text = combustivel.CADCOMBUSTIVEL;
            }
            else if (acaoNaTela == AcaoNaTela.Consultar)
            {
                this.Text = "Consultar Combustível";

                //Carregar campos da tela
                textBoxCodigo.Text      = combustivel.IDCADCOMBUSTIVEL.ToString();
                textBoxCombustivel.Text = combustivel.CADCOMBUSTIVEL;

                //Desabilitar campos da tela
                textBoxCombustivel.ReadOnly = true;
                textBoxCombustivel.TabStop  = false;

                buttonSalvar.Visible = false;
                buttonCancelar.Text  = "&Fechar";

                buttonCancelar.Focus();
            }
        }
Beispiel #10
0
 // Métodos;
 public Abastecimento()
 {
     _veiculo     = new Veiculo();
     _fornecedor  = new Fornecedor();
     _funcionario = new Funcionario();
     _combustivel = new Combustivel();
 }
Beispiel #11
0
        public void Button_Clicked(object sender, EventArgs e)
        {
            string      nome = Convert.ToString(C.Distribuidor);
            Button      btn  = (Button)sender;
            Combustivel comb = (Combustivel)btn.CommandParameter;

            DisplayAlert("Aviso", "Visitar o site " + nome, "cacelar", "reservar");
        }
Beispiel #12
0
 public Carro(int ano, String marca, String modelo, String placa, int cc, Combustivel combustivel)
 {
     Motor = new Motor() { CC=cc, Combustivel = combustivel };
     Ano = ano;
     Marca = marca;
     Modelo = modelo;
     Placa = placa;
 }
Beispiel #13
0
        public ActionResult DeleteConfirmed(int id)
        {
            Combustivel combustivel = db.Combustiveis.Find(id);

            db.Combustiveis.Remove(combustivel);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        private void buttonSalvar_Click(object sender, EventArgs e)
        {
            //Verificar se é inserção ou alteração
            if (acaoNaTelaSelecionada == AcaoNaTela.Inserir)
            {
                Combustivel combustivel = new Combustivel();

                combustivel.CADCOMBUSTIVEL = textBoxCombustivel.Text;

                CombustivelNegocios combustivelNegocios = new CombustivelNegocios();

                string retorno = combustivelNegocios.Inserir(combustivel);

                //Tentar converter para inteiro
                //Se der tudo certo é porque devolveu o código do cliente
                //Se der errado tem a mensagem de erro
                try
                {
                    int idCombustivel = Convert.ToInt32(retorno);
                    MessageBox.Show("Combustível inserido com sucesso." + idCombustivel.ToString());
                    this.DialogResult = DialogResult.Yes;
                }
                catch
                {
                    MessageBox.Show("Não foi possível inserir. Detalhes: " + retorno, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.DialogResult = DialogResult.No;
                }
            }
            else if (acaoNaTelaSelecionada == AcaoNaTela.Alterar)
            {
                // Crio um cliente
                Combustivel combustivel = new Combustivel();

                //Coloco os campos da tela no objeto clliente, e envio para alterar no banco

                combustivel.IDCADCOMBUSTIVEL = Convert.ToInt32(textBoxCodigo.Text);
                combustivel.CADCOMBUSTIVEL   = textBoxCombustivel.Text;

                CombustivelNegocios combustivelNegocios = new CombustivelNegocios();

                string retorno = combustivelNegocios.Alterar(combustivel);

                //Tentar converter para inteiro
                //Se der tudo certo é porque devolveu o código do cliente
                //Se der errado tem a mensagem de erro
                try
                {
                    int idCombustivel = Convert.ToInt32(retorno);
                    MessageBox.Show("Combustível alterado com sucesso." + idCombustivel.ToString());
                    this.DialogResult = DialogResult.Yes;
                }
                catch
                {
                    MessageBox.Show("Não foi possível alterar. Detalhes: " + retorno, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.DialogResult = DialogResult.No;
                }
            }
        }
        public async Task <CombustivelViewModel> Add(Combustivel combustivel)
        {
            var db = new TrackRoadContext();

            db.Combustiveis.Add(combustivel);
            db.SaveChanges();

            return(new CombustivelViewModel(combustivel));
        }
        public CombustivelViewModel(Combustivel combustivel)
        {
            if (combustivel.Id != 0)
            {
                this.Id = combustivel.Id;
            }

            this.Nome  = combustivel.Nome;
            this.Preco = combustivel.Preco;
        }
Beispiel #17
0
 public Veiculo(int id, string marca, string modelo, Cor cor, DateTime anoDeFabricacao, Combustivel combustivel, double valor)
 {
     Id              = id;
     Marca           = marca;
     Modelo          = modelo;
     Cor             = cor;
     AnoDeFabricacao = anoDeFabricacao;
     Combustivel     = combustivel;
     Valor           = valor;
 }
Beispiel #18
0
 public ActionResult Edit([Bind(Include = "CombustivelID,combustivel")] Combustivel combustivel)
 {
     if (ModelState.IsValid)
     {
         db.Entry(combustivel).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(combustivel));
 }
Beispiel #19
0
        public ActionResult Editar(int id)
        {
            Combustivel combustivel = _dao.Get(id);

            if (combustivel == null)
            {
                return(RedirectToAction("Index", "Combustivel"));
            }

            return(View(combustivel));
        }
        private async void AtualizarCombustivel()
        {
            var combustivel = new Combustivel
            {
                Id    = this.combustivel.Id,
                Nome  = tbxNome.Text,
                Preco = double.Parse(tbxPreco.Text)
            };

            await _combustivelApp.Update(combustivel);
        }
Beispiel #21
0
        private async void AdicionarCombustivel()
        {
            var combustivel = new Combustivel
            {
                Id    = 0,
                Nome  = tbxNome.Text,
                Preco = double.Parse(tbxPreco.Text)
            };

            await _combustivelApp.Add(combustivel);
        }
Beispiel #22
0
        public ActionResult Create([Bind(Include = "CombustivelID,combustivel")] Combustivel combustivel)
        {
            if (ModelState.IsValid)
            {
                db.Combustiveis.Add(combustivel);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(combustivel));
        }
        public async Task Update(Combustivel combustivel)
        {
            var context  = new TrackRoadContext();
            var response = context.Combustiveis.First(u => u.Id == combustivel.Id);

            response.Id    = combustivel.Id;
            response.Nome  = combustivel.Nome;
            response.Preco = combustivel.Preco;

            context.SaveChanges();
        }
Beispiel #24
0
        public bool Combustivel(Combustivel Combustivel, int TipoPesquisa)
        {
            try
            {
                DataTable        table   = new DataTable();
                MySqlDataAdapter adapter = new MySqlDataAdapter();
                MySqlCommand     command = new MySqlCommand();
                table = Consulta.Combustivel(Combustivel, TipoPesquisa);

                //Verifica se o Combustivel Ja esta cadastrado.
                if (table.Rows.Count != 0)
                {
                    if (!Conexão.Checkconection())
                    {
                        Conexão.Conectar();
                    }

                    if (Conexão.Checkconection())
                    {
                        string AlterCombustivel = "UPDATE COMBUSTIVEL SET NOME = @NOME, VALOR = @VALOR, DATAS = @DATAS WHERE ID_COMBUSTIVEL = @ID_COMBUSTIVEL;";


                        command.CommandText = AlterCombustivel;
                        command.Connection  = Conexão.Pega_Conexão();
                        command.Parameters.Add("@NOME", MySqlDbType.VarChar).Value         = Combustivel.Nome;
                        command.Parameters.Add("@VALOR", MySqlDbType.Float).Value          = Combustivel.Valor;
                        command.Parameters.Add("@DATAS", MySqlDbType.Date).Value           = Combustivel.Data;
                        command.Parameters.Add("@ID_COMBUSTIVEL", MySqlDbType.Int32).Value = table.Rows[0][0];

                        int retorno = command.ExecuteNonQuery();
                        if (retorno > 0)
                        {
                            Combustivel_Alterado = true;
                        }
                        Conexão.Desconectar();
                    }
                    else
                    {
                        return(Combustivel_Alterado);
                    }
                }
                else
                {
                    MessageBox.Show("Combustivel não pode ser Alterado", "Problemas ao Alterar");
                }
            }
            catch (MySqlException Exception)
            {
                MessageBox.Show(Convert.ToString(Exception), "Estado da Conexão");
            }

            return(Combustivel_Alterado);
        }
Beispiel #25
0
        private static String ObterCombustivel(Combustivel c)
        {
            String retorno = "";

            foreach (Combustivel item in System.Enum.GetValues(typeof(Combustivel)))
            {
                if ((c & item) == item)
                    retorno += item + ", ";
            }

            return retorno.Substring(0, retorno.Length-2);
        }
Beispiel #26
0
        public bool Combustivel(Combustivel Combustivel, int TipoPesquisa)
        {
            try
            {
                DataTable        table   = new DataTable();
                MySqlDataAdapter adapter = new MySqlDataAdapter();
                MySqlCommand     command = new MySqlCommand();
                table = Consulta.Combustivel(Combustivel, TipoPesquisa);

                //Verifica se o Combustivel Ja esta cadastrado.
                if (table.Rows.Count == 0)
                {
                    if (!Conexão.Checkconection())
                    {
                        Conexão.Conectar();
                    }

                    if (Conexão.Checkconection())
                    {
                        string InsertCombustivel = "INSERT INTO COMBUSTIVEL(NOME, VALOR, DATAS) VALUES (@NOME, @VALOR, @DATAS);";


                        command.CommandText = InsertCombustivel;
                        command.Connection  = Conexão.Pega_Conexão();
                        command.Parameters.Add("@NOME", MySqlDbType.VarChar).Value = Combustivel.Nome;
                        command.Parameters.Add("@VALOR", MySqlDbType.Float).Value  = Combustivel.Valor;
                        command.Parameters.Add("@DATAS", MySqlDbType.Date).Value   = Combustivel.Data;

                        int retorno = command.ExecuteNonQuery();
                        if (retorno > 0)
                        {
                            Combustivel_Incluido = true;
                        }
                        Conexão.Desconectar();
                    }
                    else
                    {
                        return(Combustivel_Incluido);
                    }
                }
                else
                {
                    MessageBox.Show("Combustivel já Existe", "Problemas ao inserir");
                }
            }
            catch (MySqlException Exception)
            {
                MessageBox.Show(Convert.ToString(Exception), "Estado da Conexão");
            }

            return(Combustivel_Incluido);
        }
Beispiel #27
0
 public CombustivelUserControl(string id = null)
 {
     InitializeComponent();
     currentID             = -1;
     currentCombustivelDao = new CombustiveisDAO(MainWindow.currentPath);
     if (id != null)
     {
         currentID             = int.Parse(id);
         currentCombustivel    = currentCombustivelDao.selectById(currentID);
         nomeTextBox.Text      = currentCombustivel.nome;
         descricaoTextBox.Text = currentCombustivel.descricao;
     }
 }
Beispiel #28
0
        // GET: Combustiveis/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Combustivel combustivel = db.Combustiveis.Find(id);

            if (combustivel == null)
            {
                return(HttpNotFound());
            }
            return(View(combustivel));
        }
 public string Excluir(Combustivel combustivel)
 {
     try
     {
         acessoDadosSqlServer.LimparParametros();
         acessoDadosSqlServer.AdicionarParametros("@IDCADCOMBUSTIVEL", combustivel.IDCADCOMBUSTIVEL);
         string IDCADCOMBUSTIVEL = acessoDadosSqlServer.ExecutarManipulacao(CommandType.StoredProcedure, "uspCADCOMBUSTIVELExcluir").ToString();
         return(IDCADCOMBUSTIVEL);
     }
     catch (Exception exception)
     {
         return(exception.Message);
     }
 }
Beispiel #30
0
        private void OnCalcular(object sender, EventArgs e)
        {
            Combustivel etanol = new Combustivel();

            etanol.Preco   = Convert.ToDouble(precoEtanolEntry.Text);
            etanol.Consumo = Convert.ToDouble(consumoMedioEtanolEntry.Text);

            Combustivel gasolina = new Combustivel();

            gasolina.Preco   = Convert.ToDouble(precoGasolinaEntry.Text);
            gasolina.Consumo = Convert.ToDouble(consumoMedioGasolinaEntry.Text);

            Navigation.PushAsync(new ResultadoPage(etanol, gasolina));
        }
Beispiel #31
0
        public bool Combustivel(Combustivel Combustivel, int TipoPesquisa)
        {
            try
            {
                DataTable        table   = new DataTable();
                MySqlDataAdapter adapter = new MySqlDataAdapter();
                MySqlCommand     command = new MySqlCommand();
                table = Consulta.Combustivel(Combustivel, TipoPesquisa);

                //Verifica se o Combustivel Ja esta cadastrado.
                if (table.Rows.Count != 0)
                {
                    if (!Conexão.Checkconection())
                    {
                        Conexão.Conectar();
                    }

                    if (Conexão.Checkconection())
                    {
                        string ExcludCombustivel = "DELETE FROM `COMBUSTIVEL` WHERE ID_COMBUSTIVEL = @ID_COMBUSTIVEL;";


                        command.CommandText = ExcludCombustivel;
                        command.Parameters.Add("@ID_COMBUSTIVEL", MySqlDbType.Int32).Value = table.Rows[0][0];

                        int retorno = command.ExecuteNonQuery();
                        if (retorno > 0)
                        {
                            Combustivel_Excluido = true;
                        }
                        Conexão.Desconectar();
                    }
                    else
                    {
                        return(Combustivel_Excluido);
                    }
                }
                else
                {
                    MessageBox.Show("Combustivel não pode ser Excluido", "Problemas ao Excluir");
                }
            }
            catch (MySqlException Exception)
            {
                MessageBox.Show(Convert.ToString(Exception), "Estado da Conexão");
            }

            return(Combustivel_Excluido);
        }
        private void buttonConsultar_Click(object sender, EventArgs e)
        {
            //Verificar se tem algum registro selecionado
            if (dataGridViewPrincipal.SelectedRows.Count == 0)
            {
                MessageBox.Show("Nenhuma opção selecionada.");
                return;
            }

            //Pegar o cliente selecionado no grid
            Combustivel combustivelSelecionado = (dataGridViewPrincipal.SelectedRows[0].DataBoundItem as Combustivel);

            //Instanciar o formulário de cadastro
            FrmCombustivelCadastrar frmCombustivelCadastrar = new FrmCombustivelCadastrar(AcaoNaTela.Consultar, combustivelSelecionado);

            frmCombustivelCadastrar.ShowDialog();
        }