Пример #1
0
 /// <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;
     }
 }
Пример #2
0
        public void UpdateParamFromCodigo(List <Parametro> parametros)
        {
            int i = 0;

            using (var ctx = new BalcaoContext())
            {
                foreach (var param in parametros)
                {
                    try
                    {
                        var current = ctx.ParametroDao.Where(p =>
                                                             p.CodigoParametro == param.CodigoParametro)
                                      .First();

                        current.Update(param);

                        if (ctx.ParametroDao.Update(current))
                        {
                            i++;
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggerUtilIts.GenerateLogs(ex);
                    }
                }

                if (i == parametros.Count)//todos
                {
                    XMessageIts.Mensagem("As definições do sistema foram atualizadas.");
                }
                else if (i == 0)//nenhum
                {
                    XMessageIts.Erro("Não foi possível atualizar as preferências.", "Falha no sistema");
                }
                else //else if (i != parametros.Count) //uma ou mais
                {
                    XMessageIts.Advertencia("Uma ou mais preferências não foram atualizadas", "Atenção");
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Valida uma lista de objetos e exibe todas as mensagem em um MessageBox.
        /// </summary>
        /// <param colName="entidade"></param>
        /// <param name="objList"></param>
        /// <returns></returns> true se ok caso contrário false
        public static bool ValidateListWarningAll <T>(ICollection <T> objList) where T : new()
        {
            if (objList == null)
            {
                XMessageIts.Advertencia("Coleção não informada para validação");
            }

            string errorList = "";

            foreach (var obj in objList)
            {
                try
                {
                    List <ValidationResult> validationList = Validation(obj);

                    if (validationList.Count == 0)
                    {
                        return(true);
                    }
                    foreach (var errorMsg in validationList)
                    {
                        errorList = errorList + errorMsg.ToString() + "\n";
                    }

                    var hr = "==============================================================================\n";
                    errorList = errorList + hr + "\n";
                }
                catch (Exception ex)
                {
                    XMessageIts.Erro("Entidade nula tentou ser válidada.", "Atenção!!!");
                    LoggerUtilIts.GenerateLogs(ex);
                }
            }

            if (!String.IsNullOrWhiteSpace(errorList))
            {
                XMessageIts.Advertencia(errorList, "Dados inválidos");
                return(false);
            }
            return(true);
        }
Пример #4
0
        public bool ExcluirExtratos(List <ExtratoBancario> extratos)
        {
            using (var ctx = new BalcaoContext())
            {
                try
                {
                    foreach (var extrato in extratos)
                    {
                        var current = ctx.ExtratoBancarioDao.Find(extrato.IdExtrato);
                        ctx.ExtratoBancarioDao.Delete(current);
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    LoggerUtilIts.ShowExceptionMessage(ex);
                    return(false);
                }
            }
        }
Пример #5
0
        public void FindSetContaBancaria(string codigoConta)
        {
            try
            {
                using (var ctx = new BalcaoContext())
                {
                    //nao carregar os relacionamentos
                    ctx.LazyLoading(false);


                    if (!String.IsNullOrEmpty(codigoConta))
                    {
                        var contas = ctx.ContasBancaria
                                     .Where(f => f.CodigoContaBancaria == codigoConta);

                        if (contas.ToList().Count > 1)
                        {
                            //se isso aconteceu tem algo errado
                            XMessageIts.Mensagem("Número da conta informado pertence a mais de uma conta");
                        }
                        else
                        {
                            var current = contas.FirstOrDefault();

                            this.ContaBancaria = current;

                            txtCodConta.Text = current.Agencia;
                            buttonEdit1.Text = current.DescricaoContaBancaria;
                        }
                    }
                }
            }
            catch (NullReferenceException ex)
            {
                LoggerUtilIts.ShowExceptionLogs(ex);
                XMessageIts.Advertencia("Conta bancária não encontrada!");
                buttonEdit1.Text = "";
                return;
            }
        }
Пример #6
0
        /// <summary>
        /// Os objetos das celulas da linha especifica.
        /// </summary>
        /// <param colName="gridView"></param>
        /// <param colName="rowIndex"></param>
        /// <param name="gridView"></param>
        /// <returns></returns>
        public static object[] GetRowObjects(GridView gridView, int index)
        {
            try
            {
                int rowCount = gridView.DataRowCount;

                if (rowCount < 1)
                {
                    return(null);
                }
                int      columnCount = gridView.Columns.Count;
                object[] result      = new object[columnCount];

                DataRowView drv = gridView.GetRow(index) as DataRowView;

                DataRow dr = drv.Row;

                for (int i = 0; i < columnCount; i++)
                {
                    try
                    {
                        object o = dr.ItemArray[i];

                        result[i] = (o != null) ? o.ToString() : null;
                    }
                    catch (IndexOutOfRangeException ex)
                    {
                        Console.WriteLine("Falha ao obter os valores das celulas do gridview");
                        LoggerUtilIts.ShowExceptionLogs(ex);
                        return(null);
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao obter o valor da celula=>" + ex.Message);
                return(null);
            }
        }
Пример #7
0
        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);
            }
        }
Пример #8
0
        public List <CotacaoMonetaria> GetCotacoesIndicadoresBacen()
        {
            var cotacoes = new List <CotacaoMonetaria>();

            using (var ctx = new CambioContext())
            {
                try
                {
                    //recupera as moedas
                    var indicadores = CambioContext.Instance.IndicadoresBacenDao
                                      .FindAll().ToList();
                    //.Where(m => m.NomeCompletoMoeda.ToLower().Contains("peso")).ToList();

                    foreach (var ind in indicadores)
                    {
                        try
                        {
                            var cot     = getLastCotacaoAux(ind.CodigoMoeda);
                            var cotacao = new CotacaoMonetaria(cot.DataCotacao, cot.ValorCotacao, cot.ValorCotacao, ind);
                            cotacoes.Add(cotacao);
                        }
                        catch (BacenCambioException ex)
                        {
                            XMessageIts.Erro("Falha ao informações dos indicadores\n\n" +
                                             "Erro:" + ex.Message, ex.Title);
                            return(null);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string msg   = "Nenhum indicador localizado";
                    string title = "Falha na listagem de indicadores.";
                    XMessageIts.Advertencia(msg, title);
                    LoggerUtilIts.GenerateLogs(ex, msg + "\n" + title);
                }
            }
            return(cotacoes);
        }
Пример #9
0
            /// <summary>
            /// Gera um mensagem gráfica com os dados da exceção.
            /// </summary>
            /// <param colName="ex"></param>
            public DebugDao(Exception ex, T t, bool errorMessage = true)
                : base(ex.Message)
            {
                var type   = ex.GetType();
                var classe = t.GetType();
                //Logs
                string dirLogDao = @"C:\logs\its\dao";
                string title     = "Relatório de logs\n";
                string excecao   = "Erros de persistência: " + type;
                string entity    = "\nClasse de ocorrência: " + classe;
                string data      = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss");

                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
                string msg = "Mensagem: " + ex.Message + "\n" +
                             "Pilha de erros: " + ex.StackTrace + "\n" +
                             "Exceção interna: " + inner;


                var fileName = type + "-" + data + ".txt";
                var pathLog  = Path.Combine(dirLogDao, fileName);

                //cria o dir
                FileManagerIts.CreateDirectory(dirLogDao);

                //write logs
                FileManagerIts.AppendTextFileException(pathLog, ex, new string[] { title, excecao, entity, data, msg });

                //exibe o log na saida padrao
                LoggerUtilIts.ShowExceptionLogs(ex);

                if (errorMessage)
                {
                    //avisa do erro
                    XMessageIts.ExceptionJustMessage(ex, null, "Falha crítica no banco de dados");
                }
            }
Пример #10
0
        /// <summary>
        /// Lista todos os arquivos e pasta do diretório. Usa chamada recursiva
        ///
        /// </summary>
        /// <param name="pathDir"></param>
        /// <returns></returns>
        public HashSet <string> ToFilesRecursive(string pathDir)
        {
            try
            {
                foreach (var f in Directory.GetFiles(pathDir))
                {
                    fileList.Add(f);
                }
                foreach (var d in Directory.GetDirectories(pathDir))
                {
                    fileList.Add(d);

                    ToFilesRecursive(d);
                }
            }
            catch (Exception ex)
            {
                LoggerUtilIts.ShowExceptionLogs(ex);
                throw ex;
            }
            return(fileList);
        }
Пример #11
0
        public bool SaveUpdate(Lembrete novo)
        {
            using (var ctx = new ITSolutionContext())
            {
                if (novo.IdLembrete == 0)
                {
                    //nova tupla
                    return(save(novo, ctx));
                }
                else
                {
                    try
                    {
                        //procure o regstro
                        Lembrete result = ctx.LembreteDao
                                          .First(f => f.NomeLembrete == novo.NomeLembrete);

                        //se encontrei uma forma de pagamento
                        //que nao eh a igual a pk do registro selecionado
                        if (result.IdLembrete != novo.IdLembrete)
                        {
                            XMessageIts.Advertencia("Já existe um lembrete \"" + result.NomeLembrete + "\"");
                            return(false);
                        }

                        //atualize o registro
                        return(update(novo, ctx));
                    }
                    catch (Exception ex)
                    {
                        //nada encontrado pode atualizar
                        LoggerUtilIts.ShowExceptionMessage(ex);

                        //a pk nao eh a mesma a sendo editadava entao atualize
                        return(update(novo, ctx));
                    }
                }
            }
        }
Пример #12
0
        public bool GenerateSpoolFromReport(ReportImage report)
        {
            try
            {
                using (var ctx = new ReportContext())
                {
                    //zipar a imagem
                    var imageZipped = ZipUtil.ZipFromBytes(report.ReportImageData);

                    //criaçao do relatorio
                    var imgSave = new ReportSpool(DateTime.Now, report.ReportName, imageZipped);

                    return(ctx.ReportSpoolDao.Save(imgSave));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Falha na geração do spool");
                LoggerUtilIts.GenerateLogs(ex, "Falha na geração do spool do relatório");
                return(false);
            }
        }
Пример #13
0
        public static ContaBancaria GetContaBancariaDefault()
        {
            using (var ctx = new BalcaoContext())
            {
                try
                {
                    string codigo = TypeParametro.conta_bancaria.ToString();
                    var    param  = ctx.ParametroDao.Where(
                        c => String.Equals(c.CodigoParametro, codigo)).First();

                    var cb = ctx.ContaBancariaDao.Find(ParseUtil.ToInt(param.ValorParametro));

                    return(cb);
                }
                catch (Exception ex)
                {
                    LoggerUtilIts.ShowExceptionLogs(ex);
                    //whatever => azaaaar
                    return(null);
                }
            }
        }
Пример #14
0
        public bool SaveUpdate(CategoriaProduto novo)
        {
            using (var ctx = new BalcaoContext())
            {
                if (novo.IdCategoriaProduto == 0)
                {
                    //nova tupla
                    return(save(novo, ctx));
                }
                else
                {
                    try
                    {
                        //procure o regstro
                        CategoriaProduto result = ctx.CategoriaProdutoDao
                                                  .First(f => f.NomeCategoriaProduto == novo.NomeCategoriaProduto);

                        //se encontrei uma forma de pagamento
                        //que nao eh a igual a pk do registro selecionado
                        if (result.IdCategoriaProduto != novo.IdCategoriaProduto)
                        {
                            XMessageIts.Advertencia("Categoria " + result.NomeCategoriaProduto + " já existe !");
                            return(false);
                        }

                        //atualize o registro
                        return(update(novo, ctx));
                    }
                    catch (Exception ex)
                    {
                        //nada encontrado pode atualizar
                        LoggerUtilIts.ShowExceptionMessage(ex);

                        //a pk nao eh a mesma a sendo editadava entao atualize
                        return(update(novo, ctx));
                    }
                }
            }
        }
Пример #15
0
        private void XFrmReportEditor_Load(object sender, EventArgs e)
        {
            if (_reportImageAnt != null)
            {
                //roda em segundo plano
                // Task.Factory.StartNew(wait.Run).RunSynchronously();

                //new Thread(wait.Run).Start();

                try
                {
                    /// Abrir o relatório selecionado
                    //Abre o relatorio que foi armazenado no cache
                    var path = new ReportDaoManager().LoadToCache(_reportImageAnt);
                    itsReportDesign.OpenReport(path);
                }
                catch (Exception ex)
                {
                    LoggerUtilIts.GenerateLogs(ex);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Aguarde o fim da tarefa e invoca o menu se o contexto foi iniciado e o usuário logado corretamente
        /// </summary>
        private void waitRun()
        {
            try
            {
                _taskLogin.Wait();
            }
            catch (Exception ex)
            {
                string msg = "Ocorreu um erro não identificado ao realizar login.";
                LoggerUtilIts.GenerateLogs(ex, msg);
                Environment.Exit(0);
                Application.Exit();
                throw ex;
            }


            //se nao conseguiu logar deu ruim
            if (this._xFrmLogin.IsLogin == false)
            {
                //faz tudo denovo mas dessa vez fica amarrado
                //ou seja nao vai fechar o form ate logar corretamente
                this._xFrmLogin.ShowDialog();
            }

            Console.WriteLine("Task Done");

            AdminDTO admin = _taskLogin.Result;

            //se algum deles existe
            if (admin != null)
            {
                //garante o fim da Task
                _taskLogin.Dispose();

                //invoka a thread que amarra o menu principal
                Application.Run(new XFrmAdminMenu(_application));
            }
        }
Пример #17
0
        /// <summary>
        /// Compacta uma lista de arquivo em um arquivo .zip
        /// </summary>
        /// <param name="files"></param>Arquivos
        /// <param name="zipOut"></param>Arquivo .zip de saida
        /// <returns></returns>true compactado ou false erro
        public static bool CompressFiles(string[] files, string zipOut)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                try
                {
                    // percorre todos os arquivos da lista
                    foreach (string f in files)
                    {
                        // se o item é um arquivo
                        if (File.Exists(f))
                        {
                            // Adiciona o arquivo na pasta raiz dentro do arquivo zip
                            zip.AddFile(f, "");
                        }
                        // se o item é uma pasta
                        else if (Directory.Exists(f))
                        {
                            // Adiciona a pasta no arquivo zip com o nome da pasta
                            zip.AddDirectory(f, new DirectoryInfo(f).Name);
                        }
                    }

                    // Salva o arquivo zip para o destino
                    zip.Save(zipOut);

                    //tudo certo
                    return(true);
                }
                catch (Exception ex)
                {
                    LoggerUtilIts.ShowExceptionLogs(ex);
                    XMessageIts.ExceptionJustMessage(ex, "Falha ao compactar o arquivo");
                    //deu merda
                    return(false);
                }
            }
        }
Пример #18
0
        private CotacaoMonetaria getCotacao(TypeCodigoBacen codigoCompra, TypeCodigoBacen codigoVenda)
        {
            long codCompra = (long)codigoCompra;
            long codVenda  = (long)codigoVenda;

            var cotCompraAux = getLastCotacaoAux(codCompra);
            var cotVendaAux  = getLastCotacaoAux(codVenda);

            //a data do cotCompraAux e cotVendaAux sao iguais
            var cot = new CotacaoMonetaria(cotVendaAux.DataCotacao, cotCompraAux.ValorCotacao,
                                           cotVendaAux.ValorCotacao, cotCompraAux.SerieVo);

            cot.AddReference(cotCompraAux.SerieVo);

            using (var ctx = new CambioContext())
            {
                try
                {
                    //recupera a moeda pelo codigo de compra/venda
                    Moeda moeda = ctx.MoedaDao.First(m =>
                                                     m.CodigoWSCompra == codCompra || m.CodigoWSVenda == codVenda);

                    cot.Moeda = moeda;
                    SaveCotacaoMonetaria(ctx, cot);
                }
                catch (Exception ex)
                {
                    string msg   = "Moeda não foi localizada";
                    string title = "Não foi possível obter a atualização cambial";
                    XMessageIts.Advertencia(msg, title);

                    LoggerUtilIts.GenerateLogs(ex, msg + "\n" + title);

                    throw ex;
                }
            }
            return(cot);
        }
Пример #19
0
        /// <summary>
        /// Faz com o que o label se move
        /// </summary>
        public void RunMoving()
        {
            if (this.form.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(infoMessage);
                form.Invoke(d, new object[] { TaskName });

                //1/5 do tamanho
                int volta = this.form.Width - lblInfo.Location.X + 100;

                //terminado dps
                while (Running)
                {
                    try
                    {
                        this.lblInfo.BeginInvoke(new Action(() =>
                        {
                            //se atravessou o label pro outro lado do form
                            if (this.lblInfo.Location.X >= volta)
                            {
                                //faz o primeiro caracter aparecer do outro lado do form
                                this.lblInfo.Location = new Point(-(volta / 2), this.lblInfo.Location.Y);
                            }

                            //faz o label se mover
                            this.lblInfo.Location = new Point(this.lblInfo.Location.X + 1, this.lblInfo.Location.Y);
                        }));
                        Thread.Sleep(10);
                    }
                    catch (ObjectDisposedException ex)
                    {
                        LoggerUtilIts.ShowExceptionLogs(ex);
                        //Não importa apenas termine o laço
                        return;
                    }
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Apaga um arquivo ou diretorio
        /// 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);
        /// </summary>
        /// <param name="path"></param>Arquivo ou pasta a ser apagada.
        /// <returns></returns>true se apagado caso contrário false
        public static bool DeleteFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                    return(true);
                }

                else if (Directory.Exists(path))
                {
                    return(DeleteDirectory(path));
                }

                return(false);
            }
            catch (DirectoryNotFoundException notFoundDir)
            {
                LoggerUtilIts.ShowExceptionLogs(notFoundDir);
                return(false);
            }
            catch (FileNotFoundException notFoundDir)
            {
                LoggerUtilIts.ShowExceptionLogs(notFoundDir);
                return(false);
            }
            catch (UnauthorizedAccessException accessDenied)
            {
                LoggerUtilIts.ShowExceptionLogs(accessDenied);
                return(false);
            }
            catch (Exception ex)
            {
                LoggerUtilIts.ShowExceptionLogs(ex);
                return(false);
            }
        }
Пример #21
0
        /// <summary>
        /// Obtém um objeto da tabela pela chave primária.
        /// </summary>
        /// <returns>Um objeto do banco de dados</returns>
        public async Task <T> FindAsync(params object[] key)
        {
            if (key == null || String.IsNullOrWhiteSpace(key.ToString()))
            {
                return(null);
            }

            try
            {
                return(await DbSet.FindAsync(key));
            }
            catch (InvalidOperationException ex)
            {
                LoggerUtilIts.ShowExceptionLogs(ex);
                return(null);
            }
            catch (Exception ex)
            {
                string msg = "Falha localizar objeto pela chave primária.";
                XMessageIts.ExceptionJustMessage(ex, msg);
            }
            return(null);
        }
Пример #22
0
        /// <summary>
        /// Recupera o nome de usuário no arquivo de preferências
        /// </summary>
        /// <param name="logon"></param>
        /// <returns></returns>
        private string retryLogon(string logon)
        {
            if (logon == null)
            {
                List <string> preferencias = FileManagerIts.GetDataFile(UnitWork.PREFERENCIAS);
                if (preferencias.Count > 3)
                {
                    try
                    {
                        //recupera do arquivo o logon
                        return(ASCIIEncodingIts.Decoded(preferencias[3]));
                    }
                    catch (Exception ex)
                    {
                        LoggerUtilIts.ShowExceptionLogs(ex);

                        FileManagerIts.DeleteFile(UnitWork.PREFERENCIAS);
                        return(null);
                    }
                }
            }
            return(logon);
        }
Пример #23
0
        /// <summary>
        /// Seta o foco na primeira linha da tabela
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="rowIndex"></param>
        public static void SetSelectRow(GridView gridView, int rowIndex = 0)
        {
            try
            {
                int selectRow = gridView.FocusedRowHandle;

                if (rowIndex >= 0)
                {
                    gridView.FocusedRowHandle = rowIndex;
                    gridView.SelectRow(rowIndex);
                }
                else
                {
                    gridView.FocusedRowHandle = selectRow;
                    gridView.SelectRow(selectRow);
                }
                gridView.Focus();
            }
            catch (Exception ex)
            {
                LoggerUtilIts.ShowExceptionLogs(ex);
            }
        }
Пример #24
0
        /// <summary>
        /// Obtém um objeto da tabela pela chave primária.
        /// </summary>
        /// <returns>Um objeto do banco de dados</returns>
        public T Find(params object[] key)
        {
            if (key == null || String.IsNullOrWhiteSpace(key.ToString()))
            {
                return(null);
            }

            try
            {
                return(DbSet.Find(key));
            }
            catch (InvalidOperationException ex)
            {
                LoggerUtilIts.ShowExceptionLogs(ex);
            }
            catch (Exception ex)
            {
                //rolou um treta nao esperada
                string msg = "Falha localizar objeto pela chave primária.";
                Console.WriteLine(msg + "\n" + ex.Message);
            }
            return(null);
        }
Пример #25
0
        /// <summary>
        /// Salva ou atualiza cotação
        /// </summary>
        /// <param name="ctx"></param> Contexto
        /// <param name="cot"></param>Cotação a ser salva
        public void SaveCotacaoMonetaria(CotacaoMonetaria cot)
        {
            using (var ctx = new CambioContext())
            {
                try
                {
                    var cotacao = new CotacaoMonetaria(cot.DataCotacao, cot.ValorCompra, cot.ValorVenda);
                    //FK
                    cotacao.IdMoeda = cot.Moeda.IdMoeda;

                    //salva no banco
                    ctx.CotacaoMonetariaDao.Save(cotacao);
                }
                catch (Exception ex)
                {
                    string msg   = "Moeda não foi localizada";
                    string title = "Problema na rotina de atualização cambial";
                    XMessageIts.Advertencia(msg, title);

                    LoggerUtilIts.GenerateLogs(ex, msg + "\n" + title);
                }
            }
        }
Пример #26
0
        private void barBtnEditarCc_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                var node = treeListCentros.FocusedNode;
                var v    = treeListCentros.GetDataRecordByNode(node) as ArrayList;
                var cct  = new CentroCustoDaoManager().GetCentroByCodigo(v[0].ToString());
                var frm  = new XFrmAddCentroCusto(cct);

                frm.ShowDialog();

                cct = frm.CentroCusto;
                node.SetValue(treeListColumn1, cct.CodigoCentroCusto);
                node.SetValue(treeListColumn2, cct.NomeCentroCusto);
                treeListCentros.RefreshNode(node);
            }
            catch (Exception ex)
            {
                XMessageIts.Mensagem("Centro de custo não pode ser editado");

                LoggerUtilIts.GenerateLogs(ex);
            }
        }
Пример #27
0
        /// <summary>
        /// Captura e gera um documento html a partir do url
        /// </summary>
        /// <param name="url"></param>Url
        /// <returns></returns>Documento html
        public static HtmlDocument GetHtmlDocument(String url)
        {
            try
            {
                String     htmlSource = "";
                WebRequest request    = WebRequest.Create(url);

                WebResponse  response = request.GetResponse();
                StreamReader reader   = new StreamReader(response.GetResponseStream());

                htmlSource = reader.ReadToEnd();

                reader.Close();
                //response.Close();

                return(CreateHtmlDocument(htmlSource));
            }
            catch (Exception ex)
            {
                LoggerUtilIts.ShowExceptionLogs(ex);
                return(CreateHtmlDocument("<html> </html>"));
            }
        }
Пример #28
0
        /// <summary>
        /// Último Elemento da lista
        /// </summary>
        /// <returns></returns>
        public async Task <T> LastAsync(Func <T, bool> predicate = null)
        {
            try
            {
                if (predicate == null)
                {
                    var r = await this.DbSet.ToListAsync();

                    return(r.Last());
                }
                else
                {
                    var task = await this.DbSet.ToListAsync();

                    var r = task.Where(predicate);
                    return(r.Last());
                }
            }

            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);
        }
Пример #29
0
        /// <summary>
        /// Localiza os dados no ws dos correios
        /// </summary>
        /// <param name="cep"></param>
        /// <returns></returns>
        private bool findAdress(string cep)
        {
            if (String.IsNullOrEmpty(cep))
            {
                return(false);
            }
            try
            {
                WSCorreiosCep.AtendeClienteClient ws = new WSCorreiosCep
                                                       .AtendeClienteClient("AtendeClientePort");

                var r = ws.consultaCEP(cep);

                this.Endereco     = r.end;
                this.Bairro       = r.bairro;
                this.Complemento  = r.complemento;
                this.Complemento2 = r.complemento2;
                this.Cep          = r.cep;
                this.Cidade       = r.cidade;
                this.UF           = r.uf;

                if (!r.cep.Equals(this.Cep))
                {
                    XMessageIts.Advertencia("Notificamos que o seu CEP mudou!\n\n" +
                                            "Confira novamente seu CEP.", "Atenção ! ! !");
                }

                return(true);
            }
            catch (Exception ex)
            {
                LoggerUtilIts.GenerateLogs(ex);

                LoggerUtilIts.ShowExceptionLogs(ex);
                return(false);
            }
        }
Пример #30
0
        private async Task findCep()
        {
            string cep = txtCep.Text;

            if (!String.IsNullOrWhiteSpace(cep))
            {
                FindCepIts find = new FindCepIts();

                try
                {
                    bool result = await find.FindAdress(cep);

                    this.CEP      = find.Cep;
                    this.Cidade   = find.Cidade;
                    this.UF       = find.UF;
                    this.Bairro   = find.Bairro;
                    this.Endereco = find.Endereco;

                    this.txtCep.Text        = CEP;
                    this.txtCidade.Text     = Cidade;
                    this.txtUF.Text         = UF;
                    this.txtBairro.Text     = Bairro;
                    this.txtLogradouro.Text = Endereco;

                    if (result)
                    {
                        this.lblFlagCep.Visible = true;
                    }
                    else
                    {
                        this.lblFlagCep.Visible = false;
                    }
                }
                catch (Exception ex) { LoggerUtilIts.GenerateLogs(ex); }
            }
        }