Esempio n. 1
0
        protected Dictionary <String, DbParameter> criarParamatros(IEntidade entidade)
        {
            Type tipo = entidade.GetType();

            Dictionary <String, DbParameter> param = new Dictionary <String, DbParameter>();
            Dictionary <String, Type>        tipos = entidade.obterTiposMapeado();

            foreach (String k in tipos.Keys)
            {
                PropertyInfo p = tipo.GetProperty(k, new Type[] { });
                if (p == null || p.GetCustomAttributes(typeof(Transiente), true).Length > 0)
                {
                    continue;
                }



                if (p.GetValue(entidade, null) == null)
                {
                    param.Add(k, ad.criaParametro(k, ConverteUtils.converteParaDbType(tipos[k]), DBNull.Value));
                }
                else if (tipos[k].IsEnum)
                {
                    param.Add(k, ad.criaParametro(k, DbType.Int32, (int)p.GetValue(entidade, null)));
                }
                else if (tipos[k].IsSubclassOf(typeof(AbstractEntidade)))
                {//Se for uma entidade: 1-obtem seu mapeamento de chaves, 2-Pega a primeira chave e passa para o mapeamento
                    IEntidade tmp = (IEntidade)p.GetValue(entidade);
                    Dictionary <string, Type> chv = tmp.obterTiposMapeadoChave();
                    String priChv = chv.Keys.First();
                    param.Add(k, ad.criaParametro(k, ConverteUtils.converteParaDbType(chv[priChv]), tmp[priChv]));
                }
                else if (tipos[k] == typeof(TimeSpan))
                {
                    TimeSpan ts = (TimeSpan)p.GetValue(entidade, null);
                    //DateTime data = new DateTime(1981, 1, 30, ts.Hours, ts.Minutes, ts.Seconds);
                    param.Add(k, ad.criaParametro(k, ConverteUtils.converteParaDbType(tipos[k]), ts));
                }
                else
                {
                    param.Add(k, ad.criaParametro(k, ConverteUtils.converteParaDbType(tipos[k]), p.GetValue(entidade, null)));
                }
            }

            return(param);
        }
Esempio n. 2
0
        public virtual void excluir(E entidade)
        {
            Type tipo = typeof(E);

            List <DbParameter>        param = new List <DbParameter>();
            Dictionary <String, Type> tipos = entidade.obterTiposMapeadoChave();

            foreach (String k in tipos.Keys)
            {
                param.Add(ad.criaParametro(k, ConverteUtils.converteParaDbType(tipos[k]), tipo.GetProperty(k, new Type[] { }).GetValue(entidade, null)));
            }

            bool controleInterno = ad.conexaoFechada();

            if (controleInterno)
            {
                ad.abreConexao();
            }

            StringBuilder sql = new StringBuilder("Delete from ");

            sql.Append(obterTabela());
            sql.Append(entidade.whereComChave());

            try
            {
                ad.executaComando(sql.ToString(), param.ToArray());
            }
            catch (Exception ex)
            {
                String msg = String.Format("Falha ao tentar excluir registro no banco de dados.\n{0}", ex.Message);
                if (ex.Message.IndexOf("FK_") > -1)
                {
                    msg = String.Format("Falha de integridade referencia na tentativa de excluir o registro, possívelmente ele já esta em uso pelo sistema.\n{0}", ex.Message);
                }
                throw new Exception(msg, ex);
            }

            if (controleInterno)
            {
                ad.fechaConexao();
            }
        }
Esempio n. 3
0
        public virtual E obter(E chave)
        {
            bool controleInterno = ad.conexaoFechada();

            if (controleInterno)
            {
                ad.abreConexao();
            }

            List <DbParameter>        param = new List <DbParameter>();
            Dictionary <String, Type> tipos = chave.obterTiposMapeadoChave();

            foreach (String k in tipos.Keys)
            {
                param.Add(ad.criaParametro(k, ConverteUtils.converteParaDbType(tipos[k]), typeof(E).GetProperty(k, new Type[] { }).GetValue(chave, null)));
            }

            StringBuilder sql = new StringBuilder("Select * from ");

            sql.Append(obterTabela());
            sql.Append(chave.whereComChave());

            E           entidade = null;
            IDataReader dr       = ad.retornaDR(sql.ToString(), param.ToArray());

            if (dr.Read())
            {
                entidade = (E)typeof(E).GetConstructors()[0].Invoke(null);
                entidade.deReader(dr);
            }
            dr.Close();

            if (controleInterno)
            {
                ad.fechaConexao();
            }

            return(entidade);
        }
