コード例 #1
0
        private void Limpar()
        {
            Relatório.AdicionarAoRelatorio("Limpar pressionado");
            nome.Text                   = "";
            data.Value                  = DateTime.Now;
            codFipe.Text                = "";
            anoModeloFipe.DataSource    = new List <FipeModel>();
            anoModeloFipe.SelectedIndex = -1;
            modelo.Text                 = marca.Text = anoModeloTexto.Text = "";
            valorFipe.Text              = "000"; //TENTAR ALTERAR PARA VAZIO SEM DAR ERRO
            anoFabric.SelectedIndex     = -1;
            if (fipe)
            {
                modoManual.Checked = false;
            }
            opcaoVD.Checked                         = false;
            opcaoDebitoBB.Checked                   = false;
            seguradora.SelectedIndex                = 0;
            porcentFipe.Value                       = 100;
            opcaoRCF.Checked                        = false;
            danosMateriais.Text                     =
                danosCorporais.Text                 =
                    danosMorais.Text                =
                        APPMorte.Text               =
                            APPInvalidez.Text       =
                                equipamento.Text    = carroceria.Text = franqBasica.Text = vistaBasica.Text =
                                    franqReduz.Text = vistaReduz.Text = "0";
            observacoes.Text                        = "";
            DateTime hoje    = DateTime.Now;
            DateTime comdias = hoje.AddDays(5);

            dataValidadeCot.Value        = comdias;
            opcaoNomeFuncionario.Checked = true;
        }
コード例 #2
0
        private void gerar_Click(object sender, EventArgs e)
        {
            if (mensagem.Text != status.Mensagem.Replace("|", "\r\n"))
            {
                mensagem.Text = status.Mensagem.Replace("|", "\r\n");
            }

            if (!mensagemObservacoes.Visible)
            {
                AtualizarFill();
                Cotacao cota = new Cotacao((FipeType)Enum.Parse(typeof(FipeType), tipoveiculo), nome.Text, data.Value,
                                           seguradora.Text, modelo.Text,
                                           anoFabric.Text, anoModeloTexto.Text, marca.Text, valorFipe.Text, porcentFipe.Value.ToString(),
                                           danosMateriais.Text,
                                           danosCorporais.Text, danosMorais.Text, APPMorte.Text, APPInvalidez.Text, franqBasica.Text,
                                           vistaBasica.Text, franqReduz.Text, vistaReduz.Text, observacoes.Text,
                                           opcaoNomeFuncionario.Checked, nomeFuncionario.Text, opcaoDebitoBB.Checked, opcaoRCF.Checked,
                                           equipamento.Text,
                                           carroceria.Text, opcaoVD.Checked, opcaoValidadeCot.Checked, dataValidadeCot.Value, fill);
                if (cota.ErroDeFormato == false)
                {
                    var pdf = new Pdf(cota);
                    pdf.GerarPdf();
                }
            }
            else
            {
                Relatório.AdicionarAoRelatorio("Linhas das observações excederam limite");
                MessageBox.Show("As observações excedem o limite de linhas.",
                                "Carta de Cotação",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
            }
        }
コード例 #3
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);
            }
        }
コード例 #4
0
 public Home()
 {
     InitializeComponent();
     try
     {
         Relatório.Home = this;
         for (int i = DateTime.Now.Year; i >= 1981; i--)
         {
             anoFabric.Items.Add(i.ToString());
         }
         anoFabric.SelectedIndex = -1;
         //tipo1.Checked = true;
         data.Value                       = DateTime.Now;
         danosMateriais.Text              =
             danosCorporais.Text          =
                 danosMorais.Text         = APPMorte.Text = APPInvalidez.Text = equipamento.Text = carroceria.Text =
                     franqBasica.Text     =
                         vistaBasica.Text = franqReduz.Text = vistaReduz.Text = valorFipe.Text = "0";
         labelValorFipe.Text              = "Valor na Fipe no mês " + DateTime.Today.ToString("M/yyyy") + ":";
         List <FipeModel> modelos = new List <FipeModel>();
         anoModeloFipe.DataSource = modelos;
     }
     catch (Exception ex)
     {
         Relatório.ExHandler(ex, "Home_Load");
     }
 }
コード例 #5
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>());
            }
        }
