Example #1
0
        public async static void ExHandler(Exception ex, string adm = "")//Usar num catch
        {
            Relatório report;

            if (ex.Message.StartsWith("{"))//se for json é erro da Fipe ou Exceção nossa
            {
                report = JsonConvert.DeserializeObject <Relatório>(ex.Message);
                PostMessage(report);
            }
            else
            {
                report = new Relatório(1, ex.Message + adm);//se não for json então é Exceção do .Net
                PostMessage(report);
                //Home.Hide();
                await EnviarRelatorio(true);

                if (adm != "Home_Load")
                {
                    Home.AtualizarFill();
                    if (!File.Exists(WebFile.AppData + "Restauração.bin"))
                    {
                        File.Create(WebFile.AppData + "Restauração.bin").Close();
                    }
                    WebFile.Serialize(Home.fill, WebFile.AppData + "Restauração.bin");
                }
                //Environment.Exit(1);
            }
        }
Example #2
0
        public async Task <List <FipeMake> > GetMakes(FipeType type)
        {
            try
            {
                List <FipeMake> makes    = new List <FipeMake>();
                string          url      = /*await*/ UrlBuilder(_getMakesUrl, new string[] { _refTable, ((int)type).ToString() });
                string          jsonList = await WebFile.HttpRequestAsync(url);

                if (String.IsNullOrEmpty(jsonList))
                {
                    throw new WebException(JsonConvert.SerializeObject(new Relatório(2, "", "Sem acesso à internet")));
                }
                else
                {
                    if (jsonList.StartsWith("["))//tests if string is a json list (starts with '[')... "{\"codigo\":\"3\",\"erro\":\"Código fipe inválido\"}" , "{\"codigo\":\"0\",\"erro\":\"Nada encontrado\"}")
                    {
                        makes = JsonConvert.DeserializeObject <List <FipeMake> >(jsonList);
                    }
                    else
                    {
                        throw new WebException(jsonList);
                    }
                }
                return(makes);
            }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(new List <FipeMake>());
            }
        }
Example #3
0
        public async Task <List <FipeModel> > QueryYear_modelsByFipeCode(string code)//QueryByFipeCode(Tipo t, string code)
        {
            try
            {
                int numcode = -1;
                if (code == "" || !Int32.TryParse(code.Replace("-", ""), out numcode) || numcode == 0 || numcode > 9999999)
                {
                    throw new WebException(JsonConvert.SerializeObject(new Relatório(3)));
                }

                code = numcode.ToString("000000-0");

                List <FipeModel> models = await GetModels(code);

                if (models.Count == 0)
                {
                    return(models);
                }

                List <Task <string> > requests = new List <Task <string> >();
                foreach (FipeModel model in models)
                {
                    string url = /*await*/ UrlBuilder(_queryByFipeCodeUrl, new string[] { _refTable, ((int)model.TipoVeiculo).ToString(), model.AnoModelo, model.TipoCombustivel, _vehicleTypes[(int)model.TipoVeiculo], code, _queryTypes[0] });
                    requests.Add(WebFile.HttpRequestAsync(url));
                }

                string[] responses = await TaskEx.WhenAll(requests);

                if (responses.Length == 0 || String.IsNullOrEmpty(responses[0]))
                {
                    throw new WebException(JsonConvert.SerializeObject(new Relatório(4)));
                }

                foreach (string json in responses)
                {
                    if (Array.IndexOf(responses, json) == 0)                                //insert mockup in position 0
                    {
                        FipeModel mockup = JsonConvert.DeserializeObject <FipeModel>(json); //mockup: "Selecione o ano/modelo:"
                        mockup.Label = "Selecione o ano/modelo:";
                        mockup.Value = "0";
                        mockup.Valor = null;
                        models.Insert(0, mockup);
                    }

                    FipeModel model = JsonConvert.DeserializeObject <FipeModel>(json);
                    model.Label = models.ElementAt(Array.IndexOf(responses, json) + 1).Label;
                    model.Value = models.ElementAt(Array.IndexOf(responses, json) + 1).Value;
                    models[Array.IndexOf(responses, json) + 1] = model;
                }
                return(models);
            }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(new List <FipeModel>());
            }
        }
