Ejemplo n.º 1
0
 public static void compactaArquivo(String diretorioCompactar, String diretorioSaida, String dsComentario, String nomeArquivoCompactado, String dsPassword, Boolean criaPasta = true)
 {
     /*
      * http://grapevine.dyndns-ip.com/download/authentec/download/dotnetzip/examples.htm
      * compactaArquivo(1, 2, 3, 4, 5, 6);
      * 1 - Local do arquivo compactado
      * 2 - Local que será usado para salvar o arquivo compactado
      * 3 - Comentário do arquivo compactado, se não desejar informar passar vazio ""
      * 4 - Nome do arquivo compactado
      * 5 - Senha para a compactação
      * 6 - Se estiver como true ou vazio irá compactar a pasta, se estiver como false irá compactar os arquivos que estão dentro da pasta
      */
     try
     {
         using (ZipFile zip = new ZipFile())
         {
             if (!dsPassword.Equals(""))
             {
                 zip.Password   = dsPassword;
                 zip.Encryption = EncryptionAlgorithm.WinZipAes256;
             }
             if (criaPasta)
             {
                 /*
                  * No arquivo zip, a pasta que irá apacer será do diretório localizado
                  * Exemplo: Users\Allan\Desktop\TransmissorNovo
                  * Se passar algum parametro terá o nome da pasta
                  * Exemplo: zip.AddFile(nomearquivo, "NomeDaPasta");
                  * se deixar zip.AddFile(nomearquivo, ""); não irá pegar o diretório que está sendo compactado
                  */
                 String[] nomeArquivos = Directory.GetFiles(diretorioCompactar);
                 //Irá compactar somente os arquivos do diretório, não levando em consideração as subpastas existentes no diretório
                 foreach (String nomearquivo in nomeArquivos)
                 {
                     zip.AddFile(nomearquivo);
                 }
             }
             else
             {
                 //Compacta os arquivos e as pastas e subpastas existentes no diretório
                 zip.AddDirectory(diretorioCompactar, "");
             }
             zip.Comment = String.Format("{0} {1:G}", Valida.removeAcentos(dsComentario), DateTime.Now);
             zip.Save(String.Format("{0}\\{1}.zip", diretorioSaida, nomeArquivoCompactado));
             zip.Dispose();
         }
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro ao compactar o arquivos do diretorio {0} \n", diretorioCompactar) + erro.Message);
     }
 }
Ejemplo n.º 2
0
 public static void getGrid <T>(List <T> dados, GridControl grid, String msg)
 {
     try
     {
         grid.DataSource = null;
         grid.DataSource = dados;
         grid.Refresh();
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro ao carregar dados {0}. \n Erro: {1} - {2}", msg, erro.Message, erro.Source));
     }
 }
Ejemplo n.º 3
0
 public static void buildReport(string itablename, string vsql, Report report)
 {
     try
     {
         DataTable tab = createDataTableFromSQL(itablename, vsql);
         report.RegisterData(tab, itablename);
         report.GetDataSource(itablename).Enabled = true;
     }
     catch (Exception erro)
     {
         Alert.erro("Erro ao gerar o relatorio \n" + erro.Message);
     }
 }
Ejemplo n.º 4
0
 public static void criaArquivo(String dsNome, String dsExtensao, String dsDiretorio)
 {
     try
     {
         String       path = getLocalArquivo(dsNome, dsExtensao, dsDiretorio);
         StreamWriter x    = File.CreateText(path);
         x.Close();
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro ao gerar no arquivo ({0}).\n{1}", dsNome, erro.Message));
     }
 }
Ejemplo n.º 5
0
        public static String loadWord(string irelatorioname)
        {
            String report = "";

            try
            {
                report = String.Format("{0}\\Relatorios\\{1}", Ficheiro.getLocalExecutavel(), irelatorioname);
            }
            catch (Exception ex)
            {
                Alert.erro(String.Format("Erro ao acessar o arquivo do Word {0} \n", irelatorioname, ex.Message));
            }
            return(report);
        }
Ejemplo n.º 6
0
        public static Report loadReport(string irelatorioname)
        {
            Report report = new Report();

            try
            {
                report.Load(String.Format("{0}\\Relatorios\\{1}", Ficheiro.getLocalExecutavel(), irelatorioname));
            }
            catch (Exception ex)
            {
                Alert.erro("Erro ao gerar o relatorio \n" + ex.Message);
            }
            return(report);
        }