コード例 #6
0
        private void opcaoRCF_CheckedChanged(object sender, EventArgs e)
        {
            if (opcaoRCF.Checked)
            {
                Relatório.AdicionarAoRelatorio("RCF");
                labelVistaBasica.Text    = "Valor à vista se RCF:";
                labelPorcentFipe.Visible = porcentFipe.Visible = simboloPorcentFipe.Visible = false;

                labelFranqBasica.Visible        =
                    franqBasica.Visible         = labelFranqReduz.Visible = franqReduz.Visible = metadeBasica.Visible =
                        labelVistaReduz.Visible = vistaReduz.Visible = false;

                labelVistaBasica.Location = new Point(154, 78);
                vistaBasica.Location      = new Point(157, 94);
            }
            else
            {
                labelVistaBasica.Text = "Valor à vista com franquia básica:";

                if (opcaoVD.Checked != true)
                {
                    labelPorcentFipe.Visible   = true;
                    porcentFipe.Visible        = true;
                    simboloPorcentFipe.Visible = true;
                }

                labelFranqBasica.Visible        =
                    franqBasica.Visible         = labelFranqReduz.Visible = franqReduz.Visible = metadeBasica.Visible =
                        labelVistaReduz.Visible = vistaReduz.Visible = true;

                labelVistaBasica.Location = new Point(154, 120);
                vistaBasica.Location      = new Point(157, 136);
            }
        }
コード例 #7
0
        private void sobreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Relatório.AdicionarAoRelatorio("Sobre aberto");
            Sobre about = new Sobre();

            about.Show();
        }
コード例 #8
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>());
            }
        }
コード例 #9
0
        public static void Serialize(object o, string local)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream     stream    = new FileStream(local, FileMode.Create, FileAccess.Write, FileShare.Read);

            try { formatter.Serialize(stream, o); }
            catch (Exception ex) { Relatório.ExHandler(ex); }
            finally { stream.Close(); }
        }
コード例 #10
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>());
            }
        }
コード例 #11
0
        public static void PostMessage(Relatório report)
        {
            if (report.Erro != " ")//vazio = não adicionar ao Report
            {
                AdicionarAoRelatorio(report.Erro);
            }

            if (report.UserMessage != " ")//vazio = não mostrar para o usuário
            {
                MessageBox.Show(report.UserMessage + "\r\n\r\nErro interno:\r\n" + report.Erro, AppDomain.CurrentDomain.FriendlyName.Replace(".exe", ""), MessageBoxButtons.OK, UserMessageTypes[report.Codigo]);
            }
        }
コード例 #12
0
 private void modoManual_CheckedChanged(object sender, EventArgs e)
 {
     if (modoManual.Checked)
     {
         Relatório.AdicionarAoRelatorio("Digitar manualmente");
         HabilitarFipe(false);
     }
     else
     {
         HabilitarFipe(true);
     }
 }
コード例 #13
0
        public static object Deserialize(string local)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream     stream    = new FileStream(local, FileMode.Open, FileAccess.Read, FileShare.Read);

            try { return(formatter.Deserialize(stream)); }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(new object());
            }
            finally { stream.Close(); }
        }
