Exemplo n.º 1
0
        /// <summary>
        /// Obtem o tipo da linha selecionada. Gera alertas
        /// </summary>
        /// <param colName="gridView"></param>
        /// <returns></returns>
        public static T ConvertToObject <T>(DataGridView dataGridView) where T : class
        {
            int selectRowsCount = dataGridView.SelectedRows.Count;

            if (IsEmpty(dataGridView))
            {
                MessageIts.Mensagem("Tabela vazia.");
            }

            else if (IsSelectRow(dataGridView) == false)
            {
                MessageIts.Mensagem("Nenhuma linha selecionada");
            }

            else
            {
                try
                {
                    T linha = (dataGridView.SelectedRows[0].DataBoundItem as T);
                    return(linha);
                }
                catch (IndexOutOfRangeException ex)
                {
                    MessageIts.Mensagem("Falha ao obter o objeto do DataGridView" + ex.StackTrace + "\n" + ex.Message);
                }
            }
            return(null);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Escrever os dados do pathFile no tarjetFile
        /// O diretório precisa existir.
        /// O conteúdo será sobreescrito.
        /// </summary>
        /// <param name="tarjetFile"></param>
        /// <param name="pathFile"></param>
        public static bool OverWriteFile(string tarjetFile, string pathFile)
        {
            try
            {
                var data = GetDataFile(tarjetFile);

                if (File.Exists(tarjetFile))
                {
                    File.SetAttributes(tarjetFile, FileAttributes.Normal);
                }

                File.WriteAllLines(tarjetFile, data);

                return(true);
            }
            catch (ArgumentException aex)
            {
                MessageIts.MensagemExcecao(aex, "Falha ao gerar logs");
            }
            catch (IOException exio)
            {
                MessageIts.MensagemExcecao(exio, "Falha ao gerar logs");
            }
            return(false);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Converter um IEnumerable para DataTable
        /// </summary>
        /// <typeparam colName="T"></typeparam>
        /// <param colName="collection"></param>
        /// <returns></returns>
        public static DataTable ConvertToDataTable <T>(IEnumerable <T> collection) where T : new()
        {
            DataTable dataTable = new DataTable();

            try
            {
                Type           impliedType = typeof(T);
                PropertyInfo[] _propInfo   = impliedType.GetProperties();
                foreach (PropertyInfo pi in _propInfo)
                {
                    dataTable.Columns.Add(pi.Name, pi.PropertyType);
                }

                foreach (T item in collection)
                {
                    DataRow newDataRow = dataTable.NewRow();
                    newDataRow.BeginEdit();
                    foreach (PropertyInfo pi in _propInfo)
                    {
                        newDataRow[pi.Name] = pi.GetValue(item, null);
                    }
                    newDataRow.EndEdit();
                    dataTable.Rows.Add(newDataRow);
                }
            }
            catch (Exception ex)
            {
                MessageIts.Mensagem("Falha ao gerar DataTable através da lista\n" + ex.StackTrace + "\n" + ex.Message);
            }
            return(dataTable);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Escreve no arquivo
 /// O arquivo deve existe.
 /// </summary>
 /// <param name="pathFile"></param>Path do arquivo
 /// <param name="lines"></param>Conteúdo a ser adicionado no arquivo
 /// <returns></returns>
 public static bool AppendTextFile(string pathFile, params string[] lines)
 {
     if (lines == null || pathFile == null)
     {
         return(false);
     }
     try
     {
         if (File.Exists(pathFile))
         {
             using (StreamWriter sw = File.AppendText(pathFile))
             {
                 foreach (var text in lines)
                 {
                     //escrever no final do arquivo
                     sw.Write(text + '\n');
                 }
                 sw.Close();
             }
             return(true);
         }
     }
     catch (Exception ex)
     {
         MessageIts.MensagemExcecao(ex, "Arquivo : " + pathFile + "não encontrado!");
     }
     return(false);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Executa procedimentos
        /// </summary>
        /// <param name="querySql"></param>
        /// <returns></returns>
        public bool ExecuteProcedureScalar(string querySql)
        {
            object flag = null;

            //se a conexao foi aberta
            if (OpenConnection())
            {
                try
                {
                    using (this.connection)
                    {
                        //criando o comando
                        PrepareCommand(CommandType.StoredProcedure, querySql);

                        //executa o comando no banco de dados
                        flag = sqlCommand.ExecuteScalar();
                    }
                }
                catch (SqlException ex)
                {
                    MessageIts.MensagemExcecao(ex, "Falha na conexão com o banco de dados");
                }
            }
            return(flag != null);
        }
Exemplo n.º 6
0
 public void Select(string command)
 {
     if (_connectionSql == null)
     {
         MessageIts.Erro("Conexão SQL não foi informada ao DataSetSQl");
     }
     else
     {
         this.Select(command, _connectionSql);
     }
 }
Exemplo n.º 7
0
        /// <summary>
        ///Converte uma lista tipada para um DataTable por reflexão.
        ///
        /// A class POCO não pode conter propriedas de outras classes.
        ///
        /// Exemplo:
        ///     CentroCusto
        ///         string nome;
        ///         ....
        ///         //considerando uma classe com chave estrangeira
        ///         Lancamento lancamento;
        ///          public virtual ICollection<Lancamento> Lancamentos;
        ///     Caso haja o metódo irá falhas
        ///
        /// </summary>
        /// <typeparam colName="T"></typeparam>
        /// <param colName="lista"></param>
        /// <returns></returns>
        public static DataTable ConvertToDataTable <T>(List <T> lista) where T : new()
        {
            if (lista == null)
            {
                MessageIts.Mensagem("Lista não informada na conversão para DataTable");
                return(new DataTable());
            }
            DataTable dataTable = new DataTable(typeof(T).Name);

            try
            {
                //Get all the properties
                PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (PropertyInfo prop in Props)
                {
                    //Setting column names as Property names
                    dataTable.Columns.Add(prop.Name);
                }

                foreach (T item in lista)
                {
                    try
                    {
                        var values = new object[Props.Length];

                        for (int i = 0; i < Props.Length; i++)
                        {
                            //inserting property values to datatable rows
                            values[i] = Props[i].GetValue(item, null);
                        }

                        dataTable.Rows.Add(values);
                    }
                    catch (Exception ex)
                    {
                        MessageIts.Mensagem("Falha na conversão do paramentro da lista em dados\n"
                                            + ex.StackTrace + "\n\n" + ex.Message);

                        throw ex;
                    }
                }
            }
            catch (NullReferenceException ex)
            {
                MessageIts.Mensagem("Falha ao gerar DataTable através da lista\n" + ex.StackTrace + "\n" + ex.Message, "Falha");
            }

            //put first breakpoint here and check datatable
            return(dataTable);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Nome das colunas do DataGridView
        /// </summary>
        /// <param colName="gridView"></param>
        /// <returns></returns>
        public static string[] GetColumnsName(DataGridView gridView)
        {
            int t = gridView.Columns.Count;

            String[] columns = new String[t];
            for (int i = 0; i < t; i++)
            {
                String x = gridView.Columns[i].Name;
                columns[i] = x;

                MessageIts.Mensagem(x);
            }
            return(columns);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Concatenar linhas no arquivo, sem quebra de linha
        /// </summary>
        /// <param name="pathFile"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool AppendText(string pathFile, string text)
        {
            try
            {
                File.AppendAllText(pathFile, text);

                return(true);
            }
            catch (ArgumentException aex)
            {
                MessageIts.MensagemExcecao(aex, "Falha ao concatenar");
            }
            catch (IOException exio)
            {
                MessageIts.MensagemExcecao(exio, "Falha ao concatenar");
            }
            return(false);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Gera um arquivo com os dados da exceção.
        /// O diretório precisa existir.
        /// Caso o arquivo exista o conteúdo é adicionado ao final do arquivo.
        /// Lines são adcionados primeiro
        /// </summary>
        /// <param name="pathFile"></param>
        /// <param name="ex"></param>
        /// <param name="lines"></param>
        /// <returns></returns>
        public static bool AppendTextFileException(string pathFile, Exception ex, string[] lines = null)
        {
            try
            {
                DateTime dataAtual = DateTime.Now;

                //Verifico se o arquivo que desejo abrir existe e passo como parâmetro a respectiva variável
                if (File.Exists(pathFile))
                {
                    //escreve as linhas no arquivo
                    AppendTextFile(pathFile, lines);

                    //Crio um using, dentro dele instancio o StreamWriter, uso a classe File e o método
                    //AppendText para concatenar o texto, passando como parâmetro a variável pathFile
                    using (StreamWriter sw = File.AppendText(pathFile))
                    {
                        var inner = ex.InnerException == null
                            ? "Nenhuma exceção interna"
                            : ex.InnerException.Message + "";

                        //Uso o método Write para escrever o arquivo que será adicionado no arquivo texto
                        sw.Write(
                            "\nMensagem: " + ex.Message + "\n" +
                            "Classe: " + ex.GetType() + "\n" +
                            "Exceção interna: " + inner + "\n" +
                            "Pilha de erros: " + ex.StackTrace + "\n");
                    }
                    return(true);
                }
                else
                {
                    if (CreateFile(pathFile))
                    {
                        return(AppendTextFileException(pathFile, ex, lines));
                    }
                }
            }
            catch (IOException exio)
            {
                MessageIts.Mensagem(exio, "Falha ao gerar logs");
            }
            return(false);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Escreve com quebra de linha
        /// </summary>
        /// <param name="pathFile"></param>
        /// <param name="lines"></param>
        /// <returns></returns>
        public static bool AppendLines(string pathFile, params string[] lines)
        {
            try
            {
                //cria o arquivo se ele nao existir
                File.AppendAllLines(pathFile, lines);

                return(true);
            }
            catch (ArgumentException aex)
            {
                MessageIts.MensagemExcecao(aex, "Falha ao concatenar");
            }
            catch (IOException exio)
            {
                MessageIts.MensagemExcecao(exio, "Falha ao concatenar");
            }
            return(false);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Converte um DataRow em uma em um tipo T
        /// </summary>
        /// <typeparam colName="T"></typeparam>
        /// <param colName="row">Linha da tabela</param>
        /// <param colName="columnsName">Nome das colunas da tabela</param>
        /// <returns></returns>
        public static T ConvertToObject <T>(DataRow row, List <string> columnsName) where T : new()
        {
            T obj = new T();

            try
            {
                string         columnname = "";
                string         value      = "";
                PropertyInfo[] Properties;
                Properties = typeof(T).GetProperties();

                foreach (PropertyInfo objProperty in Properties)
                {
                    columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());

                    if (!string.IsNullOrEmpty(columnname))
                    {
                        value = row[columnname].ToString();

                        if (!string.IsNullOrEmpty(value))
                        {
                            if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                            {
                                value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                            }
                            else
                            {
                                value = row[columnname].ToString().Replace("%", "");
                                objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageIts.MensagemExcecao(ex, "Falha ao gerar objeto tipado pelo DataRow.",
                                           "Falha na conversão do objeto da linha selecionada");
            }
            return(obj);
        }
Exemplo n.º 13
0
 public void Select(string command, SqlConnection connectionSql)
 {
     try
     {
         this._sqlCommand            = new SqlCommand(command, connectionSql);
         _sqlCommand.CommandType     = CommandType.Text;
         this._adapter.SelectCommand = _sqlCommand;
     }
     catch (SqlException sqlex)
     {
         MessageIts.MensagemExcecao(sqlex, "Falha com SQL ao preencher a tabela",
                                    "Falha no comando scriptSql: " + command);
         throw sqlex;
     }
     catch (Exception ex)
     {
         MessageIts.MensagemExcecao(ex, "Falha ao preencher a tabela");
         throw ex;
     }
 }
Exemplo n.º 14
0
        //Inicializa todos os componentes necessarios para o DataSet funcionar
        private void Fill(string command)
        {
            try
            {
                this.Clear();
                this.Select(command);
                this._adapter.Fill(this);

                if (this.Tables.Count > 0)
                {
                    this._dataTable = Tables[0];
                }
                else
                {
                    this._dataTable = new DataTable();
                }

                //aqui eu pego os dados da tabela
                this._bindingSource.DataSource = this._dataTable;

                //aqui eu falo pro bs que ele vai existir no grid
                //atribui o dataset ao DataSource do BindingSource
                _bindingSource.DataSource = this;

                //essa linha fala que eu qro usar o bs pra navegar
                //essa linha tinha sumido nao sei pq
                //atribui o BindingSource ao BindingNavigator
                _bindingSource.DataMember = _dataTable.TableName;
            }
            catch (SqlException sqlex)
            {
                MessageIts.MensagemExcecao(sqlex, "Falha com SQL ao preencher a tabela",
                                           "Falha no comando scriptSql: " + command);
                throw sqlex;
            }
            catch (Exception ex)
            {
                MessageIts.MensagemExcecao(ex, "Falha ao preencher a tabela");
                throw ex;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Executa o comando ou procedimento no banco de dados.
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="querySql"></param>
        /// <param name="sqlParameterCollection"></param>
        /// <returns></returns>Retorna um datatable com as colunas e dados do banco
        public DataTable ExecuteManipulation(CommandType commandType, string querySql, SqlParameterCollection sqlParameterCollection)
        {
            DataTable dataTable = new DataTable();

            //se a conexao foi aberta
            if (OpenConnection())
            {
                try
                {
                    using (this.connection)
                    {
                        PrepareCommand(commandType, querySql);

                        if (sqlParameterCollection != null)
                        {
                            //add o parametro no comando
                            foreach (SqlParameter paramentro in sqlParameterCollection)
                            {
                                //sqlCommand.Parameters.Add(new SqlParameter("@parameterName", value));
                                this.sqlCommand.Parameters.Add(new SqlParameter(paramentro.ParameterName, paramentro.Value));
                            }
                        }
                        //adaptador para tabela
                        SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand);

                        //indexa o dataTable
                        adapter.Fill(dataTable);
                    }
                }
                catch (SqlException ex)
                {
                    MessageIts.MensagemExcecao(ex, "Falha na conexão com o banco de dados");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return(dataTable);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Gera um arquivo com os dados do vetor de string.
        /// O diretório precisa existir.
        /// O conteúdo será sobreescrito.
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="lines"></param>
        public static bool OverWriteOnFile(string pathFile, List <string> lines)
        {
            try
            {
                if (File.Exists(pathFile))
                {
                    //permissao total
                    File.SetAttributes(pathFile, FileAttributes.Normal);
                }

                File.WriteAllLines(pathFile, lines);
                return(true);
            }
            catch (ArgumentException aex)
            {
                MessageIts.MensagemExcecao(aex, "Falha ao gerar logs");
            }
            catch (IOException exio)
            {
                MessageIts.MensagemExcecao(exio, "Falha ao gerar logs");
            }
            return(false);
        }