Esempio n. 4
0
        public AcessaDadosConstrutor adicionaSqlComParametro(ISqlConstrutor sqlConstrutor, String propriedade, object valorParametro)
        {
            DbType tipoParam = ConverteUtils.converteParaDbType(valorParametro.GetType());

            return(adicionaSqlComParametro(sqlConstrutor, propriedade, tipoParam, valorParametro));
        }
Esempio n. 5
0
 public AcessaDadosConstrutor adicionaParametro(string nomeParametro, object valorParametro)
 {
     return(adicionaParametro(nomeParametro, ConverteUtils.converteParaDbType(valorParametro.GetType()), valorParametro));
 }
Esempio n. 6
0
        private void inicializarProcesso()
        {
            #region Obtém o funcionário em sessão
            funcionario = JsonConvert.DeserializeObject <Funcionario>(
                c.GetAsync(String.Format("servico/ObterFuncionarioPorLogin/{0}", usuario))
                .Result.Content.ReadAsStringAsync()
                .Result);
            if (funcionario == null || String.IsNullOrEmpty(funcionario.LoginAD))
            {
                MessageBox.Show(this.Owner, String.Format("Falha ao obter funcionário para o login {0}.", usuario), "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                mataReboot();
                Application.Exit();
                return;
            }
            #endregion

            #region Verifica se o funcionário é gerente (interfere na notificação de lembrete para hora extra)
            if (String.IsNullOrEmpty(eGerente))
            {
                String matricula =
                    c.GetAsync(String.Format("servico/verificaSeEGerente/{0}", funcionario.Id))
                    .Result.Content.ReadAsStringAsync()
                    .Result ?? String.Empty;
                matricula = matricula.Replace("\"", "");
                eGerente  = matricula != String.Empty ? "sim" : "nao";
            }
            #endregion

            #region Obtém hora do servidor
            try
            {
                String str = c.GetAsync("servico/obterHora").Result.Content.ReadAsStringAsync().Result;
                str                     = str.Substring(str.LastIndexOf("T") + 1, str.LastIndexOf(".") - str.LastIndexOf("T") - 1);
                hora                    = ConverteUtils.sempreConverteDate(str);
                iniciouHora             = true;
                timerObservador.Enabled = true;
            }
            catch (Exception)
            {
                MessageBox.Show(this.Owner, "Falha ao obter hora do servidor.", "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                iniciouHora = false;
                mataReboot();
                Application.Exit();
                return;
            }
            #endregion

            #region Obtém jornada do funcionário
            jornada = JsonConvert.DeserializeObject <JornadaTrabalho>(
                c.GetAsync(String.Format("servico/ObterJornadaTrabalho/{0}", funcionario.IdJornada))
                .Result.Content.ReadAsStringAsync()
                .Result);
            if (jornada == null)
            {
                MessageBox.Show(this.Owner, String.Format("Falha ao obter jornada para funcionário {0} - {1}.", funcionario.Id, funcionario.Nome), "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                mataReboot();
                Application.Exit();
                return;
            }
            #endregion

            #region Pega a frequência das notificações de batida na janela de intervalo
            try
            {
                frequenciaNotificacaoIntervalo = JsonConvert.DeserializeObject <Int32>(c.GetAsync("servico/obterFrequenciaNotificacaoIntervalo")
                                                                                       .Result.Content.ReadAsStringAsync()
                                                                                       .Result);
            }
            catch (Exception)
            {
                //Caso não seja possível obter o parâmetro, o padrão será o tempo da iteração do agente (40 segundos)
                frequenciaNotificacaoIntervalo = timer.Interval;
            }
            #endregion

            #region Calcula intervalos
            TimeSpan hr = jornada.Inicio;
            for (int i = 0; i < jornada.InterRepeticoes; i++)
            {
                hr = hr.Add(TimeSpan.FromMinutes(50));
                intervalos.Add(hr);
                hr = hr.Add(TimeSpan.FromMinutes(10));
            }
            #endregion

            #region Obtém a frequência de iteração do agente
            try
            {
                int emSegundos = JsonConvert.DeserializeObject <Int32>(c.GetAsync("servico/obterFrequenciaIteracaoAgente")
                                                                       .Result.Content.ReadAsStringAsync()
                                                                       .Result);
                //Converte para milissegundos
                this.timer.Interval = emSegundos * 1000;
            }
            catch (Exception)
            {
                //timer.Interval já traz um valor padrão, atribuído em FrmPrinc.Designer.cs
                //Não é necessário tratar a exceção
            }
            #endregion

            #region Obter período pré hora extra
            //Em minutos
            try
            {
                periodoPreHoraExtra =
                    JsonConvert.DeserializeObject <Int32>(c.GetAsync("servico/obterPeriodoPreHoraExtra")
                                                          .Result.Content.ReadAsStringAsync().Result);
            }
            catch (Exception)
            {
                //Define um valor padrão caso haja problema na consulta do parâmetro
                periodoPreHoraExtra = 15;
            }
            #endregion

            #region Verifica se deve ser mostrado o demonstrativo após a batida de ponto
            mostrarDemonstrativo = true;

            /*ConverteUtils.sempreConverteBoleano(JsonConvert.DeserializeObject<string>(
             *                                                                      c.GetAsync("servico/deveMostrarDemonstrativoAposBatida")
             *                                                                          .Result.Content.ReadAsStringAsync().Result));*/
            #endregion

            #region Obtém batidas do dia
            //batidasDoDia = JsonConvert.DeserializeObject<IList<Batida>>(
            //    c.GetAsync(String.Format("servico/ObterBatidasDia/{0}", funcionario.Id))
            //        .Result.Content.ReadAsStringAsync().Result);
            atualizarListaDeBatidasDoDia();
            #endregion

            defineHorariosDoDia();
        }
Esempio n. 7
0
        public virtual E incluir(E entidade)
        {
            Dictionary <String, DbParameter> param = criarParamatros(entidade);
            string campoAutoIncrementado           = obterCampoAutoIncrementado();

            //remove campo autoincrementado
            if (!String.IsNullOrEmpty(campoAutoIncrementado) && param.ContainsKey(campoAutoIncrementado))
            {
                param.Remove(obterCampoAutoIncrementado());
            }

            bool controleInterno = ad.conexaoFechada();

            if (controleInterno)
            {
                ad.abreConexao();
            }

            StringBuilder sql = new StringBuilder("Insert into ");

            sql.Append(obterTabela());
            sql.Append(entidade.instrucaoParaInsert(campoAutoIncrementado));
            try
            {
                if (!String.IsNullOrEmpty(campoAutoIncrementado))
                {
                    sql.Append("select @idRetorno = @@identity");
                    DbParameter idRetorno = ad.criaParametro("idRetorno", DbType.Int32);
                    idRetorno.Direction = ParameterDirection.Output;
                    param.Add("idRetorno", idRetorno);

                    ad.retornaParametros(sql.ToString(), param.Values.ToArray());
                    PropertyInfo pInfo = entidade.GetType().GetProperty(campoAutoIncrementado, new Type[] { });
                    if (pInfo.PropertyType == typeof(Decimal))
                    {
                        pInfo.SetValue(entidade, ConverteUtils.sempreConverteDecimal(idRetorno.Value), null);
                    }
                    else
                    {
                        pInfo.SetValue(entidade, ConverteUtils.sempreConverteInt32(idRetorno.Value), null);
                    }
                }
                else
                {
                    ad.executaComando(sql.ToString(), param.Values.ToArray());
                }
            }
            catch (Exception ex)
            {
                String msg = String.Format("Falha ao tentar incluir registro no banco de dados.\n{0}", ex.Message);
                if (ex.Message.IndexOf("FK_") > -1)
                {
                    msg = String.Format("Falha de integridade referencial na tentativa de incluir o registro.\n{0}", ex.Message);
                }
                if (ex.Message.IndexOf("PK_") > -1 || ex.Message.IndexOf("UK_") > -1)
                {
                    msg = "Registro que está sendo incluído já existe no banco de dados.";
                }
                throw new Exception(msg, ex);
            }

            if (controleInterno)
            {
                ad.fechaConexao();
            }

            return(entidade);
        }