コード例 #14
0
        /*public static async Task<DateTime> LastModified(string url)
         * {
         *  if (!HasInternet())
         *      return DateTime.MinValue;
         *
         *  var tcs = new TaskCompletionSource<WebResponse>();
         *  try
         *  {
         *      HttpWebRequest head = (HttpWebRequest)WebRequest.Create(url);
         *      head.Method = WebRequestMethods.Http.Head;
         *      head.BeginGetResponse(iar =>
         *      {
         *          try { tcs.TrySetResult(req.EndGetResponse(iar)); }
         *          catch (OperationCanceledException) { tcs.TrySetCanceled(); }
         *          catch (Exception ex) { tcs.TrySetException(ex); }
         *      }, null);
         *
         *      using (WebResponse response = await tcs.Task)
         *      {
         *          DateTime lastModified;
         *          if (DateTime.TryParse(response.Headers.Get("Last-Modified"), out lastModified))
         *              return lastModified;
         *          else
         *              return DateTime.MinValue;
         *      }
         *  }
         *  catch (Exception ex)
         *  {
         *      Relatório.ExHandler(ex);
         *      return DateTime.MinValue;
         *  }
         * }*/

        public static async Task <string> HttpRequestAsync(string url)
        {
            HttpWebRequest post = (HttpWebRequest)WebRequest.Create(url.Substring(0, url.IndexOf("?")));

            post.Method = WebRequestMethods.Http.Post;

            post.Accept      = "*/*";
            post.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            post.Referer     = @"http://veiculos.fipe.org.br/api/veiculos/";
            post.UserAgent   = "Mozilla / 5.0(Windows NT 10.0; WOW64; rv: 40.0) Gecko / 20100101 Firefox / 40.0";
            post.Headers.Add("Accept-Encoding", "gzip, deflate");
            post.Headers.Add("Accept-Language", "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3");
            post.Headers.Add("X-Requested-With", "XMLHttpRequest");

            var tcsRequest  = new TaskCompletionSource <Stream>();
            var tcsResponse = new TaskCompletionSource <WebResponse>();

            try
            {
                post.BeginGetRequestStream(iar =>
                {
                    try { tcsRequest.TrySetResult(post.EndGetRequestStream(iar)); }
                    catch (OperationCanceledException) { tcsRequest.TrySetCanceled(); }
                    catch (Exception ex) { tcsRequest.TrySetException(ex); }
                }, null);

                byte[] body = Encoding.UTF8.GetBytes(url.Substring(url.IndexOf("?") + 1));
                using (Stream request = await tcsRequest.Task)
                    request.Write(body, 0, body.Length);

                post.BeginGetResponse(iar =>
                {
                    try { tcsResponse.TrySetResult(post.EndGetResponse(iar)); }
                    catch (OperationCanceledException) { tcsResponse.TrySetCanceled(); }
                    catch (Exception ex) { tcsResponse.TrySetException(ex); }
                }, null);

                string output;
                using (WebResponse response = await tcsResponse.Task)
                    using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                        output = stream.ReadToEnd();

                return(output);
            }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(null);
            }
        }
コード例 #15
0
        public static async Task <bool> SendEmailAsync(MailMessage message)
        {
            if (!HasInternet())
            {
                return(false);
            }

            SmtpClient client = new SmtpClient()
            {
                Host                  = "smtp.gmail.com",
                Port                  = 587,
                EnableSsl             = true,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(Email.Address, _password)
            };

            ServicePointManager.ServerCertificateValidationCallback =
                delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };

            var tcs = new TaskCompletionSource <bool>();

            try
            {
                client.SendCompleted += (s, e) =>
                {
                    if (e.Error != null)
                    {
                        tcs.TrySetException(e.Error);
                    }
                    else
                    if (e.Cancelled)
                    {
                        tcs.TrySetCanceled();
                    }
                    else
                    {
                        tcs.TrySetResult(true);
                    }
                };

                client.SendAsync(message, null);
                return(await tcs.Task);
            }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(false);
            }
        }
コード例 #16
0
        private void pastaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Relatório.AdicionarAoRelatorio("Botão abrir última pasta pressionado");
            var pasta = preferencias.PastaPDF;

            if (pasta != "")
            {
                Process.Start(pasta);
            }
            else
            {
                MessageBox.Show("Nenhuma pasta está registrada ainda.", "Carta de Cotação", MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation);
            }
        }
コード例 #17
0
 private void opcaoNomeFuncionario_CheckedChanged(object sender, EventArgs e)
 {
     if (opcaoNomeFuncionario.Checked)
     {
         Relatório.AdicionarAoRelatorio("Nome do funcionário selecionado");
         nomeFuncionario.Enabled = true;
         nomeFuncionario.Text    = preferencias.NomeFuncionario;
     }
     else
     {
         Relatório.AdicionarAoRelatorio("Nome do funcionário desselecionado");
         nomeFuncionario.Enabled      = false;
         preferencias.NomeFuncionario = nomeFuncionario.Text;
         WebFile.Prefs        = preferencias;
         nomeFuncionario.Text = "";
     }
 }
コード例 #18
0
 private void metadeBasica_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     Relatório.AdicionarAoRelatorio("Metade da básica pressionado");
     try
     {
         decimal metade = decimal.Parse(franqBasica.Text, NumberStyles.Currency, CultureInfo.CurrentCulture) / 2;
         franqReduz.Text = Math.Round(metade, 2).ToString("C", CultureInfo.CurrentCulture);
         //“C” de Currency (Moeda)
     }
     catch (FormatException)
     {
         MessageBox.Show(
             "Não foi possível calcular a metade\r\nda franquia básica, verifique se\r\npreencheu corretamente os campos\r\ne tente novamente!",
             "Carta de Cotação",
             MessageBoxButtons.OK,
             MessageBoxIcon.Error);
     }
 }
