Esempio n. 1
0
        private void CarregaGrid()
        {
            try
            {
                // Desativa evento para evitar erros
                grdDispositivos.SelectionChanged -= grdDispositivo_SelectionChanged;

                using (GerenciadorDB mngBD = new GerenciadorDB(false))
                {
                    BindingList <Dispositivo> bList = new BindingList <Dispositivo>(controleTela.LoadTodos(mngBD));
                    this.grdDispositivos.DataSource = bList;
                }

                if (grdDispositivos.Rows.Count == 0)
                {
                    Limpa();
                }

                grdDispositivos.AutoResizeColumns();
            }
            finally
            {
                grdDispositivos.SelectionChanged += grdDispositivo_SelectionChanged;
            }
        }
Esempio n. 2
0
        private void CarregaGrid()
        {
            try
            {
                // Desativa evento para evitar erros
                grdPiso.SelectionChanged -= grdPiso_SelectionChanged;

                using (GerenciadorDB mngBD = new GerenciadorDB(false))
                {
                    BindingList <Piso> bList = new BindingList <Piso>(controleTela.LoadTodos(mngBD));
                    this.grdPiso.DataSource = bList;
                }

                // Limpa os campos da tela se não restou nenhum piso
                if (grdPiso.Rows.Count == 0)
                {
                    Limpa();
                }

                grdPiso.AutoResizeColumns();
            }
            finally
            {
                grdPiso.SelectionChanged += grdPiso_SelectionChanged;
            }
        }