Example #4
0
        private async Task <List <FipeModel> > GetModels(string code)
        {
            try
            {
                string url = /*await*/ UrlBuilder(_getModelsUrl, new string[] { _refTable, "1", _vehicleTypes[1], code, _queryTypes[0] });
                //if (_refTable == "0")
                //  throw new WebException(JsonConvert.SerializeObject(new Relatório(0, "Fipe indisponível")));

                List <Task <string> > requests = new List <Task <string> >();
                foreach (int type in Enum.GetValues(typeof(FipeType)).OfType <object>().Where(o => (int)o > 0))//Autodetection FipeType
                {
                    url = /*await*/ UrlBuilder(_getModelsUrl, new string[] { _refTable, type.ToString(), _vehicleTypes[type], code, _queryTypes[0] });
                    requests.Add(WebFile.HttpRequestAsync(url));
                }

                string[] responses = await TaskEx.WhenAll(requests);

                if (responses.Length == 0 || String.IsNullOrEmpty(responses[0]) || String.IsNullOrEmpty(responses[1]) || String.IsNullOrEmpty(responses[2]))
                {
                    throw new WebException(JsonConvert.SerializeObject(new Relatório(2, "", "Sem acesso à internet")));
                }

                List <FipeModel> models = new List <FipeModel>();
                foreach (string jsonList in responses)
                {
                    if (jsonList.StartsWith("["))//tests if string is a json list (stars with '[')... "{\"codigo\":\"3\",\"erro\":\"Código fipe inválido\"}" , "{\"codigo\":\"0\",\"erro\":\"Nada encontrado\"}")
                    {
                        models = JsonConvert.DeserializeObject <List <FipeModel> >(jsonList);
                        foreach (FipeModel model in models)
                        {
                            model.TipoVeiculo = (FipeType)(Array.IndexOf(responses, jsonList) + 1);
                        }
                    }
                    else
                    {
                        Relatório report = JsonConvert.DeserializeObject <Relatório>(jsonList);
                        if (report.Codigo != 0)
                        {
                            throw new WebException(jsonList);
                        }
                    }
                }
                if (models.Count == 0)
                {
                    throw new WebException(JsonConvert.SerializeObject(new Relatório(3)));
                }
                else
                {
                    return(models);
                }
            }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(new List <FipeModel>());
            }
        }
Example #5
0
        public async static Task <bool> PrimeiroUso()
        {
            bool   primeira = false;
            string verArq   = null;

            if (File.Exists(LocalVersao))
            {
                using (StreamReader leitor = new StreamReader(LocalVersao))
                {
                    string linha;
                    while ((linha = leitor.ReadLine()) != null)
                    {
                        verArq = linha;
                    }
                }

                if (double.Parse(verArq) != double.Parse(Application.ProductVersion))
                {
                    primeira = true;
                }

                FileStream fs = new FileStream(LocalVersao, FileMode.Create, FileAccess.Write);
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine($"{Application.ProductVersion}");
                }
            }
            else
            {
                FileStream fs = new FileStream(LocalVersao, FileMode.Create, FileAccess.Write);
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine($"{Application.ProductVersion}");
                }
                primeira = true;
            }
            if (primeira)
            {
                string info    = "Informações:\r\nNome do usuário: " + Environment.UserName + "\r\nVersão: " + Application.ProductVersion + "\r\nSistema operacional: " + SistemaOperacional();
                var    message = new MailMessage(WebFile.Email.Address, WebFile.Email.Address)
                {
                    Subject = ("Nova versão instalada em " + Environment.UserName),
                    Body    = (info)
                };

                await WebFile.SendEmailAsync(message);
            }
            return(primeira);
        }