コード例 #19
0
 private void exemploToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Relatório.AdicionarAoRelatorio("Exemplo de preenchimento visualizado");
     if (nome.Text != "")
     {
         if (
             MessageBox.Show("Você deseja limpar o programa e visualizar\r\num exemplo de preenchimento?",
                             "Carta de Cotação", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
         {
             novaVersao.Visible = false;
             AutoPreencher();
         }
     }
     else
     {
         novaVersao.Visible = false;
         AutoPreencher();
     }
 }
コード例 #20
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);
            }
        }
コード例 #21
0
        private void opcaoVD_CheckedChanged(object sender, EventArgs e)
        {
            if (opcaoVD.Checked)
            {
                Relatório.AdicionarAoRelatorio("VD");
                modoManual.Checked = false;
                modoManual.Visible = false;
                HabilitarFipe(false);

                labelValorFipe.Text = "Valor do veículo:";

                labelPorcentFipe.Visible   = false;
                porcentFipe.Visible        = false;
                simboloPorcentFipe.Visible = false;

                porcentFipe.Text = "100";
            }
            else
            {
                if (fipe)
                {
                    modoManual.Visible = true;
                    HabilitarFipe(true);
                }
                valorFipe.Text      = "000";
                labelValorFipe.Text = string.Format("Valor na Fipe no mês {0}/{1}", DateTime.Today.Month,
                                                    DateTime.Today.Year);
                if (!fipe)
                {
                    modoManual.Checked = true;
                }
                if (opcaoRCF.Checked != true)
                {
                    labelPorcentFipe.Visible   = true;
                    porcentFipe.Visible        = true;
                    simboloPorcentFipe.Visible = true;
                }
            }
        }
コード例 #22
0
 private void opcaoDebitoBB_CheckedChanged(object sender, EventArgs e)
 {
     if (opcaoDebitoBB.Checked)
     {
         Relatório.AdicionarAoRelatorio("Débito BB");
         if (tipoveiculo == "Automóvel")
         {
             observacoes.Text = observacoes.Text.Replace("se for no débito (exceto Banrisul).",
                                                         "exclusivo para débito no Banco do Brasil.");
         }
     }
     else
     {
         if (tipoveiculo == "Automóvel")
         {
             observacoes.Text = observacoes.Text.Replace("exclusivo para débito no Banco do Brasil.",
                                                         "se for no débito (exceto Banrisul).");
         }
         else
         {
             observacoes.Text = "Assistência 24 horas.\r\n";
         }
     }
 }
コード例 #23
0
 private void opcaoValidadeCot_CheckedChanged(object sender, EventArgs e)
 {
     try
     {
         if (opcaoValidadeCot.Checked)
         {
             //Código refletido na função limpar
             dataValidadeCot.Enabled = true;
             DateTime hoje    = DateTime.Now;
             DateTime comdias = hoje.AddDays(5);
             dataValidadeCot.Value = comdias;
         }
         else
         {
             dataValidadeCot.Enabled = false;
         }
         preferencias.Validade = opcaoValidadeCot.Checked;
         WebFile.Prefs         = preferencias;
     }
     catch (Exception ex)
     {
         Relatório.ExHandler(ex, "Validade pressionada antes do status ser carregado");
     }
 }
コード例 #24
0
        public static bool HasInternet()
        {
            try
            {
                using (Ping ping = new Ping())
                {
                    PingReply reply = ping.Send("8.8.8.8", 1000);//ping google public dns server

                    if (reply.Status == IPStatus.Success)
                    {
                        return(true);
                    }
                    else
                    {
                        throw new PingException(JsonConvert.SerializeObject(new Relatório(2, reply.Status.ToString())));
                    }
                }
            }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(false);
            }
        }
