/// <summary> /// Exclui o diretório informado /// Para tratar problemas de acesso ao negado ao copiar e excluir /// Delete /// File.SetAttributes(file, FileAttributes.Normal); /// File.Delete(file); ///Copy ///File.Copy(file, dest, true); /// File.SetAttributes(dest, FileAttributes.Normal); /// /// Para diretorios use /// File.SetAttributes(d, FileAttributes.Directory); /// ///Todas as pasta, subpastas e arquivos serão removidos /// </summary> /// <param name="path"></param>Path do arquivo /// <returns></returns> public static bool DeleteDirectory(string path, bool recursive = true) { try { if (Directory.Exists(path)) { File.SetAttributes(path, FileAttributes.Directory); // Apaga tudo o que estiver // lá dentro (arquivos, sub-pastas, etc...) Directory.Delete(path, recursive); return(true); } } catch (DirectoryNotFoundException notFoundDir) { LoggerUtilIts.ShowExceptionLogs(notFoundDir); } catch (UnauthorizedAccessException accessDenied) { LoggerUtilIts.ShowExceptionLogs(accessDenied); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); } return(false); }
/// <summary> /// Faz com o que o label fique piscando /// </summary> public void RunOscillate() { string texto = TaskName; while (Running) { try { if (this.lblInfo.InvokeRequired) { SetTextCallback d = new SetTextCallback(infoMessage); form.Invoke(d, new object[] { texto }); } Thread.Sleep(350); if (this.lblInfo.InvokeRequired) { SetTextCallback d = new SetTextCallback(infoMessage); form.Invoke(d, new object[] { "" }); } Thread.Sleep(350); Console.WriteLine("Ilustrando ..."); } catch (ObjectDisposedException ex) { LoggerUtilIts.ShowExceptionLogs(ex); //Não importa apenas termine o laço return; } } }
//Converte JSON em classe C# //informe um link ou o proprio JSON //http://json2csharp.com/# public static string GetJSONString(string url) { try { //https://github.com/DeveloperCielo/Webservice-3.0/issues/12 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; ////https://github.com/adeniltonbs/Zeus.Net.NFe.NFCe/issues/219 /*ServicePointManager.Expect100Continue = true; * ServicePointManager.CheckCertificateRevocationList = false; * ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;*/ HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); WebResponse response = request.GetResponse(); using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); return(reader.ReadToEnd()); } } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); throw ex; } }
public Usuario FindUserByNameOrId(string logon) { Usuario usuario = null; if (string.IsNullOrWhiteSpace(logon) == false) { try { using (var ctx = new BalcaoContext()) { if (logon.IsContainsLetters()) { usuario = ctx.Usuarios.First(u => u.NomeUtilizador.Equals(logon)); } else { int id = ParseUtil.ToInt(logon); usuario = ctx.Usuarios.First(u => u.IdUsuario == id); } } } catch (InvalidOperationException ex) { Console.WriteLine("Usuario nao encontrado => " + ex.Message); return(null); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); return(null); } } return(usuario); }
public bool CreateNcms() { var x = gridView1.RowCount; var ctx = new BalcaoContext(); var dao = ctx.NcmsDao; for (int i = 0; i < gridView1.DataRowCount; i++) { DataRow row = gridView1.GetDataRow(i); var codigo = row[Codigo].ToString(); var desc = row[Descricao].ToString().Trim(); var un = row[UnidadeMed].ToString(); Ncms l = new Ncms { CodigoNcm = codigo, DataCadastro = DateTime.Now, DescricaoNcm = desc, UnidadeMedida = un }; try { dao.Save(l); this.Result.Add(l); } catch (Exception ex) { this.Errors.Add(l); LoggerUtilIts.ShowExceptionLogs(ex); } } return(true); }
public override async void PreVisualizarValidar() { if (!string.IsNullOrEmpty(txtExcelFile.Text)) { try { var m = new ModelProducaoSerra(gridViewBase, _user); XFrmWait.ShowSplashScreen("Preparando Dados"); var r = await Task.Run(() => m.LoadProducaoNew()); if (r) { base.ShowResult(m.Result); this.IsValido = true; this.barBtnSalvar.Enabled = true; } else { XMessageIts.Advertencia("Validação com erros."); base.ShowErrors(m.Errors); this.barBtnSalvar.Enabled = false; } Console.WriteLine(r); XFrmWait.CloseSplashScreen(); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); } } }
public CliFor GetClienteByNome(string nome) { using (var ctx = new BalcaoContext()) { ctx.LazyLoading(false); try { return(ctx.CliForDao.Where(c => c.RazaoSocial == nome).First()); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); if (nome.Equals("CONSUMIDOR")) { Console.WriteLine("CONSUMIDOR NOT FOUND => Criando ..."); CliFor c = new CliFor { RazaoSocial = nome, TipoCliente = ITSolution.Framework.Enumeradores.TypeCliente.Fisica, Classificacao = TypeClassificaoCliente.Cliente, CpfCnpj = "00000000000", }; if (ctx.CliForDao.Save(c)) { return(c); } } return(null); } } }
/// <summary> /// Verifica se o Objeto é válido a partir da anotações feitas. /// </summary> /// <param colName="entidade"></param> /// <returns></returns> Um coleção dos errorList public static List <ValidationResult> Validation(object obj) { //lista para armanezar os errorList List <ValidationResult> validationList = new List <ValidationResult>(); try { ValidationContext contexto = new ValidationContext(obj, null, null); //seta a lista de erros do Objeto informado Validator.TryValidateObject(obj, contexto, validationList, true); } catch (OverflowException ex1) { LoggerUtilIts.ShowExceptionLogs(ex1); throw ex1; } catch (Exception ex2) { LoggerUtilIts.ShowExceptionLogs(ex2); throw ex2; } return(validationList); }
/// <summary> /// Último Elemento da lista /// </summary> /// <returns></returns> public T Last(Func <T, bool> predicate = null) { try { if (predicate == null) { return(this.DbSet.ToList().Last <T>()); } else { return(this.DbSet.Where(predicate).Last <T>()); } } catch (InvalidOperationException ex) { // T:System.InvalidOperationException: // The source sequence is empty. // nao esta na sequencia LoggerUtilIts.ShowExceptionLogs(ex); } catch (ArgumentNullException ex) { // source is null. LoggerUtilIts.ShowExceptionLogs(ex); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); } return(null); }
/// <summary> /// Ilustra os '...' no tempo de inicialização do entity framework /// </summary> private void runProgress() { try { var description = this.progressPanel1.Description; int j = 0; //nao demora nunca 500 secs while (true)//usava o Sucess aqui { Thread.Sleep(200); Trace.WriteLine("Ilustrando ..."); if (j > 6) { SetTextCallback status = new SetTextCallback(setDescriptonProgressPanel); this.Invoke(status, new object[] { description }); j = 0; } else { SetTextCallback status = new SetTextCallback(setDescriptonProgressPanel); this.Invoke(status, new object[] { progressPanel1.Description + "." }); } j++; } } catch (System.InvalidOperationException ex) { LoggerUtilIts.ShowExceptionLogs(ex); Environment.Exit(0); } Trace.WriteLine("Fim do progresso"); }
/// <summary> /// Gera logs na saida padrão se a tarefa esta sendo executada /// </summary> private void loggerOut() { // Access thread-sensitive resources. try { //enquanto o form esta exibido while (this.Visible) { //Isso manda um repaint na barra nao eh a intencao /*RunTask task = new RunTask(PaintProgress); * string text = progressPanel1.Description + "."; * * this.Invoke(task, new object[] { text }); * reticencia++;*/ Thread.Sleep(150); Console.WriteLine("Tarefa em execução ..."); } //this.progressPanel1.BeginInvoke(new RunTask(InvokeMethod)); /// <summary> /// Ação de terminar a barra de progresso /// </summary> } catch (Exception ex) { this.Failed = true; LoggerUtilIts.ShowExceptionLogs(ex); } Console.WriteLine("Fim do progresso\nTarefa concluída"); }
/// <summary> /// Seleciona todas as linhas do grid view /// </summary> /// <param name="gridView"></param> public static void SelectAllRow(this GridView gridView) { try { gridView.SelectRange(0, gridView.RowCount - 1); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); } }
/// <summary> /// Move um diretorio para outro diretório /// </summary> /// <param name="tarjet"></param>Arquivo diretorio a ser movido /// <param name="destiny"></param>Local onde sera movido os arquivos /// </summary> /// <param name="tarjet"></param> /// <param name="destiny"></param> public static void MoveDirectories(string tarjet, string destiny) { try { Directory.Move(tarjet, destiny); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); throw ex; } }
private DbContextIts createCtx() { try { //retorna o pai return(new AdminContext()); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); return(null); } }
public AbstractAttach(string path, byte[] data) { try { this.PathFile = path; this.FileName = Path.GetFileName(path); this.DataFile = data; } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); } }
private void updateSoftware() { try { //extraindo atualização taskLogger("Iniciando atualização em: " + _installDir); var itemDlls = rChListTask.GetItemChecked(1); var itemDllsITE = rChListTask.GetItemChecked(2); var itemDllsITSolution = rChListTask.GetItemChecked(3); taskLogger("Atualizando DLLs ... "); /*Task.Run(new Action(() => * { * foreach (var f in FileManagerIts.ToFiles(...)) * { * //vo mostrar so o nome * taskLogger("Atualizando: " + Path.GetFileName(f)); * } * }));*/ //realiza a tarefa enquanto a ilustração rola if (itemDllsITE) { taskLogger("Atualizando ITE DLLs ... "); _taskUpdateManager.UpdateDLLsITE(_resourceDir, _installDir); } if (itemDllsITSolution) { taskLogger("Atualizando ITSolution DLLs ... "); _taskUpdateManager.UpdateDLLsITSolution(_resourceDir, _installDir); } else { _taskUpdateManager.UpdateSystemDLLs(_resourceDir, _installDir); } } catch (Exception ex) { try { cancelation(); taskLogger("Falha no pacote de atualizações"); taskLogger(ex.Message); LoggerUtilIts.ShowExceptionLogs(ex, this); } catch (OperationCanceledException oc) { taskLogger("Operação cancelada: " + oc.Message); } } }
/// <summary> /// Seleciona todas as linhas do grid view /// </summary> /// <param name="gridView"></param> public static void UnSelectAllRow(this GridView gridView) { try { for (int i = 0; i < gridView.RowCount; i++) { gridView.UnselectRow(i); } } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); } }
private void boundXGridTabDestino() { try { ConnectionFactoryIts conn = new ConnectionFactoryIts(AppConfigManager.Configuration.AppConfig.ConnectionString); DataTable dtTabelas = new DataTable("Tabelas"); dtTabelas = conn.ExecuteQueryDataTable("SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES"); gridControlTabDestino.DataSource = dtTabelas; } catch (SqlException ex) { LoggerUtilIts.ShowExceptionLogs(ex); } }
/// <summary> /// Remove um relatório do spool /// </summary> /// <param name="idSpool"></param> /// <returns></returns> public bool RemoveRelatorioFromSpool(Int32 idSpool) { using (var ctx = new ReportContext()) { try { var reportDelete = ctx.ReportSpoolDao.Find(idSpool); return(ctx.ReportSpoolDao.Delete(reportDelete)); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); return(false); } } }
/// <summary> /// Obtém a lista de todos os elementos da tabela. /// </summary> /// <param name="predicate"></param>Expressão /// <returns>A Queryable com todos os dados do objeto do banco de dados</returns> public IQueryable <T> Where(Func <T, bool> predicate) { try { return(this.DbSet.Where(predicate).AsQueryable()); } catch (ArgumentNullException ex) { LoggerUtilIts.ShowExceptionLogs(ex); throw ex; } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); throw ex; } }
/// <summary> /// Fecha a conexão com o banco de dados /// </summary> /// <returns>true se a conexão foi fechada ou false outros</returns> public virtual bool CloseConnection() { if (IsOpen()) { try { connection.Close(); return(true); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); return(false); } } return(false); }
/// <summary> /// Move todos os arquivos do diretório informado "tarjet" para o diretório "destiny" /// Se os arquivos existirem serão substituídos /// </summary> /// <param name="tarjet"></param>Arquivo diretorio a ser movido /// <param name="destiny"></param>Local onde sera movido os arquivos public static void MoveFiles(string tarjet, string destiny) { string alvo = ""; string destino = ""; try { //demorei a chegar a essa logica //.net complicou muito as coisas var files = FileManagerIts.GetFiles(tarjet); var directories = FileManagerIts.GetDirectories(tarjet); foreach (var d in directories) { alvo = d.FullName; destino = Path.Combine(destiny, d.Name); if (Directory.Exists(destino)) { Directory.Delete(destino); } Directory.Move(alvo, destino); } foreach (var f in files) { alvo = f.FullName; destino = Path.Combine(destiny, f.Name); if (File.Exists(destino)) { File.Delete(destino); } File.Move(alvo, destino); } } catch (Exception ex) { Console.WriteLine("Falha ao mover " + alvo + " para " + destino); LoggerUtilIts.ShowExceptionLogs(ex); throw ex; } }
/// <summary> /// Selecionar a coluna epecifica do grid View /// </summary> /// <param name="gridView"></param>GridView /// <param name="gridColumn"></param>Coluna a ser selecionad /// <param name="rowIndex"></param>Index da coluna public static void SetSelectColumn(GridView gridView, GridColumn gridColumn = null, int rowIndex = 0) { try { gridView.SelectRow(rowIndex); if (gridColumn == null) { gridColumn = gridView.Columns[0]; } gridView.FocusedColumn = gridColumn; gridView.RefreshData(); gridView.Focus(); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); } }
/// <summary> /// Exportar os dados do grid para o excel /// </summary> /// <param name="gridControlimport"></param> public void ExportExcel(GridControl gridControl) { try { var sv = new SaveFileDialog(); //caminho temporario var path = Application.StartupPath + "\\excel_temp.xlsx"; gridControl.ExportToXlsx(path); Process.Start(path); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); //throw; } }
public bool validar() { this.Errors = new HashSet <LancamentoFinanceiro>(); this.Result = new HashSet <LancamentoFinanceiro>(); for (int i = 0; i < gridViewBase.DataRowCount; i++) { DataRow row = gridViewBase.GetDataRow(i); var dt = DataUtil.ToDate(row[Data].ToString()); var vlr = ParseUtil.ToDecimal(row[Valor].ToString().Trim()); var obs = row[Obs].ToString().Trim(); var id = ParseUtil.ToInt(row[ID].ToString().Trim()); var l = new LancamentoFinanceiro(); l.DataLancamento = dt; l.DataVencimento = dt; l.ValorLancamento = vlr; l.Observacao = obs; l.IdCentroCusto = 4; l.IdCliFor = id; l.RecCreatedBy = 2; l.IdFilial = 1; l.IdFormaPagamento = (int)TypeFormaPagamento.Cheque; try { if (ValidadorDTO.Validate(l)) { this.Result.Add(l); } else { this.Errors.Add(l); } } catch (Exception ex) { this.Errors.Add(l); LoggerUtilIts.ShowExceptionLogs(ex); } } return(this.Errors.Count == 0); }
public List <ReportImage> GetReportGrpVendas() { using (var ctx = new ReportContext()) { try { var grpVenda = ctx.ReportGroupDao .Where(g => g.GroupDescription.Equals("Vendas")).First(); //todos os relatorios do grupo vendas return(ctx.ReportImages.Where(r => r.IdGrpReport == grpVenda.IdGrpReport).ToList()); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); return(null); } } }
/// <summary> /// Copia um arquivo para um diretorio ou substitui um arquivo existente /// /// </summary> /// <param name="sourceFile"></param>Arquivo a ser copiado /// <param name="file"></param>Destino do arquivo copiado /// <param name="overWrite"></param> /// <returns></returns>true para ser reescrito false nao sobreescreve public static bool CopyFile(string sourceFile, string file, bool overWrite = true) { try { //permissao para copiar File.SetAttributes(sourceFile, FileAttributes.Normal); // To copy a file to another location and // overwrite the destination file if it already exists. File.Copy(sourceFile, file, overWrite); return(true); } catch (Exception ex) { LoggerUtilIts.ShowExceptionLogs(ex); return(false); } }
private void indexColumnsCbColDestino(string tableName) { try { var dtColumns = new DataTable("ColumnsDestino"); ConnectionFactoryIts cnn = new ConnectionFactoryIts(AppConfigManager.Configuration.AppConfig.ConnectionString); dtColumns = cnn.ExecuteQueryDataTable(String.Format("SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = {0}", "\'" + tableName + "\'")); foreach (var col in dtColumns.AsEnumerable()) { var colDest = new ColunaDestino(col[0].ToString(), col[1].ToString(), col[2].ToString(), col[3].ToString(), col[4].ToString()); repComboDestino.Items.Add(colDest); } } catch (SqlException ex) { LoggerUtilIts.ShowExceptionLogs(ex); } }
/// <summary> ///Verifica se existe um ou mais elemetos na tabela. ///<br> ///Exceptions: ///</br> ///T:System.ArgumentNullException: ///<br> source is null.</br> ///<br>T:System.InvalidOperationException:</br> ///<br>The source sequence is empty.</br> /// </summary> /// <returns>true existe 1 ou mais caso contrário false</returns> public bool CheckFirst() { try { var f = First();//passou daqui ta ok return(true); } catch (ArgumentNullException ex) { Console.WriteLine("Primeiro nao existe"); LoggerUtilIts.ShowExceptionLogs(ex); throw ex; } catch (InvalidOperationException ex) { Console.WriteLine("Primeiro nao existe"); LoggerUtilIts.ShowExceptionLogs(ex); throw ex; } }
public bool CreateFuncionarios() { using (var ctx = new BalcaoContext()) { var dao = ctx.FuncionarioDao; for (int i = 0; i < gridView1.DataRowCount; i++) { DataRow row = gridView1.GetDataRow(i); var f = new Funcionario(); try { f.NomeFuncionario = row[NomeFuncionario].ToString(); f.CPF = row[CPF].ToString(); f.DataNascimento = DataUtil.ToDate(row[DataNascimento].ToString()); f.Idade = ParseUtil.ToInt(row[Idade].ToString()); f.DataAdmissao = DataUtil.ToDate(row[DataAdmissao].ToString()); f.Situacao = (TypeSituacaoFuncionario)ParseUtil.ToInt(row[Situacao].ToString()); f.Salario = ParseUtil.ToDecimal(row[Salario].ToString()); f.EstadoCivil = (TypeEstadoCivil)ParseUtil.ToDecimal(row[EstadoCivil].ToString()); f.TipoRecebimento = (TypeRecebimento)ParseUtil.ToDecimal(row[TipoRecebimento].ToString()); f.IdDepartamento = ParseUtil.ToInt(row[IdDepartamento].ToString()); f.IdFuncao = ParseUtil.ToInt(row[IdFuncao].ToString()); f.IdFilial = ParseUtil.ToInt(row[IdFilial].ToString()); //efetiva no banco dao.Save(f); this.Result.Add(f); } catch (Exception ex) { this.Errors.Add(f); LoggerUtilIts.ShowExceptionLogs(ex); } } return(true); } }