Ejemplo n.º 7
0
 public static void editaTexto(String vlArquivoReplace, String vlRemover, String vlSubstituir)
 {
     try
     {
         //https://social.msdn.microsoft.com/Forums/pt-BR/449d8246-49b5-46e6-9968-f7c92777739f/alterar-arquivo-de-texto-txt-c?forum=vscsharppt
         string conteudoTxt     = File.ReadAllText(vlArquivoReplace);
         string novoConteudoTxt = conteudoTxt.Replace(vlRemover, vlSubstituir);
         File.WriteAllText(vlArquivoReplace, novoConteudoTxt);
     }
     catch (Exception erro)
     {
         Alert.erro("Erro ao alterar arquivo\n" + erro.Message);
     }
 }
Ejemplo n.º 8
0
 public static void escreveArquivo(String dsTexto, String dsNome, String dsExtensao, String dsDiretorio)
 {
     try
     {
         String       path = getLocalArquivo(dsNome, dsExtensao, dsDiretorio);
         StreamWriter sw   = File.AppendText(path);
         sw.WriteLine(dsTexto);
         sw.Close();
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro ao escrever no arquivo de log ({0}).\n{1}", dsNome, erro.Message));
     }
 }
Ejemplo n.º 9
0
        public static String retornaDiretorio(String diretorio)
        {
            String retorno = "";

            try
            {
                FileInfo TheFile = new FileInfo(diretorio);
                retorno = TheFile.DirectoryName;
            }
            catch (Exception erro)
            {
                Alert.erro("Erro ao verificar Diretório " + erro.Message);
            }
            return(retorno);
        }
Ejemplo n.º 10
0
 public static void abreArquivo(String dsDiretorio)
 {
     try
     {
         System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo()
         {
             FileName = dsDiretorio
         };
         System.Diagnostics.Process.Start(startInfo);
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro abrir o arquivo localizado {0}!\n {1}", dsDiretorio, erro.Message));
     }
 }
Ejemplo n.º 11
0
 public static void grid_remove(DevExpress.XtraGrid.Views.Grid.GridView gvGrid)
 {
     try
     {
         int[] aList = gvGrid.GetSelectedRows();
         for (int i = 0; i < aList.Length; i++)
         {
             gvGrid.DeleteSelectedRows();
         }
     }
     catch (Exception erro)
     {
         Alert.erro("Erro ao realizar a remoção \n " + erro.Message);
     }
 }
Ejemplo n.º 12
0
 public static void removeArquivos(String formatoAquivo, String local)
 {
     try
     {
         criaDiretorio(local);
         string[] arquivos = Directory.GetFiles(getLocalExecutavel() + local, formatoAquivo, SearchOption.AllDirectories);
         foreach (var arq in arquivos)
         {
             File.Delete(arq);
         }
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro ao realizar a remoção dos arquivos com a extensão: {0}\n{1}", formatoAquivo, erro.Message));
     }
 }
Ejemplo n.º 13
0
        private void dsFiltroChanged(object sender, EventArgs e)
        {
            try
            {
                string expressao   = "";
                string dsOrdenacao = "";
                for (int i = 0; i < tbDadosLista.Columns.Count; i++)
                {
                    string tipo = tbDadosLista.Columns[i].DataType.ToString();
                    if (tbDadosLista.Columns[i].DataType.ToString().Equals("System.Int32"))
                    {
                        try
                        {
                            Int32 nrExpressao = Convert.ToInt32((sender as Control).Text);
                            expressao   = String.Format("{0} {1} = {2} or ", expressao, tbDadosLista.Columns[i].ColumnName, nrExpressao);
                            dsOrdenacao = String.Format("{0} {1},", dsOrdenacao, tbDadosLista.Columns[i].ColumnName);
                        }
                        catch { }
                    }
                    if (tbDadosLista.Columns[i].DataType.ToString().Equals("System.String"))
                    {
                        expressao   = String.Format("{0} {1} like '%{2}%' or ", expressao, tbDadosLista.Columns[i].ColumnName, (sender as Control).Text);
                        dsOrdenacao = String.Format("{0} {1},", dsOrdenacao, tbDadosLista.Columns[i].ColumnName);
                    }
                }

                expressao   = expressao.Substring(0, expressao.Length - 3);
                dsOrdenacao = dsOrdenacao.Substring(0, dsOrdenacao.Length - 1);

                DataTable dt = new DataTable();
                dt = tbDadosLista.Clone();
                DataRow[] drResults = tbDadosLista.Select(expressao, dsOrdenacao);

                foreach (DataRow dr in drResults)
                {
                    object[] row = dr.ItemArray;
                    dt.Rows.Add(row);
                }

                tbDadosFiltro       = dt;
                ctrlGrid.DataSource = tbDadosFiltro;
            }
            catch (Exception erro)
            {
                Alert.erro(erro.Message);
            }
        }