コード例 #25
0
        /*public static async Task<string> DownloadStringAsync(string url)
         * {
         *  if (!HasInternet())
         *      return null;
         *
         *  var tcs = new TaskCompletionSource<string>();
         *  try
         *  {
         *      using (var client = new WebClient())
         *      {
         *          client.DownloadStringCompleted += (s, e) =>
         *          {
         *              if (e.Error != null)
         *                  tcs.TrySetException(e.Error);
         *              else
         *                  if (e.Cancelled)
         *                      tcs.TrySetCanceled();
         *                  else
         *                      tcs.TrySetResult(e.Result);
         *          };
         *          client.DownloadStringAsync(new Uri(url));
         *      }
         *      return await tcs.Task;
         *  }
         *  catch (Exception ex)
         *  {
         *      Relatório.ExHandler(ex);
         *      return null;
         *  }
         * }*/

        public static async Task <bool> DownloadFileAsync(string url, string local)
        {
            if (!HasInternet())
            {
                return(false);
            }

            HttpWebRequest get = (HttpWebRequest)WebRequest.Create(url);

            get.Method = WebRequestMethods.Http.Get;

            var tcs = new TaskCompletionSource <WebResponse>();

            try
            {
                get.BeginGetResponse(iar =>
                {
                    try { tcs.TrySetResult(get.EndGetResponse(iar)); }
                    catch (OperationCanceledException) { tcs.TrySetCanceled(); }
                    catch (Exception ex) { tcs.TrySetException(ex); }
                }, null);

                using (WebResponse response = await tcs.Task)
                {
                    using (Stream rs = response.GetResponseStream())
                    {
                        int    bytesRead = 0;
                        byte[] buffer    = new byte[4096];

                        MemoryStream ms = new MemoryStream();
                        while ((bytesRead = rs.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, bytesRead);
                        }

                        ms.Position = 0;

                        var    md5        = MD5.Create();
                        byte[] localHash  = new byte[16];
                        byte[] remoteHash = md5.ComputeHash(ms);

                        if (File.Exists(local))
                        {
                            using (FileStream fs = new FileStream(local, FileMode.Open, FileAccess.Read, FileShare.Read))
                                localHash = md5.ComputeHash(fs);
                        }

                        if (!remoteHash.SequenceEqual(localHash))
                        {
                            ms.Position = 0;
                            using (FileStream fs = new FileStream(local, FileMode.Create, FileAccess.Write, FileShare.Read))
                                while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    fs.Write(buffer, 0, bytesRead);
                                }
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                Relatório.ExHandler(ex);
                return(false);
            }
        }
コード例 #26
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);
            }
        }