Esempio n. 3
0
        private void CarregaTela()
        {
            try
            {
                // Carrega as configurações do Banco de Dados
                using (GerenciadorDB mngBD = new GerenciadorDB(false))
                {
                    List <ConfiguracaoGeral> lstConfig = controleTela.LoadTodos(mngBD);

                    if (lstConfig.Count > 0)
                    {
                        // Pega só o primeiro, uma vez que essa tabela deverá conter uma única linha
                        ConfiguracaoGeral objConfig = lstConfig[0];

                        // Carrega as informações na tela
                        txtIdServidor.Text        = objConfig.IdServidor;
                        txtWsServidor.Text        = objConfig.WsServidor;
                        txtWsPorta.Text           = objConfig.WsPorta;
                        txtPortaSerial.Text       = objConfig.SerialPorta;
                        cmbBaudRate.SelectedIndex = cmbBaudRate.FindString(objConfig.SerialBaudRate.ToString());
                        cmbParidade.SelectedIndex = cmbParidade.FindString(Enum.GetName(typeof(Parity), objConfig.SerialParidade));
                        cmbDataBits.SelectedIndex = cmbDataBits.FindString(objConfig.SerialDataBits.ToString());
                        cmbStopBits.SelectedIndex = cmbStopBits.FindString(Enum.GetName(typeof(StopBits), objConfig.SerialStopBits));
                    }
                }
            }
            catch (Exception ex)
            {
                Biblioteca.Controle.controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, "Erro ao carregar os dados da tabela do Configuador Geral. ", ex);
                MessageBox.Show("Erro ao carregar os dados da tabela do Configurador Geral. Visualizar a tabela de logs para mais detalhes.", "Erro no Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Limpa();
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Insere objeto Modelo na Base de Dados
        /// </summary>
        public void Insert(Dictionary <string, object> DadosLinha, GerenciadorDB mngBD, ref string sDetalhesLog)
        {
            sDetalhesLog += string.Format("{0} inserido(a). Detalhes:\r\n", this.NomeEntidade);

            using (DbCommand cmd = mngBD.getCommand())
            {
                string sSQL   = string.Format("INSERT INTO {0}.{1} (", GerenciadorDB.NameSpaceDB, NomeTabela);
                string campos = "";
                string values = "";

                foreach (KeyValuePair <string, object> item in DadosLinha)
                {
                    campos += item.Key + ",";
                    values += "?,";
                    // inclui parametro utilizando metodo auxiliar
                    cmd.Parameters.Add(Parametro(item, mngBD));
                    sDetalhesLog += item.Key + ": [" + (item.Value == null ? "NULL" : item.Value.ToString()) + "]\r\n";
                }

                sSQL           += campos.Substring(0, campos.Length - 1) + ") VALUES (" + values.Substring(0, values.Length - 1) + ")";
                cmd.CommandText = sSQL;

                // Executa
                cmd.ExecuteNonQuery();
            }
        }
Esempio n. 5
0
 public static void Insere(TraceComunicacao.ProcedenciaTrace procedencia, string sControlador, string sDispositivo, string sMensagem)
 {
     using (GerenciadorDB mngBD = new GerenciadorDB(false))
     {
         Insere(procedencia, sControlador, sDispositivo, sMensagem, mngBD);
     }
 }
Esempio n. 6
0
 public static void Insere(Log.LogTipo tipo, string sDescricao, Exception exc = null)
 {
     using (GerenciadorDB mngBD = new GerenciadorDB(false))
     {
         Insere(tipo, sDescricao, exc, mngBD);
     }
 }
Esempio n. 7
0
        private void ConfiguraTela()
        {
            // Adiciona controle visual do dispositivo
            imgPiso.Controls.Add(pairDispSelecionado.Key);
            pairDispSelecionado.Key.BringToFront();
            pairDispSelecionado.Key.Visible = false;

            using (GerenciadorDB mngBD = new GerenciadorDB(false))
            {
                ConfiguraGrid();
                CarregaGrid();

                // Carrega pisos e configura ComboBox
                _lstPisos = new controlBase <Piso>().LoadTodos(mngBD);

                var CodigosPiso = from Piso objAux in _lstPisos
                                  select objAux.Codigo;

                cmbPiso.DropDownStyle = ComboBoxStyle.DropDownList;
                List <string> lstCodigosPiso = CodigosPiso.ToList();
                lstCodigosPiso.Insert(0, string.Empty);
                cmbPiso.DataSource = lstCodigosPiso;

                // Configura ComboBox Tipos
                cmbTipo.DropDownStyle = ComboBoxStyle.DropDownList;
                List <string> lstTipos = Enum.GetNames(typeof(Dispositivo.TipoSensor)).ToList();
                lstTipos.Insert(0, string.Empty);
                cmbTipo.DataSource = lstTipos;
            }
        }
Esempio n. 8
0
        public bool Salva(ModeloBase <M> objModelo, GerenciadorDB mngBD)
        {
            bool   bRetorno     = false;
            string sDetalhesLog = string.Empty;

            if (objModelo.Status == ModeloBase <M> .ObjetoStatus.NaoAlterado)
            {
                // Não realiza nenhuma alteração
            }
            else if (objModelo.Status == ModeloBase <M> .ObjetoStatus.Novo)
            {
                // Insert
                Insert(getDicionarioColValores(objModelo), mngBD, ref sDetalhesLog);
            }
            else if (objModelo.Status == ModeloBase <M> .ObjetoStatus.Editado)
            {
                // Update
                Update(getDicionarioColValores(objModelo), getDicionarioColValores(objModelo._objetoOriginal), mngBD, ref sDetalhesLog);
                // Atualiza o ObjetoOriginal para o que acabou de ser salvo
                objModelo.CarregaObjeto(getDicionarioColValores(objModelo), getDicionarioColPropInfo(objModelo));
            }
            else
            {
                throw new Exception(string.Format("Solicitado salvamento para objeto ModeloBase com STATUS inválido. Valor recebido: {0}",
                                                  Enum.GetName(typeof(ModeloBase <M> .ObjetoStatus), objModelo.Status)));
            }

            return(bRetorno);
        }
Esempio n. 9
0
        private void CarregaGrid()
        {
            try
            {
                BindingList <TraceComunicacao> bList;

                using (GerenciadorDB mngBD = new GerenciadorDB(false))
                {
                    // Filtra pelas Datas
                    bList = new BindingList <TraceComunicacao>(controleTela.LoadFiltro(mngBD, decimal.ToInt32(numMaximoLinhas.Value), t => t.DataHoraOcorrencia >= dtInicio.Value, t => t.DataHoraOcorrencia <= dtFinal.Value));
                }

                // Pega as procedencias de trace selecionadas no filtro para exibição
                List <TraceComunicacao.ProcedenciaTrace> lstProcedenciaTrace = GetProcedenciaTraceSelecionados();

                // Aplica Filtros restantes
                var auxTrace = (from TraceComunicacao objTrace in bList.OrderByDescending(l => l.ID)
                                where lstProcedenciaTrace.Contains(objTrace.Procedencia)
                                select objTrace).Select(t => { t.Mensagem = Util.TraduzCaracteresEspeciais(t.Mensagem); return(t); });

                List <TraceComunicacao> lstTrace = auxTrace.ToList();

                #region Filtros Opcionais

                // Filtro pelo ID da ocorrência do Trace
                if (!string.IsNullOrEmpty(txtOcorrencia.Text))
                {
                    lstTrace = lstTrace.Where(t => t.ID.ToString() == txtOcorrencia.Text).ToList();
                }

                // Filtro pelo código do Controlador
                if (!string.IsNullOrEmpty(txtControlador.Text))
                {
                    lstTrace = lstTrace.Where(t => t.Controlador == txtControlador.Text).ToList();
                }

                // Filtro pelo código do Dispositivo
                if (!string.IsNullOrEmpty(txtDispositivo.Text))
                {
                    lstTrace = lstTrace.Where(t => t.Dispositivo == txtDispositivo.Text).ToList();
                }

                #endregion

                this.grdTraceOcorrencias.DataSource = lstTrace;

                if (grdTraceOcorrencias.Columns.Contains("DataHoraOcorrencia"))
                {
                    grdTraceOcorrencias.Columns["DataHoraOcorrencia"].DefaultCellStyle.Format = "dd/MM/yyyy HH:mm:ss";
                }

                grdTraceOcorrencias.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                Biblioteca.Controle.controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, "Erro ao carregar ocorrências de Trace. ", ex);
                MessageBox.Show("Erro ao Carregar as ocorrências de Trace do sistema.", "Erro no Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Devolve DBParameter com base no nome (string) e no valor (object);
        /// </summary>
        private DbParameter Parametro(KeyValuePair <string, object> item, GerenciadorDB mngDB)
        {
            // Nesse momento estamos utilizando MySqlParameter, deixa todo o encapsulamento dentro da classe GerenciadorBD
            DbParameter paramRet = mngDB.getParameter();

            if (item.Value != null)
            {
                // Associa valor ao DBParameter
                paramRet.Value = item.Value;

                // Verifica Type da propriedade
                Type tipo = item.Value.GetType();
                paramRet.ParameterName = item.Key + Guid.NewGuid().ToString("N");

                if (item.Value.GetType() == typeof(string))
                {
                    paramRet.DbType = DbType.String;

                    //if (string.IsNullOrEmpty(item.Value.ToString()))
                    //    paramRet.Value = DBNull.Value;
                }
                else if (item.Value.GetType() == typeof(decimal))
                {
                    paramRet.DbType = DbType.Decimal;
                }
                else if (item.Value.GetType() == typeof(int))
                {
                    paramRet.DbType = DbType.Int32;
                }
                else if (item.Value.GetType() == typeof(DateTime))
                {
                    if (item.Value is DateTime && ((DateTime)item.Value).Equals(((DateTime)item.Value).Date))
                    {
                        paramRet.DbType = DbType.Date;
                    }
                    else
                    {
                        paramRet.DbType = DbType.DateTime;
                    }
                }
                else if (item.Value.GetType() == typeof(bool))
                {
                    paramRet.DbType = DbType.Boolean;
                }
                else if (item.Value.GetType() == typeof(float) || item.Value.GetType() == typeof(Double))
                {
                    paramRet.DbType = DbType.Double;
                }
            }
            else
            {
                paramRet.Value = DBNull.Value;
            }

            // Retorna DBParameter
            return(paramRet);
        }
Esempio n. 11
0
        /// <summary>
        /// Testa o Arquivo 'conexoes.xml' de Conexão ao Danco de Dados e grava os dados em memória enquanto o sistema estiver sendo executado
        /// </summary>
        /// <returns>Retorna se o teste da Conexão ao Banco de Dados funcionou ou não</returns>
        public static bool TestaArquivoConexao()
        {
            bool   bSucesso   = false;
            string sDiretorio = string.Empty;

            // Pega o Arquivo de Conexões
            sDiretorio = GetArquivoConexao();
            if (string.IsNullOrEmpty(sDiretorio))
            {
                return(false);
            }

            // Faz a leitura do arquivo Xml
            XmlDocument xmlConexoes = new XmlDocument();

            xmlConexoes.Load(sDiretorio);

            // Pega o Server e Port especificados no arquivo para a conexão com o Banco de Dados
            XmlNode xmlDados = xmlConexoes.DocumentElement.SelectSingleNode("/Conexoes/Banco");

            // Seta os dados para as conexões a serem realizadas enquanto o sistema estiver sendo executado
            GerenciadorDB._Server = xmlDados["Server"].InnerText;
            GerenciadorDB._Port   = xmlDados["Port"].InnerText;

            // Testa Conexão
            try
            {
                using (GerenciadorDB mngBD = new GerenciadorDB(false))
                {
                    bSucesso = true;
                }
            }
            catch
            {
                // Se caiu aqui, a conexão não funcionou
            }
            //catch (Exception exc)
            //{
            //	using (FileStream fs = new FileStream("C:\\temp\\log.txt", FileMode.OpenOrCreate, FileAccess.Write))
            //	{
            //		using (StreamWriter w = new StreamWriter(fs))
            //		{
            //			w.BaseStream.Seek(0, SeekOrigin.End);
            //			w.WriteLine(exc.ToString());
            //			w.Flush();
            //			w.Close();
            //		}

            //		fs.Close();
            //	}
            //}

            return(bSucesso);
        }
Esempio n. 12
0
        protected override void Salva()
        {
            string sMensagem = string.Empty;

            // Valida Dados
            if (!Valida(out sMensagem))
            {
                MessageBox.Show(sMensagem, "As configurações não puderam ser salvas", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                return;
            }

            try
            {
                using (GerenciadorDB mngBD = new GerenciadorDB(true))
                {
                    ConfiguracaoGeral objConfig = new ConfiguracaoGeral();

                    // Monta objeto do Configurador Geral
                    objConfig.IdServidor     = txtIdServidor.Text;
                    objConfig.WsServidor     = txtWsServidor.Text;
                    objConfig.WsPorta        = txtWsPorta.Text;
                    objConfig.SerialPorta    = txtPortaSerial.Text;
                    objConfig.SerialBaudRate = int.Parse(cmbBaudRate.SelectedValue.ToString());
                    objConfig.SerialParidade = (Parity)Enum.Parse(typeof(Parity), cmbParidade.SelectedValue.ToString());
                    objConfig.SerialDataBits = int.Parse(cmbDataBits.SelectedValue.ToString());
                    objConfig.SerialStopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.SelectedValue.ToString());

                    // Antes de salvar, verifica se já existe algo salvo na tabela (Essa tabela pode conter apenas uma linha)
                    List <ConfiguracaoGeral> lstConfig = controleTela.LoadTodos(mngBD);

                    // Apaga todos os itens recebidos
                    foreach (ConfiguracaoGeral oldConfig in lstConfig)
                    {
                        controleTela.Apaga(oldConfig, mngBD);
                    }

                    // Salva a nova Configuração
                    controleTela.Salva(objConfig, mngBD);

                    mngBD.ConfirmaTransacao();
                }
            }
            catch (Exception ex)
            {
                Biblioteca.Controle.controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, "Erro ao salvar Configuador Geral. ", ex);
                MessageBox.Show("Erro ao Salvar Configurador Geral. Visualizar a tabela de logs para mais detalhes.", "Erro no Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                base.Salva();
                CarregaTela();
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Carrega todos objetos Modelo da tabela
        /// </summary>
        public List <M> LoadTodos(GerenciadorDB mngBD, int?MaxLinhas)
        {
            //string sSQL = string.Format("SELECT {0} * FROM {1}", (MaxLinhas != null ? "TOP " + MaxLinhas : ""), NomeTabela);
            string sSQL = string.Format("SELECT * FROM {0}", NomeTabela);

            if (MaxLinhas != null)
            {
                sSQL = string.Format("{0} LIMIT {1}", sSQL, MaxLinhas);
            }

            using (DbCommand cmd = mngBD.getCommand(sSQL))
            {
                return(ListObjetosCarregados(ExecutaQuery(cmd)));
            }
        }
Esempio n. 14
0
        private void ConfiguraTela()
        {
            using (GerenciadorDB mngBD = new GerenciadorDB(false))
            {
                // Carrega pisos e configura ComboBox
                _lstPisos = new controlBase <Piso>().LoadTodos(mngBD);

                var CodigosPiso = from Piso objAux in _lstPisos
                                  select objAux.Codigo;

                cmbPiso.DropDownStyle = ComboBoxStyle.DropDownList;
                List <string> lstCodigosPiso = CodigosPiso.ToList();
                lstCodigosPiso.Insert(0, string.Empty);
                cmbPiso.DataSource = lstCodigosPiso;
            }
        }
Esempio n. 15
0
        public bool Apaga(ModeloBase <M> objModelo, GerenciadorDB mngBD)
        {
            bool   bRetorno     = false;
            string sDetalhesLog = string.Empty;

            if (objModelo.Status != ModeloBase <M> .ObjetoStatus.Novo)
            {
                // Delete
                Delete(getDicionarioColValores(objModelo._objetoOriginal), mngBD, ref sDetalhesLog);
                bRetorno = true;
            }
            else
            {
                throw new Exception(string.Format("Solicitado exclusão para objeto ModeloBase com STATUS inválido. Valor recebido: {0}",
                                                  Enum.GetName(typeof(ModeloBase <M> .ObjetoStatus), objModelo.Status)));
            }

            return(bRetorno);
        }
Esempio n. 16
0
        private void CarregaGrid()
        {
            try
            {
                BindingList <Log> bList;

                // Pega os tipos de logs selecionados no filtro para exibição
                List <Log.LogTipo> lstTiposLog = GetTipoLogsSelecionados();

                using (GerenciadorDB mngBD = new GerenciadorDB(false))
                {
                    bList = new BindingList <Log>(controleTela.LoadFiltro(mngBD, decimal.ToInt32(numMaximoLinhas.Value), l => l.DataHoraInclusao >= dtInicio.Value, l => l.DataHoraInclusao <= dtFinal.Value));
                }

                // Aplica filtros da tela na lista
                var auxLogs = from Log objLog in bList.OrderByDescending(l => l.ID)
                              where lstTiposLog.Contains(objLog.Tipo)
                              select objLog;

                List <Log> lstLogs = auxLogs.ToList();

                // Se o filtro direto por ID de ocorrência foi utilizado, faz a busca
                if (!string.IsNullOrEmpty(txtOcorrencia.Text))
                {
                    lstLogs = lstLogs.Where(l => l.ID.ToString() == txtOcorrencia.Text).ToList();
                }

                this.grdLogs.DataSource = lstLogs;

                if (grdLogs.Columns.Contains("DataHoraInclusao"))
                {
                    grdLogs.Columns["DataHoraInclusao"].DefaultCellStyle.Format = "dd/MM/yyyy HH:mm:ss";
                }

                grdLogs.AutoResizeColumns();
            }
            catch (Exception ex)
            {
                Biblioteca.Controle.controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, "Erro ao carregar logs. ", ex);
                MessageBox.Show("Erro ao Carregar os logs na tela.", "Erro no Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 17
0
        private void CarregaImagemPisoSelecionado()
        {
            if (cmbPiso.SelectedValue != null && !string.IsNullOrEmpty(cmbPiso.SelectedValue.ToString()))
            {
                var auxPiso = from Piso objAux in _lstPisos
                              where objAux.Codigo == cmbPiso.SelectedValue.ToString()
                              select objAux;

                Piso objPisoSelecionado = auxPiso.First();

                if (objPisoSelecionado != null)
                {
                    // Carrega a imagem do Piso no PictureBox
                    imgPiso.Image = Biblioteca.Util.byteArrayToImage(objPisoSelecionado.Imagem);

                    using (GerenciadorDB mngBD = new GerenciadorDB(false))
                    {
                        // Carrega os Dispositivos associados ao Piso selecionado
                        _lstDispositivos = new controlBase <Dispositivo>().LoadFiltro(mngBD, p => p.Piso == cmbPiso.SelectedValue.ToString());

                        // Carrega os dispositivos no Piso
                        foreach (Dispositivo disp in _lstDispositivos)
                        {
                            ctlDispositivoBase ctlDisp = FactoryControlDispositivo.getControleDispositivo(disp);
                            ctlDisp.PermiteArrastar(false);
                            ctlDisp.setPosicaoDispositivoNaImagem(disp.PosicaoX, disp.PosicaoY, imgPiso);
                            ctlDisp.Visible = true;
                            ctlDisp.AtivaTimerExibicao(true, 1000);

                            // Exibe o dispositivo na tela
                            imgPiso.Controls.Add(ctlDisp);
                            ctlDisp.BringToFront();

                            // Adiciona em um dicionario que deverá conter sempre os Dispositivos do Piso selecionado
                            Point pDisp = new Point(disp.PosicaoX, disp.PosicaoY);
                            _dicDispositivos.Add(ctlDisp, pDisp);
                        }
                    }
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Exclui um objeto Modelo na Base de Dados
        /// </summary>
        private void Delete(Dictionary <string, object> DadosOriginal, GerenciadorDB mngBD, ref string sDetalhesLog)
        {
            sDetalhesLog += string.Format("{0} apagado(a). Detalhes:\r\n", NomeEntidade);

            using (System.Data.Common.DbCommand cmd = mngBD.getCommand())
            {
                string sSQL = string.Format("DELETE FROM {0}.{1} WHERE ", GerenciadorDB.NameSpaceDB, NomeTabela);

                // inclui todos os parametros no where para verificar concorrencia
                foreach (KeyValuePair <string, object> itemOriginal in DadosOriginal)
                {
                    // Verifica se valor é NULL
                    string VerifNull = itemOriginal.Value == null || (itemOriginal.Value is string && string.IsNullOrEmpty((string)itemOriginal.Value)) ||
                                       (itemOriginal.Value is bool && (bool)itemOriginal.Value == false) || (itemOriginal.Value is int && (int)itemOriginal.Value == 0) ? "1" : "0";

                    // SQL do parâmetro
                    sSQL += "((1=" + VerifNull + " AND " + itemOriginal.Key + " is NULL) OR (" + itemOriginal.Key + "=?" + (VerifNull == "1" && itemOriginal.Value is string? " OR " + itemOriginal.Key + "=\'\'" : "") + ")) AND ";

                    // Adiciona parâmetro
                    cmd.Parameters.Add(Parametro(itemOriginal, mngBD));

                    // descrição LOG
                    sDetalhesLog += itemOriginal.Key + ": [" + (itemOriginal.Value == null ? "NULL" : itemOriginal.Value.ToString()) + "]\r\n";
                }

                sSQL = sSQL.Substring(0, sSQL.Length - 5);

                cmd.CommandText = sSQL;
                cmd.Prepare();

                // Executa
                int iAffectedRows = cmd.ExecuteNonQuery();

                if (!iAffectedRows.Equals(1))
                {
                    throw new Exception(string.Format("Erro ao executar delete. Não foi afetado o número esperado de linhas.\r\nLinhas afetadas: {0}.\r\nDetalhes: {1}.", iAffectedRows, sDetalhesLog));
                }
            }
        }
Esempio n. 19
0
        protected override void Apaga()
        {
            try
            {
                // Sai se nenhum piso do grid estiver selecionado
                if (grdPiso.CurrentRow == null)
                {
                    MessageBox.Show("Não há nenhum piso selecionado. Selecione um piso para poder apagá-lo.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Limpa();
                    return;
                }

                // Janela de confirmação
                DialogResult drApaga = MessageBox.Show("Tem certeza que deseja apagar o piso selecionado?", "Apagar Piso", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (drApaga == DialogResult.Yes)
                {
                    using (GerenciadorDB mngBD = new GerenciadorDB(false))
                    {
                        Piso objPisoSelecionado = (Piso)grdPiso.CurrentRow.DataBoundItem;
                        controleTela.Apaga(objPisoSelecionado, mngBD);

                        string sDetalhe = "Piso '" + objPisoSelecionado.Codigo + "' apagado com sucesso.";
                        Biblioteca.Controle.controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.ManutencaoTabelaPisos, sDetalhe);
                    }
                }
            }
            catch (Exception exc)
            {
                Biblioteca.Controle.controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, "Erro ao apagar piso. ", exc);
                MessageBox.Show("Erro ao Apagar Piso. Visualizar a tabela de logs para mais detalhes.", "Erro no Sistema", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                base.Apaga();
                CarregaGrid();
            }
        }
Esempio n. 20
0
 public GerenciadorUsuario()
 {
     gerenciadorDB = new GerenciadorDB();
 }
Esempio n. 21
0
 public GerenciadorLote()
 {
     gerenciadorDB = new GerenciadorDB();
 }
Esempio n. 22
0
        public static void Insere(Log.LogTipo tipo, string sDescricao, Exception exc, GerenciadorDB mngBD)
        {
            try
            {
                Log objLog = new Log();

                objLog.DataHoraInclusao = DateTime.Now;
                objLog.Tipo             = tipo;
                objLog.Descricao        = sDescricao;

                // Se recebido exceção
                if (exc != null)
                {
                    objLog.Descricao += "\r\n" + exc.ToString();
                }

                new Controle.controlLog().Salva(objLog, mngBD);
            }
            catch
            {
                /// Se caiu aqui #$%#@
            }
        }
Esempio n. 23
0
 public GerenciadorLeilao()
 {
     gerenciadorDB = new GerenciadorDB();
 }
Esempio n. 24
0
 /// <summary>
 /// Carrega objetos do Modelo que passem pelo filtro informado
 /// </summary>
 public List <M> LoadFiltro(GerenciadorDB mngBD, params Expression <Func <M, object> >[] ListaFiltro)
 {
     return(LoadFiltro(mngBD, null, ListaFiltro));
 }
Esempio n. 25
0
        /// <summary>
        /// Carrega objetos do Modelo que passem pelo filtro informado
        /// </summary>
        public List <M> LoadFiltro(GerenciadorDB mngBD, int?MaxLinhas, params Expression <Func <M, object> >[] ListaFiltro)
        {
            //string sSQL = string.Format("SELECT {0} * FROM {1}", (MaxLinhas != null ? "TOP " + MaxLinhas : ""), NomeTabela);
            string sSQL = string.Format("SELECT * FROM {0}", NomeTabela);

            using (DbCommand cmd = mngBD.getCommand(sSQL))
            {
                string sWhere = "";
                foreach (Expression <Func <M, object> > item in ListaFiltro)
                {
                    dynamic operation = item.Body;
                    dynamic operand   = operation.Operand;
                    string  campo     = "";
                    object  valor     = "";
                    string  operacao  = "";

                    if (operand is MethodCallExpression)
                    {
                        campo    = operand.Object.Member.Name;
                        valor    = operand.Arguments[0];
                        operacao = operand.Method.Name;
                    }
                    else
                    {
                        campo = operand.Left.Member.Name;

                        if (operand.Right is System.Linq.Expressions.ConstantExpression)
                        {
                            valor = operand.Right.Value;
                        }
                        else
                        {
                            valor = GetValueExpression(operand.Right);
                        }

                        operacao = Operacoes[operation.Operand.NodeType];
                    }

                    if (valor == null || valor == DBNull.Value)
                    {
                        sWhere += string.Format("{0}({1} IS NULL)", (sWhere != "" ? " AND " : ""), campo, operacao);
                    }
                    else
                    {
                        sWhere += string.Format("{0}({1}{2}?)", (sWhere != "" ? " AND " : ""), campo, operacao);
                        cmd.Parameters.Add(Parametro(new KeyValuePair <string, object>(campo, valor), mngBD));
                    }
                }

                if (ListaFiltro.Count() > 0)
                {
                    cmd.CommandText = string.Format("{0} WHERE {1}", cmd.CommandText, sWhere);
                }

                if (MaxLinhas != null)
                {
                    cmd.CommandText = string.Format("{0} LIMIT {1}", cmd.CommandText, MaxLinhas);
                }

                // Executa query
                return(ListObjetosCarregados(ExecutaQuery(cmd)));
            }
        }
Esempio n. 26
0
        public static void Insere(TraceComunicacao.ProcedenciaTrace procedencia, string sControlador, string sDispositivo, string sMensagem, GerenciadorDB mngBD)
        {
            try
            {
                TraceComunicacao objTrace = new TraceComunicacao();

                objTrace.Procedencia = procedencia;
                objTrace.Controlador = sControlador;
                objTrace.Dispositivo = sDispositivo;
                objTrace.Mensagem = sMensagem;
                objTrace.DataHoraOcorrencia = DateTime.Now;

                new controlTrace().Salva(objTrace, mngBD);
            }
            catch(Exception ex)
            {
                string sMsg = "Erro ao salvar uma ocorrência de Trace.\r\n";
                sMsg += "Procedência: " + Enum.GetName(typeof(TraceComunicacao.ProcedenciaTrace), procedencia) + "\r\n";
                sMsg += "Controlador: " + sControlador + "\r\n";
                sMsg += "Dispositivo: " + sDispositivo + "\r\n";
                sMsg += "Mensagem: " + sMensagem + ". ";
                Biblioteca.Controle.controlLog.Insere(Biblioteca.Modelo.Log.LogTipo.Erro, sMsg, ex);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Atualiza objeto Modelo na Base de Dados
        /// </summary>
        public void Update(Dictionary <string, object> DadosAlterados, Dictionary <string, object> DadosOriginal, GerenciadorDB mngBD, ref string sDetalhesLog)
        {
            sDetalhesLog += string.Format("{0} editado(a). Detalhes:\r\n", this.NomeEntidade);

            using (DbCommand cmd = mngBD.getCommand())
            {
                string sSQL = string.Format("UPDATE {0}.{1} SET ", GerenciadorDB.NameSpaceDB, NomeTabela);

                // Seta com os parametros atuais
                foreach (KeyValuePair <string, object> item in DadosAlterados)
                {
                    // Não faz update de campos não alterados
                    if (
                        (item.Value != null && DadosOriginal != null && DadosOriginal.ContainsKey(item.Key) && DadosOriginal[item.Key] != null && item.Value.Equals(DadosOriginal[item.Key])) ||
                        (item.Value == null && (DadosOriginal == null || !DadosOriginal.ContainsKey(item.Key) || DadosOriginal[item.Key] == null))
                        )
                    {
                        continue;
                    }

                    if ((item.Value == null && DadosOriginal[item.Key] != null) ||
                        (item.Value != null && DadosOriginal[item.Key] == null) ||
                        ((item.Value != null && DadosOriginal[item.Key] != null) && (!item.Value.Equals(DadosOriginal[item.Key])))
                        )
                    {
                        sDetalhesLog += item.Key + ": [";
                        if (DadosOriginal != null && DadosOriginal.ContainsKey(item.Key))
                        {
                            sDetalhesLog += (DadosOriginal[item.Key] == null ? "NULL" : DadosOriginal[item.Key].ToString()) + "] --> [";
                        }
                        sDetalhesLog += (item.Value == null ? "NULL" : item.Value.ToString()) + "]\r\n";
                    }

                    // SQL do parâmetro, valor novo
                    sSQL += item.Key + "=?,";

                    // Adiciona parâmetro
                    cmd.Parameters.Add(Parametro(item, mngBD));
                }

                //se nenhum campo deve ser alterado, retorna sem executar
                if (cmd.Parameters.Count == 0)
                {
                    return;
                }

                sSQL = sSQL.Substring(0, sSQL.Length - 1) + " Where ";

                // Verifica parametros originais para concorrencia
                // Ou seja, coloca valores anteriores na condição, pois qualquer se tabela está diferente do esperado gera Exception
                foreach (KeyValuePair <string, object> itemOriginal in DadosOriginal)
                {
                    string VerifNull = itemOriginal.Value == null || (itemOriginal.Value is string && string.IsNullOrEmpty((string)itemOriginal.Value)) ||
                                       (itemOriginal.Value is bool && (bool)itemOriginal.Value == false) || (itemOriginal.Value is int && (int)itemOriginal.Value == 0) ? "1" : "0";

                    // SQL do parâmetro valor anterior (condição)
                    sSQL += "((1=" + VerifNull + " AND " + itemOriginal.Key + " is NULL) OR (" + itemOriginal.Key + "=?" + (VerifNull == "1" && itemOriginal.Value is string? " OR " + itemOriginal.Key + "=\'\'" : "") + ")) AND ";

                    // Adiciona parâmetro
                    cmd.Parameters.Add(Parametro(itemOriginal, mngBD));
                }

                sSQL = sSQL.Substring(0, sSQL.Length - 5);

                cmd.CommandText = sSQL;
                cmd.Prepare();

                // Executa
                int iAffectedRows = cmd.ExecuteNonQuery();

                if (!iAffectedRows.Equals(1))
                {
                    throw new Exception(string.Format("Erro ao executar Update. Não foi afetado o número esperado de linhas.\r\nLinhas afetadas: {0}.\r\nDetalhes: {1}.", iAffectedRows, sDetalhesLog));
                }
            }
        }
Esempio n. 28
0
 public GerenciadorLance()
 {
     gerenciadorDB = new GerenciadorDB();
 }
Esempio n. 29
0
 /// <summary>
 /// Carrega todos objetos Modelo da tabela
 /// </summary>
 public List <M> LoadTodos(GerenciadorDB mngBD)
 {
     return(LoadTodos(mngBD, null));
 }