Ejemplo n.º 14
0
        public void Conectar()
        {
            try
            {
                if (BancoDados == null)
                {
                    BancoDados = new NpgsqlConnection();
                }

                if ((StaticVariables.dbName != null) && (BancoDados.State == ConnectionState.Closed) || (BancoDados.State == ConnectionState.Broken))
                {
                    BancoDados.ConnectionString =
                        String.Format("Server= {0};Port={1};User Id={2};Password={3};Database={4};CommandTimeout=1800000;Pooling=false;Timeout=1024;",
                                      StaticVariables.ServerName, StaticVariables.nrPorta, StaticVariables.nmUser, StaticVariables.snUser, StaticVariables.dbName);

                    if (!StaticVariables.RemoteServerName.Equals(""))
                    {
                        try
                        {
                            BancoDados.Open();
                        }
                        catch (Exception erro)
                        {
                            Alert.erro("Conexao: " + erro.Message);
                            Application.Exit();
                        }
                    }
                    else
                    {
                        try
                        {
                            BancoDados.Open();
                        }
                        catch (Exception erro)
                        {
                            Alert.erro("Erro ao Conectar ao Banco de dados: " + erro.Message);
                        }
                    }
                }
            }
            catch (Exception erro)
            {
                Alert.erro("Erro ao conectar ao banco de dados: " + erro.Message);
                Application.Exit();
            }
        }
Ejemplo n.º 15
0
        public static void preencheArquivoWord(String caminhoArquivo, String dsNomeArquivo, String[] dsFindText, String[] dsReplaceWith, Boolean abreVisualizao = false)
        {
            //Somente irá funcionar se o pacote office estiver instalado no computador
            try
            {
                #region 'Inicio'
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application oApp = new Microsoft.Office.Interop.Word.Application();
                object template = caminhoArquivo;
                Microsoft.Office.Interop.Word.Document oDoc = oApp.Documents.Add(ref template, ref missing, ref missing, ref missing);

                //Troca o conteúdo de alguns tags
                Microsoft.Office.Interop.Word.Range oRng = oDoc.Range(ref missing, ref missing);
                object MatchWholeWord = true;
                object Forward        = false;
                object replace        = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                #endregion

                for (int i = 0; i < dsFindText.Length; i++)
                {
                    object FindText    = dsFindText[i];
                    object ReplaceWith = dsReplaceWith[i];

                    oRng.Find.Execute(ref FindText, ref missing, ref MatchWholeWord,
                                      ref missing, ref missing, ref missing, ref Forward,
                                      ref missing, ref missing, ref ReplaceWith, ref replace,
                                      ref missing, ref missing, ref missing, ref missing);
                }

                #region 'Final'
                oApp.Visible = abreVisualizao;
                oDoc.SaveAs2(String.Format("{0}\\{1}", retornaDiretorio(caminhoArquivo), dsNomeArquivo));
                if (abreVisualizao == false)
                {
                    Alert.informacao("Arquivo Exportado.");
                    oDoc.Close();
                    oApp.Quit();
                }
                #endregion
            }
            catch (Exception erro)
            {
                Alert.erro("Erro ao preencher arquivo do Word" + erro.Message);
            }
        }
Ejemplo n.º 16
0
        public static Boolean verificaExistenciaDiretorio(String dsDiretorio)
        {
            //if (Ficheiro.verificaExistenciaDiretorio("\\Log\\teste"))
            Boolean path = true;

            try
            {
                if (!Directory.Exists(dsDiretorio))
                {
                    path = false;
                }
            }
            catch (Exception erro)
            {
                Alert.erro("Erro ao verificar a existência diretório \n" + erro.Message);
            }
            return(path);
        }