Example #6
0
        private async void button1_Click(object sender, EventArgs e)
        {
            if (WebFile.HasInternet())
            {
                textBox1.ReadOnly = true;
                textBox2.ReadOnly = true;
                button1.Enabled   = false;
                button2.Enabled   = false;
                button1.Text      = "Enviando...";
                Cursor            = Cursors.WaitCursor;

                await Relatório.EnviarErro(textBox1.Text, textBox2.Text, anexo);

                Close();
            }
            else
            {
                MessageBox.Show("Sem conexão com a internet,\r\npor favor tente mais tarde.", "Carta de Cotação", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #7
0
        private async void botaobuscar_Click(object sender, EventArgs e)
        {
            botaobuscar.Enabled         = false;
            botaobuscar.BackgroundImage = Properties.Resources.CarregandoParado;

            if (WebFile.HasInternet())
            {
                FipeQuery        query   = new FipeQuery();
                List <FipeModel> modelos = await query.QueryYear_modelsByFipeCode(codFipe.Text);

                if (modelos.Count > 0)
                {
                    switch (modelos[0].TipoVeiculo)
                    {
                    case FipeType.Automóvel:
                        tipo1.Checked = true;
                        break;

                    case FipeType.Moto:
                        tipo2.Checked = true;
                        break;

                    case FipeType.Caminhão:
                        tipo3.Checked = true;
                        break;
                    }
                }
                anoModeloFipe.DisplayMember = "Label";
                anoModeloFipe.ValueMember   = "Value";
                anoModeloFipe.DataSource    = modelos;
            }
            else
            {
                MessageBox.Show("Sem acesso à internet!", "Carta de Cotação",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }

            botaobuscar.Enabled         = true;
            botaobuscar.BackgroundImage = Properties.Resources.Buscar;
        }
Example #8
0
        public async static Task EnviarErro(string nome, string descricao, string local)
        {
            string adicionais = "Nome do usuário: " + Environment.UserName + "\r\nVersão: " + Application.ProductVersion + "\r\nSistema operacional: " + SistemaOperacional() + "\r\n-------------------------------------------------";
            var    message    = new MailMessage(WebFile.Email.Address, WebFile.Email.Address)
            {
                Subject = ("Relatório de erro de " + Environment.UserName),
                Body    = (adicionais + "\r\n\r\n" + "Nome: " + nome + "\r\n" + "Descrição: " + descricao + "\r\n")
            };

            if (local != null)
            {
                var attachment = new Attachment(local);
                message.Attachments.Add(attachment);
            }
            if (await WebFile.SendEmailAsync(message))
            {
                MessageBox.Show("Problema enviado com sucesso!", "Carta de Cotação", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                MessageBox.Show("Não foi possível enviar o problema.", "Carta de Cotação", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Example #9
0
        public void GerarPdf()
        {
            var       doc1     = new Document(PageSize.A4, 40.0f, 20.0f, 30.0f, 30.0f);//Margens - Margem direita precisa ser 20 para poder caber valores acima de R$ 100.000,00 nas contratações
            string    filename = null;
            PdfWriter writer   = null;

            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog
                {
                    InitialDirectory = PdfFolder,
                    Filter           = "Arquivo PDF|*.pdf",
                    Title            = "Salvar como",
                    FileName         = Cota.Cliente + ".pdf"
                };
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (saveFileDialog1.FileName != "")
                    {
                        filename = saveFileDialog1.FileName;
                        writer   = PdfWriter.GetInstance(doc1, new FileStream(saveFileDialog1.FileName, FileMode.Create));
                        Relatório.SalvaUtilizacao(Cota);
                    }
                }
                else
                {
                    return;
                }

                Home.preferencias.PastaPDF = saveFileDialog1.FileName.Substring(0, saveFileDialog1.FileName.LastIndexOf('\\') + 1);
                WebFile.Prefs = Home.preferencias;
            }
            catch (IOException)
            {
                Relatório.AdicionarAoRelatorio("Há um arquivo de mesmo nome aberto");
                MessageBox.Show("Não foi possível criar o arquivo PDF,\r\nverifique se há um arquivo de mesmo nome aberto.\r\nFeche-o e tente novamente.",
                                "Carta de Cotação",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                return;
            }

            doc1.Open();
            iTextSharp.text.Font normal = FontFactory.GetFont("Helvetica", 11);

            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(ConverteImageParaByteArray(Properties.Resources.Bragaseg));
            jpg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
            jpg.ScaleToFit(250f, 250f);
            //jpg.SetAbsolutePosition(500f, 750f);

            //Como colocar marca d'água:
            //jpg.SetAbsolutePosition(doc1.PageSize.Width - 500f, 750f);
            //jpg.Rotation = (float)Math.PI / 2;
            //jpg.RotationDegrees = 90f;

            doc1.Add(jpg);

            doc1.Add(new Paragraph("\r\n", normal));
            Paragraph pfcity = new Paragraph("Passo Fundo, " + DataPorExtenso(Cota.Data) + ".", normal);

            //pfcity.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
            //pfcity.IndentationLeft = 230;
            doc1.Add(pfcity);
            doc1.Add(new Paragraph("\r\n", normal));
            if (Home.excedeuLinhas)
            {
                doc1.Add(new Paragraph("A " + Cota.Cliente, normal));
            }
            else
            {
                doc1.Add(new Paragraph("A", normal));
                doc1.Add(new Paragraph(Cota.Cliente, normal));
            }
            doc1.Add(new Paragraph("\r\n", normal));
            doc1.Add(new Paragraph("Estamos encaminhando a cotação do veículo abaixo:", normal));
            doc1.Add(new Paragraph(Cota.Marca + " - " + Cota.Modelo, normal));
            doc1.Add(new Paragraph("Ano de fabricação: " + Cota.AnoFabricacao + "      Ano modelo: " + Cota.AnoModelo, normal));
            doc1.Add(new Paragraph("\r\n", normal));

            //Início das contratações:
            decimal        valorfipecont = Cota.ValorFipe * Cota.PorContratada / 100m;
            List <string>  contrat       = new List <string>();
            List <decimal> listvalores   = new List <decimal>();

            if (Cota.Rcf != true)
            {
                if (Cota.Vd != true)
                {
                    contrat.Add("Casco - " + Cota.PorContratada + "% da Fipe:");
                }
                else
                {
                    contrat.Add("Valor Determinado:");
                }
                listvalores.Add(valorfipecont);
            }
            else
            {
                contrat.Add("Sem casco contratado");
                listvalores.Add(-1.0m);
            }

            contrat.Add("Danos Materiais:");
            listvalores.Add(Cota.DanosMateriais);

            contrat.Add("Danos Corporais:");
            listvalores.Add(Cota.DanosCorporais);

            contrat.Add("Danos Morais:");
            listvalores.Add(Cota.DanosMorais);

            if (Cota.Seguradora != "Itaú")
            {
                contrat.Add("APP Morte:");
            }
            else
            {
                contrat.Add("APP:");
            }
            listvalores.Add(Cota.APPMorte);

            //AQUI: ESSE NÃO APARECE SE FOR ITAÚ
            contrat.Add("APP Invalidez:");
            listvalores.Add(Cota.APPInvalidez);

            if (Cota.Tipo == FipeType.Caminhão)
            {
                contrat.Add("Equipamento:");
                listvalores.Add(Cota.Equipamento);

                contrat.Add("Carroceria:");
                listvalores.Add(Cota.Carroceria);
            }

            bool semdecimais = listvalores.Exists(d => d > 999999);

            PdfPTable valores = new PdfPTable(5);

            valores.HorizontalAlignment = 0;
            float[] widthvalores = { 45f, 30f, 9f, 40f, 30f };
            valores.SetWidths(widthvalores);
            valores.DefaultCell.BorderColor = iTextSharp.text.BaseColor.WHITE;

            int c    = 0;  //contador de valores não zero na listvalores
            int n    = 0;  //num linhas
            int MODO = 0;  //<--MODO 0 divide os itens entre as colunas 1 e 2

            if (MODO == 0) //MODO 1 sempre preenche a coluna 1 inteira (3 itens ou 4 se caminhão) e depois preenche a coluna 2
            {
                foreach (decimal d in listvalores)
                {
                    if (d != 0.0m)
                    {
                        c++;
                        if (c % 2 != 0)
                        {
                            n++;
                        }
                    }
                }
            }
            else
            {
                n = 3;//num linhas se não caminhão
                if (Cota.Tipo == FipeType.Caminhão)
                {
                    n = 4;//num linhas se caminhão
                }
            }

            int[] col1 = new int[] { -1, -1, -1, -1 }; //posições na coluna 1, inicializa com -1 = não preenchido
            int[] col2 = new int[] { -1, -1, -1, -1 }; //posições na coluna 2, inicializa com -1 = não preenchido

            c = 0;                                     //reinicia contador
            int i = 0;                                 //contador de índice da listvalores

            foreach (decimal d in listvalores)
            {
                if (d != 0.0m)
                {
                    if (c < n)       //preenchimento da coluna 1
                    {
                        col1[c] = i; //guarda a posição de d na listvalores e contrat
                    }
                    else//preenchimento da coluna 2, após coluna 1 estar cheia
                    {
                        col2[c - n] = i;//guarda a posição de d na listvalores e contrat, c - n porque o índice deve iniciar no zero
                    }
                    c++;
                }
                i++;
            }

            for (i = 0; i < n; i++)
            {
                if (col1[i] != -1)                                         //testa se a posição na coluna 1 tem valor a ser preenchido
                {
                    valores.AddCell(new Phrase(contrat[col1[i]], normal)); //preenche com a string de contrat na posição guardada em col1

                    if (listvalores[col1[i]] != -1.0m)                     // testa se é o caso "sem casco"
                    {
                        if (!semdecimais)
                        {
                            valores.AddCell(new Phrase(listvalores[col1[i]].ToString("C2", CultureInfo.CurrentCulture)));//converte valor para string
                        }
                        else
                        {
                            valores.AddCell(new Phrase(listvalores[col1[i]].ToString("C0", CultureInfo.CurrentCulture)));//converte valor para string
                        }
                    }
                    else
                    {
                        valores.AddCell(new Phrase("", normal)); //se for "sem casco" preenche com vazio
                    }
                    valores.AddCell(new Phrase("", normal));     //preenche a coluna do meio com vazio
                }

                if (col2[i] != -1)                                         //testa se a posição na coluna 2 tem valor a ser preenchido
                {
                    valores.AddCell(new Phrase(contrat[col2[i]], normal)); //preenche com a string de contrat na posição guardada em col2
                    // como "sem casco" nunca vai cair na coluna 2, não precisa testar
                    if (!semdecimais)
                    {
                        valores.AddCell(new Phrase(listvalores[col2[i]].ToString("C2", CultureInfo.CurrentCulture)));//converte valor para string
                    }
                    else
                    {
                        valores.AddCell(new Phrase(listvalores[col2[i]].ToString("C0", CultureInfo.CurrentCulture)));//converte valor para string
                    }
                }
                else
                {
                    valores.AddCell(new Phrase("", normal)); //se a posição na coluna 2 não tem valor, preenche com vazio
                    valores.AddCell(new Phrase("", normal)); //idem acima para o valor
                }
            }
            doc1.Add(valores);
            //Fim das contratações

            int colunas = 3;
            if (Cota.Seguradora == "Bradesco" || Cota.Seguradora == "Generale" || (Cota.Seguradora == "Mapfre" && Cota.DebitoBB == true))
            {
                colunas = 2;
            }
            float[] width  = { 15f, 15f, 15f };
            float[] width2 = { 15f, 15f };

            //Tabela Franquia Básica
            if (Cota.FranquiaBasica + Cota.ValFranqBasicaAVista != 0)
            {
                PdfPTable table = new PdfPTable(colunas);

                if (colunas == 3)
                {
                    table.SetWidths(width);
                }
                else
                {
                    table.SetWidths(width2);
                }
                table.HorizontalAlignment = 0;
                PdfPCell cell = new PdfPCell(new Phrase(""));
                cell.Colspan             = 1;
                cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                table.AddCell(cell);
                doc1.Add(new Paragraph("\r\n", normal));
                if (Cota.Rcf != true)
                {
                    doc1.Add(new Paragraph("Franquia básica: " + Cota.FranquiaBasica.ToString("C2", CultureInfo.CurrentCulture), normal));
                    doc1.Add(new Paragraph("\r\n", normal));
                }

                if (Cota.Seguradora == "Mapfre" && Cota.DebitoBB)
                {
                    table.AddCell(new Phrase("Débito", normal));
                }
                else
                {
                    table.AddCell(new Phrase("Carnê", normal));
                }

                if (colunas != 2)
                {
                    if (Cota.Seguradora == "Sul América")
                    {
                        table.AddCell(new Phrase("Débito BB", normal));
                    }
                    else
                    {
                        table.AddCell(new Phrase("Débito", normal));
                    }
                }

                foreach (Parcelamento parc in Cota.TabelaParcelamento.FindAll(p => (p.TipoFranq == "Básica" && !(p.Seguradora == "Bradesco" && p.FormaPagto == "Débito")) && /* ADICIONADO */ !(p.Seguradora == "Generale" && p.FormaPagto == "Débito") && (p.TipoFranq == "Básica" && !(p.Seguradora == "Mapfre" && p.FormaPagto == "Carnê" && Cota.DebitoBB == true))))
                {
                    if (parc.FormaPagto == "Carnê" || (parc.FormaPagto == "Débito" && Cota.DebitoBB && parc.ValParcela != 0.0m))
                    {
                        table.AddCell(new Phrase(parc.Descricao.ToString(), normal));
                    }

                    if (parc.ValParcela == 0.0m)
                    {
                        table.AddCell(new Phrase("", normal));
                    }
                    else
                    {
                        table.AddCell(new Phrase(parc.ValParcela.ToString("C2", CultureInfo.CurrentCulture), normal));
                    }
                }
                doc1.Add(table);
            }
            //Tabela Franquia Reduzida
            if (Cota.FranquiaReduzida + Cota.ValFranqReduzidaAVista != 0.0m && Cota.Rcf != true)
            {
                PdfPTable table2 = new PdfPTable(colunas);
                if (colunas == 3)
                {
                    table2.SetWidths(width);
                }
                else
                {
                    table2.SetWidths(width2);
                }
                table2.HorizontalAlignment = 0;
                PdfPCell cell2 = new PdfPCell(new Phrase(""))
                {
                    Colspan             = 1,
                    HorizontalAlignment = 1
                };
                //0=Left, 1=Centre, 2=Right
                table2.AddCell(cell2);
                doc1.Add(new Paragraph("\r\n"));
                doc1.Add(new Paragraph("Franquia reduzida: " + Cota.FranquiaReduzida.ToString("C2", CultureInfo.CurrentCulture), normal));
                doc1.Add(new Paragraph("\r\n"));

                if (Cota.Seguradora == "Mapfre" && Cota.DebitoBB)
                {
                    table2.AddCell(new Phrase("Débito", normal));
                }
                else
                {
                    table2.AddCell(new Phrase("Carnê", normal));
                }

                if (colunas != 2)
                {
                    if (Cota.Seguradora == "Sul América")
                    {
                        table2.AddCell(new Phrase("Débito BB", normal));
                    }
                    else
                    {
                        table2.AddCell(new Phrase("Débito", normal));
                    }
                }

                foreach (Parcelamento parc in Cota.TabelaParcelamento.FindAll(p => (p.TipoFranq == "Reduzida" && !(p.Seguradora == "Bradesco" && p.FormaPagto == "Débito")) && /* ADICIONADO */ !(p.Seguradora == "Generale" && p.FormaPagto == "Débito") && (p.TipoFranq == "Reduzida" && !(p.Seguradora == "Mapfre" && p.FormaPagto == "Carnê" && Cota.DebitoBB == true))))
                {
                    if (parc.FormaPagto == "Carnê" || (parc.FormaPagto == "Débito" && Cota.DebitoBB && parc.ValParcela != 0.0m))
                    {
                        table2.AddCell(new Phrase(parc.Descricao.ToString(), normal));
                    }

                    if (parc.ValParcela == 0.0m)
                    {
                        table2.AddCell(new Phrase("", normal));
                    }
                    else
                    {
                        table2.AddCell(new Phrase(parc.ValParcela.ToString("C2", CultureInfo.CurrentCulture), normal));
                    }
                }
                doc1.Add(table2);
            }
            //Final Tabelas

            doc1.Add(new Paragraph("\r\n", normal));
            doc1.Add(new Paragraph(Cota.Observacoes, normal));

            if (Cota.MostrarValidade == true)
            {
                string textovalidade = "*Validade da cotação: " + Cota.Validade.ToShortDateString();
                doc1.Add(new Paragraph(textovalidade, normal));
            }

            doc1.Add(new Paragraph("\r\n", normal));
            iTextSharp.text.Font negrito = FontFactory.GetFont("Helvetica", 11, iTextSharp.text.Font.BOLD);

            //Testes das exibições

            /*if (Cota.NomeClaudio == true)
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * if (Cota.CelClaudio == true)
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * if (Cota.NomeFuncionario == true && Cota.Funcionario != "")
             *  exib += "1";
             * else
             *  exib += "0";
             *
             * switch (exib)
             * {
             *  case "001":
             *      doc1.Add(new Paragraph(Cota.Funcionario, negrito));
             *      break;
             *  case "010":
             *      doc1.Add(new Paragraph("(54) 9981-4797", negrito));
             *      break;
             *  case "011":
             *      doc1.Add(new Paragraph("(54) 9981-4797 / " + Cota.Funcionario, negrito));
             *      break;
             *  case "100":
             *      doc1.Add(new Paragraph("Cláudio Zanchet", negrito));
             *      break;
             *  case "101":
             *      doc1.Add(new Paragraph("Cláudio Zanchet / " + Cota.Funcionario, negrito));
             *      break;
             *  case "110":
             *      doc1.Add(new Paragraph("Cláudio Zanchet" + " - (54) 9981-4797", negrito));
             *      break;
             *  case "111":
             *      doc1.Add(new Paragraph("Cláudio Zanchet" + " - (54) 9981-4797 / " + Cota.Funcionario, negrito));
             *      break;
             * }*/
            //Fim dos testes das exibições
            doc1.Add(new Paragraph(Cota.Funcionario, negrito));

            if (Cota.NomeFuncionario)
            {
                doc1.Add(new Paragraph("Bragaseg Corretora de Seguros", normal));
            }
            else
            {
                doc1.Add(new Paragraph("Bragaseg Corretora de Seguros", negrito));
            }
            doc1.Add(new Paragraph("Rua Uruguai, 1763 - Bairro Centro", normal));
            doc1.Add(new Paragraph("Passo Fundo - RS    CEP: 99010-112", normal));
            doc1.Add(new Paragraph("Telefone: (54) 3045-5300", normal));

            doc1.AddCreator("Carta de Cotação");
            File.Create(WebFile.AppData + "TempFill.bin").Close();
            WebFile.Serialize(Cota.Preenchimento, WebFile.AppData + "TempFill.bin");
            PdfFileSpecification pfs = PdfFileSpecification.FileEmbedded(writer, WebFile.AppData + "TempFill.bin", "TempFill.bin", null);
            writer.AddFileAttachment(pfs);
            doc1.Close();
            File.Delete(WebFile.AppData + "TempFill.bin");

            if (MessageBox.Show("Arquivo PDF gerado com sucesso!\r\nVocê deseja visualizá-lo agora?", "Carta de Cotação", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                Process.Start(filename);
            }
        }
Example #10
0
        private async static Task EnviarRelatorio(bool emergencia = false)
        {
            DirectoryInfo appData = new DirectoryInfo(WebFile.AppData);

            FileInfo[] arqsAppData     = appData.GetFiles();
            string     arquivosAPPData = "\r\n-------------------------------------------------\r\n";

            foreach (FileInfo f in arqsAppData)
            {
                arquivosAPPData += f.Name + " - " + f.Length + " KB - " + f.LastWriteTime + "\r\n";
            }
            arquivosAPPData += "-------------------------------------------------";

            string log = null;

            if (File.Exists(LocalUtilizacoes))
            {
                using (StreamReader leitor = new StreamReader(LocalUtilizacoes))
                {
                    string linha;
                    while ((linha = leitor.ReadLine()) != null)
                    {
                        log += linha;
                        log += "\r\n";
                    }
                }
            }
            else
            {
                log = "Nenhuma utilização registrada.\r\n";
            }

            string log2 = "\r\n";

            if (File.Exists(LocalRelatorio))
            {
                using (StreamReader leitor = new StreamReader(LocalRelatorio))
                {
                    string linha;
                    while ((linha = leitor.ReadLine()) != null)
                    {
                        log2 += linha;
                        log2 += "\r\n";
                    }
                }
            }
            else
            {
                log2 += "Nenhum relatório de uso.\r\n";
            }

            int numLinhas = log.Split('\n').Length - 1;

            string adicionais = "Nome do usuário: " + Environment.UserName + "\r\nVersão: " + Application.ProductVersion + "\r\nSistema operacional: " + SistemaOperacional() +
                                "\r\nNúmero de utilizações: " + numLinhas.ToString() + arquivosAPPData + log2;

            var message = new MailMessage(WebFile.Email.Address, WebFile.Email.Address);

            if (!emergencia)
            {
                message.Subject = ("Relatório semanal de " + Environment.UserName);
            }
            else
            {
                message.Subject = ("Relatório emergencial de " + Environment.UserName);
            }
            string mensagem = adicionais + "-------------------------------------------------\r\n" + log;

            message.Body = (mensagem);
            if (await WebFile.SendEmailAsync(message))
            {
                File.Delete(LocalUtilizacoes);
                if (File.Exists(LocalRelatorio))
                {
                    File.Delete(LocalRelatorio);
                }
            }
        }
Example #11
0
        private void editarCartaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = preferencias.PastaPDF,
                Filter           = "Arquivo PDF|*.pdf",
                Title            = "Abrir"
            };

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (openFileDialog1.FileName != "")
                {
                    string        filename = openFileDialog1.FileName;
                    PdfDictionary documentNames;
                    PdfDictionary embeddedFiles;
                    PdfDictionary fileArray;
                    PdfDictionary file;
                    PRStream      stream;
                    using (PdfReader reader = new PdfReader(filename))
                    {
                        PdfDictionary catalog = reader.Catalog;

                        documentNames = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.NAMES));

                        if (documentNames != null)
                        {
                            embeddedFiles =
                                (PdfDictionary)PdfReader.GetPdfObject(documentNames.Get(PdfName.EMBEDDEDFILES));
                            if (embeddedFiles != null)
                            {
                                PdfArray filespecs = embeddedFiles.GetAsArray(PdfName.NAMES);

                                for (int i = 0; i < filespecs.Size; i++)
                                {
                                    i++;
                                    fileArray = filespecs.GetAsDict(i);
                                    file      = fileArray.GetAsDict(PdfName.EF);

                                    foreach (PdfName key in file.Keys)
                                    {
                                        stream = (PRStream)PdfReader.GetPdfObject(file.GetAsIndirectObject(key));
                                        //string attachedFileName = fileArray.GetAsString(key).ToString();
                                        byte[] attachedFileBytes = PdfReader.GetStreamBytes(stream);

                                        File.WriteAllBytes(WebFile.AppData + "TempFill.bin", attachedFileBytes);
                                        fill = (Fill)WebFile.Deserialize(WebFile.AppData + "TempFill.bin");
                                        Limpar();
                                        PreencherFill();
                                        File.Delete(WebFile.AppData + "TempFill.bin");
                                        Relatório.AdicionarAoRelatorio("Editar carta");
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    Relatório.AdicionarAoRelatorio("Tentativa de editar carta antiga");
                    MessageBox.Show(
                        "Somente as cartas geradas a partir da versão atual\r\ndo programa podem ser editadas.",
                        "Carta de Cotação",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Relatório.AdicionarAoRelatorio("Tentativa de editar carta antiga");
                }
            }
        }
Example #12
0
        private async void Home_Load(object sender, EventArgs e)
        {
            try
            {
                //if (!File.Exists(WebFile.AppData + "Status.dat") && !await WebFile.HasInternet())
                //throw new Exception("Sem internet e Status não encontrado");

                await WebFile.CheckAppFilesAsync();

                preferencias  = WebFile.Prefs;
                status        = WebFile.Status;
                tipo1.Checked = true;
                opcaoNomeFuncionario.Checked = true;
                //seguradora.DataSource = status.Segs;
                if (preferencias.Validade)
                {
                    opcaoValidadeCot.Checked = true;
                }
                else
                {
                    opcaoValidadeCot.Checked = true;
                    opcaoValidadeCot.Checked = false;
                }

                if (await Relatório.PrimeiroUso())
                {
                    Relatório.MoverDadosAntigos();
                    if (novaVersaoLabel2.Text != "" && novaVersaoLabel2.Text != " ")
                    {
                        novaVersao.Location = new Point(171, 207);
                        novaVersao.Size     = new Size(503, 229);
                        novaVersao.Visible  = true;
                    }
                }

                if (status.VersoesFunc.FirstOrDefault(v => v.VersionNum == Application.ProductVersion) == null)
                {
                    Relatório.PostMessage(new Relatório(5));
                }

                if (Atualizacao.VerificarAtualizacoes(status))
                {
                    AtualizarPrograma();
                }

                if (status.VersoesFunc.FirstOrDefault(v => v.VersionNum == Application.ProductVersion) == null)
                {
                    Close();
                }

                if (!status.ProgDisp)
                {
                    Relatório.PostMessage(new Relatório(6));
                    Environment.Exit(1);
                }

                if (status.Mensagem != "")
                {
                    mensagem.ForeColor = Color.FromName(status.CorMsg);
                    mensagem.Text      = status.Mensagem.Replace("|", "\r\n");
                    mensagem.Visible   = true;
                }

                if (!status.Fipe)
                {
                    modoManual.Checked = true;
                    modoManual.Visible = false;
                    fipe = false;
                }
                else
                {
                    fipe = true;
                }
                if (File.Exists(WebFile.AppData + "Restauração.bin"))
                {
                    fill = (Fill)WebFile.Deserialize(WebFile.AppData + "Restauração.bin");

                    if (File.GetCreationTime(WebFile.AppData + "Restauração.bin").Date == DateTime.Now.Date &&
                        fill.Cliente != "")
                    {
                        if (
                            MessageBox.Show(
                                "Você deseja restaurar o preenchimento salvo\r\nde quando ocorreu um erro no programa?",
                                "Carta de Cotação", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                            DialogResult.Yes)
                        {
                            mensagem.ForeColor = Color.Blue;
                            mensagem.Text      =
                                "Verifique se o preenchimento restaurado foi\r\ninserido corretamente antes de gerar a carta.";
                            PreencherFill();
                        }
                    }

                    File.Delete(WebFile.AppData + "Restauração.bin");
                }
                //Código para destacar novos recursos:

                /*DateTime dataArquivo = File.GetLastWriteTime(WebFile.AppData + "Versão.dat");
                 * TimeSpan dif = DateTime.Now - dataArquivo;
                 * if (dif.Days <= 3)
                 * {
                 *  label1.Visible = true;
                 *  arquivoToolStripMenuItem.ForeColor = Color.Blue;
                 *  editarCartaToolStripMenuItem.ForeColor = Color.Blue;
                 * }*/
                await Relatório.VerificarEnvio();

                exemploToolStripMenuItem.Enabled = true;
                limparToolStripMenuItem.Enabled  = true;
                botaoLimpar.Enabled = true;
                seguradora.Enabled  = true;
                carregando.Visible  = false;
            }
            catch (Exception ex)
            {
                if (File.Exists(WebFile.AppData + "Status.dat"))
                {
                    Relatório.ExHandler(ex, "Home_Load");
                }
                else
                {
                    MessageBox.Show("ATENÇÃO:\r\nNão foi possível baixar os arquivos necessários para o programa funcionar.\r\n"
                                    + "Verifique se seu Windows está atualizado (IMPORTANTE).\r\n"
                                    + "Verifique sua conexão com a internet ou se o acesso à internet pelo programa está sendo bloqueado.\r\n"
                                    + "\r\nErro interno:\r\n"
                                    + ex.Message, "Carta de Cotação", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Relatório.AdicionarAoRelatorio("Status não encontrado");
                    Environment.Exit(1);
                }
            }
        }