コード例 #27
0
        public Cotacao(FipeType tiposeg, string cliente, DateTime data, string seguradora, string modelo, string anoFabricacao, string anoModelo,
                       string marca, string valorFipe, string porContratada, string danosMateriais, string danosCorporais, string danosMorais,
                       string appMorte, string appInvalidez, string franquiaBasica, string valFranqBasicaAVista, string franquiaReduzida,
                       string valFranqReduzidaAVista, string observacoes, bool nomeFuncionario, string funcionario,
                       bool debitobb, bool rcf, string equipamento, string carroceria, bool vd, bool mostrarvalidade, DateTime validade, Fill preenchimento)
        {
            try
            {
                var segerrada = new FormatException();
                Tipo    = tiposeg;
                Cliente = cliente;
                Data    = data;
                if (seguradora != "")
                {
                    Seguradora = seguradora;
                }
                else
                {
                    throw segerrada;
                }
                Modelo        = modelo;
                AnoFabricacao = Convert.ToInt32(anoFabricacao);
                AnoModelo     = anoModelo;
                Marca         = marca;
                ValorFipe     = Decimal.Parse(valorFipe, NumberStyles.Currency, CultureInfo.CurrentCulture);
                if (porContratada != "")
                {
                    PorContratada = Decimal.Parse(porContratada);
                }
                else
                {
                    PorContratada = 0.0m;
                }
                Rcf                    = rcf;
                DanosMateriais         = Decimal.Parse(danosMateriais, NumberStyles.Currency, CultureInfo.CurrentCulture);
                DanosCorporais         = Decimal.Parse(danosCorporais, NumberStyles.Currency, CultureInfo.CurrentCulture);
                DanosMorais            = Decimal.Parse(danosMorais, NumberStyles.Currency, CultureInfo.CurrentCulture);
                APPMorte               = Decimal.Parse(appMorte, NumberStyles.Currency, CultureInfo.CurrentCulture);
                APPInvalidez           = Decimal.Parse(appInvalidez, NumberStyles.Currency, CultureInfo.CurrentCulture);
                FranquiaBasica         = Decimal.Parse(franquiaBasica, NumberStyles.Currency, CultureInfo.CurrentCulture);
                ValFranqBasicaAVista   = Decimal.Parse(valFranqBasicaAVista, NumberStyles.Currency, CultureInfo.CurrentCulture);
                FranquiaReduzida       = Decimal.Parse(franquiaReduzida, NumberStyles.Currency, CultureInfo.CurrentCulture);
                ValFranqReduzidaAVista = Decimal.Parse(valFranqReduzidaAVista, NumberStyles.Currency, CultureInfo.CurrentCulture);
                if (FranquiaBasica + ValFranqBasicaAVista + FranquiaReduzida + ValFranqReduzidaAVista == 0.0m)
                {
                    throw segerrada;
                }

                NomeFuncionario = nomeFuncionario;
                Funcionario     = funcionario;
                Observacoes     = observacoes;

                DebitoBB      = debitobb;
                ErroDeFormato = false;

                if (nomeFuncionario == true)
                {
                    Home.preferencias.NomeFuncionario = funcionario;
                    WebFile.Prefs = Home.preferencias;
                }

                Equipamento     = Decimal.Parse(equipamento, NumberStyles.Currency, CultureInfo.CurrentCulture);
                Carroceria      = Decimal.Parse(carroceria, NumberStyles.Currency, CultureInfo.CurrentCulture);
                Vd              = vd;
                MostrarValidade = mostrarvalidade;
                Validade        = validade;
                Preenchimento   = preenchimento;
            }
            catch (FormatException)
            {
                Relatório.AdicionarAoRelatorio("Campos preenchidos incorretamente");
                MessageBox.Show("Algum campo foi preenchido incorretamente.\r\nCorrija-o e tente novamente.",
                                "Carta de Cotação",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                ErroDeFormato = true;
            }

            TabelaParcelamento = new List <Parcelamento>();
            int max = maxParcelas;

            if (Seguradora == "Allianz")
            {
                max = 6; //Ajusta o número máximo de parcelas conforme a seguradora;
            }
            for (int i = 0; i < max; i++)
            {
                foreach (string tipo in tiposFranq)
                {
                    foreach (string forma in formasPagto)
                    {
                        try
                        {
                            object o = WebFile.Extras.CreateInstance("CartaDeCotacao.Parcelamento");
                            o.GetType().GetConstructors()[1].Invoke(o, new object[] { Seguradora, forma, tipo, ValFranqBasicaAVista, ValFranqReduzidaAVista });
                            o.GetType().GetMethod("CalculaParcela").Invoke(o, new object[] { 1 + i });

                            Parcelamento parc = new Parcelamento()
                            {
                                Seguradora  = (string)o.GetType().GetProperty("Seguradora").GetValue(o, null),
                                FormaPagto  = (string)o.GetType().GetProperty("FormaPagto").GetValue(o, null),
                                TipoFranq   = (string)o.GetType().GetProperty("TipoFranq").GetValue(o, null),
                                Basica      = (decimal)o.GetType().GetProperty("Basica").GetValue(o, null),
                                Reduzida    = (decimal)o.GetType().GetProperty("Reduzida").GetValue(o, null),
                                NumParcelas = (int)o.GetType().GetProperty("NumParcelas").GetValue(o, null),
                                Descricao   = (string)o.GetType().GetProperty("Descricao").GetValue(o, null),
                                ValParcela  = (decimal)o.GetType().GetProperty("ValParcela").GetValue(o, null)
                            };

                            TabelaParcelamento.Add(parc);
                        }
                        catch (Exception ex)
                        {
                            Relatório.ExHandler(ex, "Uso do parcelamento");
                        }
                    }
                }

                if (i == 0) //Começa no zero (Á vista)
                {
                    i++;
                }

                if (i == 1)
                {
                    i++;
                }

                if (Seguradora == "Allianz" && i == 3)
                {
                    i++;
                }
            }
        }
コード例 #28
0
 private void fecharToolStripMenuItem_Click(object sender, EventArgs e)
 {
     Relatório.AdicionarAoRelatorio("Fechar do menu pressionado");
     Close();
 }
コード例 #29
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");
                }
            }
        }
コード例 #30
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);
                }
            }
        }