Ejemplo n.º 17
0
        public static void execSQLWithTransaction(NpgsqlConnection db, NpgsqlTransaction transacao, String sql)
        {
            NpgsqlCommand cmd = new NpgsqlCommand(sql.Trim(), db)
            {
                Transaction = transacao
            };

            try
            {
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            catch (Exception erro)
            {
                cmd.Dispose();
                Alert.erro(String.Format("Erro ao executar script: {0}", erro.Message));
            }
        }
Ejemplo n.º 18
0
        public static String selecionaDiretorio()
        {
            String diretorio = "";

            try
            {
                FolderBrowserDialog dirDialog = new FolderBrowserDialog();
                DialogResult        res       = dirDialog.ShowDialog();
                if (res == DialogResult.OK)
                {
                    diretorio = dirDialog.SelectedPath;
                }
            }
            catch (Exception erro)
            {
                Alert.erro(String.Format("Erro ao abrir diretorio ({0}).\n{1}", diretorio, erro.Message));
            }
            return(diretorio);
        }
Ejemplo n.º 19
0
 internal static void abreTelaRapida(String cdUsuario)
 {
     try
     {
         String vSql = String.Format(" select nm_form from usuario " +
                                     " inner join programa on programa.cd_programa = usuario.cd_programa and " +
                                     " programa.cd_modulo = usuario.cd_modulo " +
                                     " where cd_usuario = '{0}'", cdUsuario);
         Object[] result = Utilidades.consultar(vSql);
         if (result != null)
         {
             ((DevExpress.XtraEditors.XtraForm)Activator.CreateInstance(Type.GetType(Convert.ToString(result[0])))).ShowDialog();
         }
     }
     catch (Exception erro)
     {
         Alert.erro("Erro ao abrir tela Rápida \n" + erro.Message);
     }
 }
Ejemplo n.º 20
0
 internal static void filtraGridView(DevExpress.XtraGrid.Views.Grid.GridView @gridview, String expressao)
 {
     /*private void txtFiltraGrid_TextChanged(object sender, EventArgs e)
      *  {
      *      Utilidades.filtraGridView(gvGrid, txtFiltraGrid.Text);
      *  }
      */
     try
     {
         gridview.ActiveFilterEnabled = true;
         String vfiltro = "";
         if (expressao.Trim().Length > 0)
         {
             String[] vdados = expressao.Split(' ');
             foreach (DevExpress.XtraGrid.Columns.GridColumn gcc in gridview.Columns)
             {
                 if (vfiltro.Trim().Length > 0)
                 {
                     vfiltro += " OR ";
                 }
                 vfiltro += "(";
                 for (int i = 0; i < vdados.Length; i++)
                 {
                     if (i > 0)
                     {
                         vfiltro += " AND ";
                     }
                     vfiltro += String.Format("[{0}] LIKE '%{1}%'", gcc.FieldName, vdados[i]);
                 }
                 vfiltro += ")";
             }
             gridview.ActiveFilterString = vfiltro;
         }
         else
         {
             gridview.ActiveFilterString = "";
         }
     }
     catch (Exception erro)
     {
         Alert.erro(erro.Message);
     }
 }
Ejemplo n.º 21
0
        public static String getLocalArquivo(String dsNome, String dsExtensao, String dsDiretorio)
        {
            String path = "";

            try
            {
                if (!dsDiretorio.Equals(""))
                {
                    path = String.Format(getLocalExecutavel() + "\\{5}\\{0}_{1}.{2}.{3}.{4}", dsNome, DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year, dsExtensao, dsDiretorio);
                }
                else
                {
                    path = String.Format(getLocalExecutavel() + "\\{0}_{1}.{2}.{3}.{4}", dsNome, DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year, dsExtensao);
                }
            }
            catch (Exception erro)
            {
                Alert.erro(String.Format("Erro ao localizar o arquivo: {0}", dsNome + dsExtensao, erro.Message));
            }
            return(path);
        }
Ejemplo n.º 22
0
 public static String exportaRelPDF(String localExportacao, String nomeArquivo, Report relatorio)
 {
     /*
      * Utilidades.exportaRelPDF(1, 2, relatorio);
      * 1 - Local que será salvo o arquivo gerado em pdf
      * 2 - Nome do arquivo. A descrição irá ficar dessa forma Teste_06112019112927.pdf
      */
     try
     {
         /*Removido, a opção de replace, pois não havia necessidade de usar. - Allan 15-04-2020
          * nomeArquivo += "_" + DateTime.Now.ToString().Replace(":", "").Replace("/", "").Replace(" ", "");
          */
         PDFExport export = new PDFExport();
         relatorio.Export(export, String.Format(@"{0}\{1}.pdf", localExportacao, nomeArquivo));
     }
     catch (Exception erro)
     {
         Alert.erro("Erro ao exportar arquivo PDF \n" + erro.Message);
     }
     return(String.Format(@"{0}\{1}.pdf", localExportacao, nomeArquivo));
 }
Ejemplo n.º 23
0
 private void dsFiltroEnter(object sender, KeyEventArgs e)
 {
     try
     {
         if (e.KeyValue == 13)
         {
             ArrayList rows = new ArrayList();
             for (int i = 0; i < gridLst.SelectedRowsCount; i++)
             {
                 if (gridLst.GetSelectedRows()[i] >= 0)
                 {
                     rows.Add(gridLst.GetDataRow(gridLst.GetSelectedRows()[i]));
                 }
             }
             objRetorno = rows;
             frmLista.Close();
         }
     }
     catch (Exception erro)
     {
         Alert.erro(erro.Message);
     }
 }
Ejemplo n.º 24
0
 public static void descompactaArquivo(String diretorioDescompactar, String diretorioSaida, String dsPassword)
 {
     /*
      * descompactaArquivo(1, 2, 3);
      * 1 - Local do arquivo compactado
      * 2 - Local que será descompactado o arquivo
      * 3 - Senha do arquivo, se não existir passar vazio ""
      */
     try
     {
         using (var zip = new ZipFile(diretorioDescompactar))
         {
             Directory.CreateDirectory(diretorioSaida);
             zip.Password = dsPassword;
             zip.ExtractAll(diretorioSaida, ExtractExistingFileAction.OverwriteSilently);
             zip.Dispose();
         }
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro ao Descompactar o diretorio {0} \n", diretorioDescompactar) + erro.Message);
     }
 }
Ejemplo n.º 25
0
 /** retorna um vetor onde cada elemento é uma coluna da SQL
  *  portanto, a SQL deve retornar apenas uma linha */
 public static Object[] consultar(NpgsqlConnection conn, String sql)
 {
     Object[] retorno = null;
     try
     {
         NpgsqlDataReader comm = new NpgsqlCommand(sql, conn).ExecuteReader();
         while (comm.Read())
         {
             retorno = new Object[comm.FieldCount];
             for (int i = 0; i < comm.FieldCount; i++)
             {
                 retorno[i] = !comm.IsDBNull(i) ? comm.GetValue(i) : null;
             }
         }
         comm.Close();
         comm.Dispose();
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("(Erro-Consultar) :(sql = {0}){1}", sql, erro.Message));
     }
     return(retorno);
 }
Ejemplo n.º 26
0
        public static void exportaRelPDF1(String nomeArquivo, String tituloPdf, Report relatorio)
        {
            try
            {
                relatorio.Prepare();
                PDFExport pdfExport = new PDFExport();
                relatorio.PrintSettings.ShowDialog = false;
                pdfExport.ShowProgress             = false;
                //                pdfExport.Subject = "NobreSistemas";
                pdfExport.Title          = tituloPdf;
                pdfExport.Compressed     = true;
                pdfExport.AllowPrint     = true;
                pdfExport.EmbeddingFonts = true;
                MemoryStream strm = new MemoryStream();
                relatorio.Export(pdfExport, strm);

                SaveFileDialog salvarPDF = new SaveFileDialog();
                salvarPDF.Filter   = "Arquivos PDF|*.pdf";
                salvarPDF.Title    = "Salvar Arquivo em PDF";
                salvarPDF.FileName = nomeArquivo;//Irá trazer o nome do arquivo preenchido
                salvarPDF.ShowDialog();

                FileStream arquivoPDF = new FileStream(salvarPDF.FileName, FileMode.Create, FileAccess.Write);
                strm.WriteTo(arquivoPDF);

                Alert.informacao("Arquivo Salvo com Sucesso!");

                arquivoPDF.Close();
                relatorio.Dispose();
                pdfExport.Dispose();
                strm.Position = 0;
            }
            catch (Exception erro)
            {
                Alert.erro("Erro ao exportar arquivo PDF \n" + erro.Message);
            }
        }
Ejemplo n.º 27
0
        public List <List <Object> > toList(String isql, List <ParametroPGSQL> parametros)
        {
            List <List <Object> > retorno = null;

            try
            {
                NpgsqlCommand comando = getConnection().CreateCommand();
                comando.CommandText = isql;
                foreach (ParametroPGSQL p in parametros)
                {
                    comando.Parameters.Add(new NpgsqlParameter(p.nome, p.valor));
                }

                NpgsqlDataReader ireader = comando.ExecuteReader();
                if (ireader.HasRows)
                {
                    retorno = new List <List <object> >();
                    while (ireader.Read())
                    {
                        List <Object> colunas = new List <object>();
                        for (int i = 0; i < ireader.FieldCount; i++)
                        {
                            colunas.Add(!ireader.IsDBNull(i) ? ireader.GetValue(i) : null);
                        }
                        retorno.Add(colunas);
                    }
                }
                ireader.Close();
                ireader.Dispose();
            }
            catch (Exception erro)
            {
                Alert.erro("(Erro-Listar) :" + erro.Message);
            }
            return(retorno);
        }
Ejemplo n.º 28
0
        public static void ConexaoDB()
        {
            if (dbase == null)
            {
                dbase = new NpgsqlConnection();
            }
            bool reconecta = false;

            if (dbase.State == ConnectionState.Broken)
            {
                reconecta = true;
            }
            if (dbase.State == ConnectionState.Closed)
            {
                reconecta = true;
            }
            if (reconecta)
            {
                try
                {
                    if (dbase == null)
                    {
                        dbase = new NpgsqlConnection();
                    }

                    if ((dbName != null) && (dbase.State == ConnectionState.Closed))
                    {
                        dbase.ConnectionString =
                            "Server= " + ServerName +
                            ";Port=" + StaticVariables.nrPorta +
                            ";User Id=" + StaticVariables.nmUser +
                            "; Password="******";Database=" + dbName + ";CommandTimeout=1800000;Timeout=1024;Preload Reader=true;";

                        if (!StaticVariables.RemoteServerName.Equals(""))
                        {
                            try
                            {
                                dbase.Open();
                            }
                            catch
                            {
                                dbase.ConnectionString =
                                    "Server= " + StaticVariables.RemoteServerName +
                                    ";Port=" + StaticVariables.nrPorta +
                                    ";User Id=" + StaticVariables.nmUser +
                                    "; Password="******"; Database=" + dbName + ";CommandTimeout=1800000;Timeout=1024;Preload Reader=true;";
                                try
                                {
                                    dbase.Open();
                                }
                                catch (Exception erro)
                                {
                                    Alert.erro("Erro ao conectar ao banco de dados: " + erro.Message);
                                    Application.Exit();
                                }
                            }
                        }
                        else
                        {
                            dbase.Open();
                        }
                    }
                }
                catch (Exception erro)
                {
                    Alert.erro("Erro ao conectar ao banco de dados: " + erro.Message);
                    Application.Exit();
                }
            }
        }
Ejemplo n.º 29
0
        public ArrayList ListaValores(Int32 inrLista, String idsWhere, Boolean multiselecao, String idsnovocabecalho = "")
        {
            MultiSelecao = multiselecao;

            frmLista = new DevExpress.XtraEditors.XtraForm();
            Int32  iHeight      = 0;
            Int32  iWidth       = 0;
            String isqlConsulta = "";

            try
            {
                tbDadosLista = new DataTable("dadosLista");

                if (Conexao.getInstance().getConnection().State == ConnectionState.Open)
                {
                    Object[] consulta = Utilidades.consultar(String.Format(" select ds_titulo,nr_altura,nr_largura,ds_instrucaosql from listavalores where nr_sequencial = {0}", inrLista));
                    if (consulta != null)
                    {
                        if (Convert.ToInt32(consulta[1]) > 0)
                        {
                            iHeight = Convert.ToInt32(consulta[1]);
                        }
                        if (Convert.ToInt32(consulta[2]) > 0)
                        {
                            iWidth = Convert.ToInt32(consulta[2]);
                        }
                        // se foi passado um novo cabeçalho, usa o que o usuário passou
                        if (idsnovocabecalho.Trim().Length > 0)
                        {
                            frmLista.Text = idsnovocabecalho;
                        }
                        else
                        {
                            frmLista.Text = String.Format("({0}) - {1}", inrLista, Convert.ToString(consulta[0]));
                        }
                        isqlConsulta = Convert.ToString(consulta[3]);
                    }

                    if (!isqlConsulta.Equals(""))
                    {
                        isqlConsulta = isqlConsulta.Replace(":pDsWhere", idsWhere);
                        NpgsqlCommand     cmd     = new NpgsqlCommand(isqlConsulta, Conexao.getInstance().getConnection());
                        NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(cmd);
                        adapter.Fill(tbDadosLista);

                        if (multiselecao)
                        {
                            tbDadosLista.Columns.Add("X", typeof(String)).SetOrdinal(0);
                        }
                    }
                }
                objRetorno               = new ArrayList();
                frmLista.ClientSize      = new Size(iWidth, iHeight + 10);
                frmLista.Font            = new Font("Tahoma", 9, FontStyle.Bold);
                frmLista.WindowState     = FormWindowState.Normal;
                frmLista.FormBorderStyle = FormBorderStyle.FixedSingle;
                frmLista.StartPosition   = FormStartPosition.CenterParent;
                frmLista.KeyPreview      = true;
                frmLista.MaximizeBox     = false;
                frmLista.MinimizeBox     = false;
                frmLista.ShowInTaskbar   = false;
                frmLista.ShowIcon        = false;
                frmLista.TopMost         = true;

                //Tamnho da Tela
                //frmLista.Size = new Size(700, 700);

                ctrlGrid = new DevExpress.XtraGrid.GridControl();
                gridLst  = new DevExpress.XtraGrid.Views.Grid.GridView();

                ctrlGrid.Name       = "ctrlGrid";
                ctrlGrid.MainView   = gridLst;
                gridLst.Name        = "Grid";
                gridLst.GridControl = ctrlGrid;

                ctrlGrid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { gridLst });
                ctrlGrid.SetBounds(10, 60, iWidth - 20, iHeight - 85);
                ctrlGrid.DataSource     = tbDadosLista;
                ctrlGrid.BindingContext = new BindingContext();
                ctrlGrid.ForceInitialize();
                gridLst.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
                gridLst.OptionsView.ColumnAutoWidth     = false;

                List <List <Object> > colunas = Conexao.getInstance().toList(
                    " select nr_coluna,ds_titulocoluna,nm_campoinstrsql,nr_larguracampo,ds_alinhamentocampo " +
                    "   from listavalorescolunas " +
                    "  where nr_sequencial = " + inrLista);
                if (colunas != null)
                {
                    if (multiselecao)
                    {
                        RepositoryItemCheckEdit selectdp = new RepositoryItemCheckEdit();
                        gridLst.Columns[0].ColumnEdit = selectdp;
                        selectdp.NullText             = "N";
                        selectdp.ValueChecked         = "S";
                        selectdp.ValueUnchecked       = "N";
                        selectdp.ValueGrayed          = "N";

                        gridLst.Columns[0].Width = 25;
                        gridLst.Columns[0].AppearanceCell.TextOptions.HAlignment   = DevExpress.Utils.HorzAlignment.Center;
                        gridLst.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                        //gridLst.Columns[0].AppearanceHeader.Font = new Font("Tahoma", 9, FontStyle.Bold);
                        gridLst.Columns[0].Caption = "";
                    }

                    foreach (List <Object> col in colunas)
                    {
                        Int32 nrColuna = multiselecao ? Convert.ToInt32(col.ElementAt(0)) + 1 : Convert.ToInt32(col.ElementAt(0));
                        gridLst.Columns[nrColuna - 1].Width = Convert.ToInt32(col.ElementAt(3));
                        gridLst.Columns[nrColuna - 1].OptionsColumn.AllowEdit = false;
                        gridLst.Columns[nrColuna - 1].OptionsColumn.ReadOnly  = true;
                        gridLst.Columns[nrColuna - 1].Caption = Convert.ToString(col.ElementAt(1));

                        if ((col.ElementAt(4) != null ? col.ElementAt(4).ToString() : "Centralizado") == "Direita")
                        {
                            gridLst.Columns[nrColuna - 1].AppearanceCell.TextOptions.HAlignment   = DevExpress.Utils.HorzAlignment.Far;
                            gridLst.Columns[nrColuna - 1].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
                            gridLst.Columns[nrColuna - 1].AppearanceHeader.Font = new Font("Tahoma", 9, FontStyle.Bold);
                        }
                        if ((col.ElementAt(4) != null ? col.ElementAt(4).ToString() : "Centralizado") == "Esquerda")
                        {
                            gridLst.Columns[nrColuna - 1].AppearanceCell.TextOptions.HAlignment   = DevExpress.Utils.HorzAlignment.Near;
                            gridLst.Columns[nrColuna - 1].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
                            gridLst.Columns[nrColuna - 1].AppearanceHeader.Font = new Font("Tahoma", 9, FontStyle.Bold);
                        }
                        if ((col.ElementAt(4) != null ? col.ElementAt(4).ToString() : "Centralizado") == "Centralizado")
                        {
                            gridLst.Columns[nrColuna - 1].AppearanceCell.TextOptions.HAlignment   = DevExpress.Utils.HorzAlignment.Center;
                            gridLst.Columns[nrColuna - 1].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                            gridLst.Columns[nrColuna - 1].AppearanceHeader.Font = new Font("Tahoma", 9, FontStyle.Bold);
                        }
                    }
                }

                gridLst.GroupPanelText               = "Arraste o Título das Colunas para Agrupar.";
                gridLst.Appearance.GroupPanel.Font   = new Font("Tahoma", 9, FontStyle.Bold);
                gridLst.OptionsSelection.MultiSelect = multiselecao;

                gridLst.GroupPanelText               = "Arraste o Título das Colunas para Agrupar.";
                gridLst.Appearance.GroupPanel.Font   = new Font("Tahoma", 9, FontStyle.Bold);
                gridLst.OptionsSelection.MultiSelect = multiselecao;

                LabelControl lbFiltro    = new LabelControl();
                LabelControl lbInfo      = new LabelControl();
                TextEdit     txtdsFiltro = new TextEdit();

                lbFiltro.Text = "Filtro:";
                lbFiltro.Font = new Font("Tahoma", 9, FontStyle.Bold);
                lbFiltro.SetBounds(7, 23, 50, 15);


                lbInfo.Font = new Font("Tahoma", 9, FontStyle.Bold);
                lbInfo.Text = "Duplo Clique no Registro para Confirmar a Seleção";
                lbInfo.SetBounds(10, iHeight - 15, 350, 13);

                txtdsFiltro.Font = new Font("Tahoma", 9, FontStyle.Regular);
                txtdsFiltro.SetBounds(60, 20, 300, 20);
                txtdsFiltro.Properties.CharacterCasing = CharacterCasing.Upper;
                txtdsFiltro.TabIndex     = 0;
                txtdsFiltro.TextChanged += new EventHandler(dsFiltroChanged);
                txtdsFiltro.KeyDown     += new KeyEventHandler(dsFiltroEnter);

                ctrlGrid.TabIndex = 1;
                ctrlGrid.KeyDown += new KeyEventHandler(dsFiltroEnter);
                if (!multiselecao)
                {
                    ctrlGrid.DoubleClick += new EventHandler(SelecionaRegistro);
                }
                frmLista.KeyDown += new KeyEventHandler(Escape);

                SimpleButton btnConfirmar = new SimpleButton();
                btnConfirmar.SetBounds(iWidth - 110, iHeight - 20, 100, 25);
                btnConfirmar.Text   = "Confirmar";
                btnConfirmar.Font   = new Font(btnConfirmar.Font, FontStyle.Bold);
                btnConfirmar.Font   = new Font("Tahoma", 9, FontStyle.Bold);
                btnConfirmar.Click += new EventHandler(SelecionaRegistro);
                btnConfirmar.Image  = Properties.Resources.Apply_16x16;

                //Desabilita a opção de agrupamento
                gridLst.OptionsView.ShowGroupPanel = false;
                frmLista.Controls.AddRange(new Control[] { ctrlGrid, lbFiltro, txtdsFiltro, lbInfo, btnConfirmar });

                frmLista.ShowDialog();
                frmLista.BringToFront();
            }
            catch (Exception erro)
            {
                Alert.erro("Erro: " + erro.Message);
            }

            return(objRetorno);
        }
Ejemplo n.º 30
0
        internal static void loadXml()
        {
            try
            {
                bool terminar = false;
                if (File.Exists("./config.xml"))
                {
                    #region ' Carrega os dados do Arquivo de Configuração '
                    XmlDocument readerFile = new XmlDocument();
                    FileStream  fs         = new FileStream("./config.xml", FileMode.Open, FileAccess.Read);
                    readerFile.Load(fs);
                    List <Config> Configs  = new List <Config>();
                    XmlNodeList   conNodes = readerFile.GetElementsByTagName("connections");
                    foreach (XmlNode node in conNodes)
                    {
                        Config configuracao = new Config();
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            if (node.ChildNodes[i].Name == "server")
                            {
                                configuracao.EnderecoDB = node.ChildNodes[i].InnerText;
                            }
                            if (node.ChildNodes[i].Name == "dbName")
                            {
                                configuracao.dbName = node.ChildNodes[i].InnerText;
                            }
                            if (node.ChildNodes[i].Name == "nmUsuario")
                            {
                                configuracao.nmUser = Utilidades.Decryption(node.ChildNodes[i].InnerText, StaticVariables.keypass);
                            }
                            if (node.ChildNodes[i].Name == "snUsuario")
                            {
                                configuracao.snUser = Utilidades.Decryption(node.ChildNodes[i].InnerText, StaticVariables.keypass);
                            }
                            if (node.ChildNodes[i].Name == "tpUser")
                            {
                                configuracao.tpUser = node.ChildNodes[i].InnerText;
                            }
                            if (node.ChildNodes[i].Name == "nrPorta")
                            {
                                configuracao.nrPorta = Convert.ToInt32(node.ChildNodes[i].InnerText);
                            }
                            if (node.ChildNodes[i].Name == "nmSkin")
                            {
                                configuracao.nmSkin = node.ChildNodes[i].InnerText;
                            }
                            if (node.ChildNodes[i].Name == "imagemFundo")
                            {
                                configuracao.imagemFundo = node.ChildNodes[i].InnerText;
                            }
                        }
                        Configs.Add(configuracao);
                        configuracao = null;
                    }
                    #endregion
                    fs.Dispose();

                    StaticVariables.Configs = Configs;

                    if (StaticVariables.Configs != null)
                    {
                        if (StaticVariables.Configs.Count > 1)
                        {
                            if (terminar)
                            {
                                Process.GetCurrentProcess().Kill();
                            }
                        }
                        else
                        {
                            if (StaticVariables.Configs.Count != 0)
                            {
                                StaticVariables.nmConexao        = StaticVariables.Configs[0].nmBase;
                                StaticVariables.ServerName       = StaticVariables.Configs[0].EnderecoDB;
                                StaticVariables.dbName           = StaticVariables.Configs[0].dbName;
                                StaticVariables.RemoteServerName = StaticVariables.Configs[0].dbName;
                                StaticVariables.nmUser           = StaticVariables.Configs[0].nmUser;
                                StaticVariables.snUser           = StaticVariables.Configs[0].snUser;
                                StaticVariables.nrPorta          = Convert.ToInt32(StaticVariables.Configs[0].nrPorta);
                                StaticVariables.nmSkin           = StaticVariables.Configs[0].nmSkin;
                                StaticVariables.imagemFundo      = Convert.ToBoolean(StaticVariables.Configs[0].imagemFundo);
                            }
                        }
                    }
                }
            }
            catch (Exception erro)
            {
                Alert.erro("(Erro ao Carregar dados do Arquivo Xml.) :" + erro.Message);
            }
        }