コード例 #1
0
        private static void ConsultaAtaPregao(Licitacao licitacao)
        {
            RService.Log("(ConsultaAtaPregao) " + Name + ": Buscando ata do pregão at {0}", LogPath);

            try
            {
                if (!string.IsNullOrEmpty(licitacao.Uasg) && !string.IsNullOrEmpty(licitacao.NumPregao))
                {
                    List <LicitacaoHistorico> itens = new List <LicitacaoHistorico>();

                    string       _num      = Regex.Replace(licitacao.NumPregao, @"[^\d+]", "");
                    string       _url      = string.Format(Constants.CN_ATA_PREGAO, licitacao.Uasg, _num);
                    HtmlDocument htmlDoc   = WebHandle.GetHtmlDocOfPage(_url, Encoding.GetEncoding("ISO-8859-1"));
                    var          licitInfo = FindLicitInfo(htmlDoc.DocumentNode.InnerHtml);

                    if (!string.IsNullOrEmpty(licitInfo))
                    {
                        HandleTermoHomologacao(licitInfo, licitacao);
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (ConsultaAtaPregao) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath);
            }
        }
コード例 #2
0
        /*Resolve o captcha e preenche campo com a string obtida*/
        private static string GetScriptFillCaptcha(string imageId, string inputId)
        {
            RService.Log("(GetScriptFillCaptcha) " + Name + ": Resolvendo captcha... " + " at {0}", Path.GetTempPath() + Name + ".txt");

            try
            {
                string tempImg     = Path.GetTempPath() + DateTime.Now.ToString("yyyyMMddfff") + ".jpg";
                string tempImgCrop = Path.GetTempPath() + DateTime.Now.ToString("ddMMyyyyfff") + ".jpg";

                web.GetScreenshot().SaveAsFile(tempImg, ScreenshotImageFormat.Jpeg);
                Bitmap image = (Bitmap)Image.FromFile(tempImg);
                GetCaptchaImg(web.FindElement(By.Id(imageId)), image, tempImgCrop);

                string script = string.Format("document.getElementById('{0}').value = '{1}'", inputId,
                                              WebHandle.ResolveCaptcha(tempImgCrop));

                if (File.Exists(tempImg))
                {
                    File.Delete(tempImg);
                }
                if (File.Exists(tempImgCrop))
                {
                    File.Delete(tempImgCrop);
                }

                NumCaptcha++;

                return(script);
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetScriptFillCaptcha) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
                return(null);
            }
        }
コード例 #3
0
 /*Percorre a lista de links dos pregoes*/
 private static void GetPregoes(HtmlDocument pagehtml)
 {
     RService.Log("(GetPregoes) " + Name + ": Percorrendo a lista de licitações da página... " + CurrentPage + " at {0}", Path.GetTempPath() + Name + ".txt");
     try
     {
         /*Percorre cada um dos pregões de cada página*/
         foreach (var link in pagehtml.DocumentNode.Descendants("a").Where(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("vizualizar")))
         {
             /*Pega o link do pregão*/
             MatchCollection matches = StringHandle.GetMatches(link.Attributes["onclick"].Value, @"\/(.*)\'");
             //string linkPregao = GetLinkPregaoSetId(link.Attributes["onclick"].Value);
             string linkPregao = Constants.CMG_SITE + matches[0].Groups[1].Value;
             /*Pega o id do pregão*/
             Id = StringHandle.GetMatches(matches[0].Groups[1].Value, @"id=(\d+)")[0].Groups[1].Value;
             /*Pega a secretaria antes de acessar o link*/
             Secretaria = pagehtml.DocumentNode.Descendants("td").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("colOrgaoEntidade_" + Id)).InnerText.Trim();
             /*Pega a situação antes de acessar o link*/
             Situacao = pagehtml.DocumentNode.Descendants("td").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("colSituacao_" + Id)).InnerText.Trim();
             /*Verifica se o pregão já não foi acessado antes*/
             if (!AllLinks.Contains(linkPregao))
             {
                 AllLinks.Add(linkPregao);
                 HandleCreate(WebHandle.GetHtmlDocOfPage(linkPregao, Encoding.GetEncoding("ISO-8859-1")));
             }
         }
     }
     catch (Exception e)
     {
         RService.Log("RService Exception " + Name + ": (GetPregoes)" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
     }
 }
コード例 #4
0
        /*Percorre os links de cada página*/
        private static int GetOC(HtmlDocument htmlDoc)
        {
            int count = 0;

            try
            {
                var links = htmlDoc.DocumentNode.Descendants("span").Where(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains(Constants.BEC_ID_NATUREZA_RESUMO));
                count = links.Count();

                //Pra cada OC da pagina
                foreach (var link in links)
                {
                    //Valida o status da licitação
                    string status = link.ParentNode.NextSibling.NextSibling.NextSibling.InnerText;
                    string href   = link.SelectSingleNode("a").Attributes["href"].Value;
                    string ocnum  = link.SelectSingleNode("a").InnerText.ToString();
                    HandleCreate(WebHandle.GetHtmlDocOfPage(href), ocnum, status);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetOC) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }

            return(count);
        }
コード例 #5
0
        private static void HandleCreate(HtmlDocument htmlDoc, HtmlNode row)
        {
            try
            {
                if (row.InnerHtml.Contains("href"))
                {
                    string       situacao;
                    string       quoteLink = row.ChildNodes[3].ChildNodes["a"].Attributes["href"].Value.ToString();
                    HtmlDocument htmlQuote = WebHandle.GetHtmlDocOfPage(string.Format(Constants.CN_COTACAO_LINK, quoteLink), Encoding.GetEncoding("ISO-8859-1"));
                    Licitacao    l         = CreateQuote(htmlQuote, quoteLink, out situacao);
                    //RandomSleep();
                    if (l != null && !repo.Exists(l.IdLicitacaoFonte.ToString()))
                    {
                        repo.Insert(l);
                        numCotacoes++;
                        RService.Log("Cotação " + l.IdLicitacaoFonte + " inserida com sucesso" + " at {0}", Path.GetTempPath() + Name + ".txt");

                        //SegmentarCotacao(l);
                    }
                    else if (l != null && repo.Exists(l.IdLicitacaoFonte.ToString()) && LicitacaoController.SituacaoAlterada(l.IdLicitacaoFonte.ToString(), situacao))
                    {
                        l          = repo.GetByIdLicitacaoFonte(l.IdLicitacaoFonte.ToString());
                        l.Situacao = situacao;

                        repo.Update(l);
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (HandleCreate) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #6
0
        /*Inica o processamento do robot*/
        public static void Init()
        {
            RService.Log("(Init) " + Name + ": Começando o processamento... " + "at {0}", Path.GetTempPath() + Name + ".txt");

            try
            {
                AllLinks    = new List <string>();
                Orgao       = OrgaoController.FindById(27);
                Modalidades = new List <Modalidade>();
                Lote        = LoteController.CreateLote(43, 506);
                Repo        = new LicitacaoRepository();

                Modalidades.Add(ModalidadeController.FindById(24));
                Modalidades.Add(ModalidadeController.FindById(22));

                CurrentPage = 1;
                /*Pega o html da primeira página*/
                HtmlDocument pagehtml = WebHandle.GetHtmlHandleCaptcha(Constants.CMG_SITE + Constants.CMG_LINK_PAGINATION, Encoding.GetEncoding("ISO-8859-1"), "textoConfirmacao", Constants.CMG_CAPTCHA, GetParametersPagination(string.Format(Constants.CMG_PARAMETERS_PAGINATION, CurrentPage, DateTime.Now.Year)));

                /*Numero de paginas encontradas*/
                int numberPages = pagehtml.DocumentNode.Descendants("a").Where(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("tabConsultaPregoes_pagina")).ToList().Count;
                /*Caso existam poucas licitações, ao ponto de só haver uma página, o robô estava retornando numberPages = 0. Com a limitação abaixo, ele sempre vai pegar as licitações independente do pouco número de licitações*/
                if (numberPages == 0)
                {
                    numberPages = 1;
                }

                /*Percorre todas as paginas*/
                while (pagehtml != null && CurrentPage <= numberPages)
                {
                    /*Pega todas os pregões de cada página*/
                    GetPregoes(pagehtml);
                    /*Numero da próxima pagina*/
                    CurrentPage++;
                    /*Pega o html da próxima página*/
                    pagehtml = WebHandle.GetHtmlHandleCaptcha(Constants.CMG_SITE + Constants.CMG_LINK_PAGINATION, Encoding.GetEncoding("ISO-8859-1"), "textoConfirmacao", Constants.CMG_CAPTCHA, GetParametersPagination(string.Format(Constants.CMG_PARAMETERS_PAGINATION, CurrentPage, DateTime.Now.ToString("yyyy"))));
                    NumCaptcha++;
                }

                if (Directory.Exists(PathEditais))
                {
                    Directory.Delete(PathEditais, true);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (Init)" + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
            finally
            {
                if (NumLicitacoes <= 0)
                {
                    LoteController.Delete(Lote);
                }
            }
        }
コード例 #7
0
        private static void GetItens(HtmlDocument htmlQuote, Licitacao l)
        {
            try
            {
                foreach (var row in htmlQuote.DocumentNode.Descendants("tr").Where(x => !x.Attributes.Contains("height") && x.Attributes.Contains("class") && x.Attributes["class"].Value.Equals("tex3")))
                {
                    ItemLicitacao item  = new ItemLicitacao();
                    int           count = 0;

                    foreach (var cell in row.ChildNodes.Where(x => x.Name.Equals("td")))
                    {
                        switch (count)
                        {
                        case 0:
                            item.Numero = Convert.ToInt32(cell.InnerText);
                            break;

                        case 1:
                            item.Descricao = cell.InnerText.Replace("\");\r\n      \">", "");
                            string       itemLink   = cell.ChildNodes[0].Attributes["href"].Value.ToString().Split('/')[2];
                            HtmlDocument itemDetail = WebHandle.GetHtmlDocOfPage(string.Format(Constants.CN_COTACAO_LINK, itemLink), Encoding.GetEncoding("ISO-8859-1"));
                            string       descDetail = Regex.Replace(itemDetail.DocumentNode.InnerHtml.ToString().Replace("<br>", "\n"), "<.*?>", String.Empty)
                                                      .Replace("\n\n\n\n  \tCOMPRASNET - O Portal de Compras do Governo Federal :: DESCRIÇÃO COMPLEMENTAR.\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n\n    function erroLogin(){\n        window.opener.erroLogin();\n        window.close();\n    }\n\n\n\n    function popup(ev, elA, features) {\n        var url, target;\n        url = elA.getAttribute(\"href\");\n        target = elA.getAttribute(\"target\");\n        window.open(url, target, features);\n\n        if (ev.cancelBubble != undefined) { //IE\n            ev.cancelBubble = true; \n            ev.returnValue = false;\n        }\n        if (ev.preventDefault) ev.preventDefault(); //Outros\n    }\n\n\n\n\n\n\nAguarde!\n\n\nDESCRIÇÃO COMPLEMENTAR\n\r\n\r\n", "")
                                                      .Replace("\r\n\r\n\r\n", "\n")
                                                      .Replace("  ", "");
                            item.DescricaoDetalhada = descDetail;
                            break;

                        case 2:
                            item.Quantidade = Convert.ToInt32(cell.InnerText);
                            break;

                        case 3:
                            item.Unidade = cell.InnerText;
                            break;
                        }
                        count++;
                    }
                    item.Decreto7174       = "0";
                    item.MargemPreferencia = "0";

                    l.ItensLicitacao.Add(item);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetItens) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #8
0
 /*Cria o objeto licitacao arquivo, com o nome do arquivo do edital e a licitacao referente*/
 private static void DownloadEditais(string linkEdital, NameValueCollection formparameters)
 {
     try
     {
         if (!Directory.Exists(PathEditais))
         {
             Directory.CreateDirectory(PathEditais);
         }
         WebHandle.DownloadDataPost(linkEdital, PathEditais + FileHandle.GetATemporaryFileName(), formparameters);
     }
     catch (Exception e)
     {
         RService.Log("Exception (DownloadEditais) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
     }
 }
コード例 #9
0
        /*Cria os objetos Licitacao, Lote e LicitacaoArquivo fazendo as verificações necessárias.*/
        private static void HandleCreate(HtmlDocument htmlDoc, string ocnum, string situacao)
        {
            try
            {
                Regex  regex = new Regex("\\d{4}OC");
                string ocn   = ocnum;
                ocnum = "1" + regex.Replace(ocnum, DateTime.Now.ToString("yy"));

                /*Verifica se a oc já não esta na base de dados, cria um novo lote se for preciso*/
                //if (!string.IsNullOrEmpty(ocnum) && !AlreadyInserted.Contains(long.Parse(ocnum)) && AguardandoPropostasEditalPub(htmlDoc) && !AlreadyColected.Contains(long.Parse(ocnum)))
                if (!string.IsNullOrEmpty(ocn) && !LicitacaoController.ExistsBEC(ocn))
                {
                    //AlreadyColected.Add(long.Parse(ocnum));
                    //Preenche os dados da licitação e retorna para inserir na lista
                    Licitacao licitacao = CreateLicitacao(htmlDoc, ocnum, situacao);
                    if (licitacao != null && !string.IsNullOrEmpty(licitacao.LinkEdital))
                    {
                        licitacao.Observacoes = ocn;

                        Repo.Insert(licitacao);
                        //licitacoes.Add(licitacao);

                        HtmlDocument htmlEditais   = WebHandle.GetHtmlDocOfPage(licitacao.LinkEdital);
                        int          numeroArquivo = 2;
                        //Faz o download de todos os arquivos do edital
                        foreach (HtmlNode editais in htmlEditais.DocumentNode.Descendants("a").Where(x => x.Attributes.Contains("href") && x.Attributes["href"].Value.Contains("ctl00$conteudo$WUC_Documento1$dgDocumento")))
                        {
                            DownloadEditais(licitacao.LinkEdital, GetFormParametersEdital(htmlEditais, numeroArquivo));
                        }
                        CreateLicitacaoArquivo(licitacao);
                        NumLicitacoes++;
                    }
                    else
                    {
                        RService.Log("Exception (HandleCreate) " + Name + ": A licitação não foi salva - Motivo(s): " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                }
                else if (!string.IsNullOrEmpty(ocn) && LicitacaoController.ExistsBEC(ocn) && LicitacaoController.SituacaoAlteradaBEC(ocn, situacao))
                {
                    int id = LicitacaoController.GetIdByObservacoes(ocn);
                    LicitacaoController.UpdateSituacaoByIdLicitacao(id, situacao);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (HandleCreate) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #10
0
        /*Inicia o processamento do robot*/
        private static void Init()
        {
            RService.Log("(Init) " + Name + ": Começando o processamento..." + " at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                NumAlteracoes = 0;
                repo          = new FontePesquisaRepository();
                //fontePesquisa = repo.FindByActiveRobot();
                fontePesquisa = repo.FindByRegex();


                //Para debug descomentar o código abaixo

                /*FontePesquisa fp = repo.FindById(1750);
                 * fontePesquisa = new List<FontePesquisa>();
                 * fontePesquisa.Add(fp);*/

                foreach (FontePesquisa f in fontePesquisa)
                {
                    RService.Log("(Init) " + Name + ": Consultando fonte: " + f.Nome + " at {0}", Path.GetTempPath() + Name + ".txt");
                    try
                    {
                        HtmlDocument html = new HtmlDocument();

                        html = SitesComCodigoFrame(f);

                        if (string.IsNullOrEmpty(html.DocumentNode.InnerText))
                        {
                            html = WebHandle.HtmlParaObjeto(f.Link, Encoding.UTF8);
                            if (html.DocumentNode.InnerHtml.Contains("�"))
                            {
                                html = WebHandle.HtmlParaObjeto(f.Link, Encoding.GetEncoding("ISO-8859-1"));
                            }
                        }

                        RegistrarConsulta(html, f);
                    }
                    catch (Exception e)
                    {
                        RService.Log("Exception (Init)" + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (Init)" + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #11
0
        /*Percorre os links de cada página*/
        private static int GetOC(HtmlDocument htmlDoc)
        {
            int count = 1;

            try
            {
                NameValueCollection formData = new NameValueCollection();

                HtmlNode        table = htmlDoc.DocumentNode.Descendants("table").FirstOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Equals("ctl00_ContentPlaceHolder1_gvResumoNatureza"));
                List <HtmlNode> trs   = table.Descendants("tr").ToList();
                HtmlNode        tr    = trs[count];

                while (count <= trs.Count)
                {
                    if (tr.ChildNodes.Count == 6)
                    {
                        //string href = Constants.BEC_LINK_OC + link.SelectSingleNode("a").InnerText.ToString();
                        href = tr.Descendants("a").FirstOrDefault(x => x.Attributes.Contains("href")).GetAttributeValue("href", "").Replace("Edital", "Fornecedores_Dados_OC");
                        string ocnum = tr.Descendants("a").FirstOrDefault(x => x.Attributes.Contains("href")).InnerText;

                        string situacao = tr.ChildNodes[4].InnerText;

                        if (!situacao.Contains("Interposi"))
                        {
                            HandleCreate(WebHandle.GetHtmlDocOfPageDefaultEncoding(href, formData), ocnum, situacao);
                        }
                        else
                        {
                            RService.Log("Exception (GetOC)" + Name + ": Página da licitação fora do ar na fonte (Erro interno do servidor - 500) at {0}", Path.GetTempPath() + Name + ".txt");
                        }

                        count++;
                        if (count < trs.Count)
                        {
                            tr = trs[count];
                        }
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetOC)" + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }

            return(count);
        }
コード例 #12
0
        internal static void Init()
        {
            RService.Log("(Init) " + Name + ": Começando o processamento.. at {0}", Path.GetTempPath() + Name + ".txt");

            try
            {
                //Inicializa as listas e variáveis que serão usadas pelo robô
                CurrentPage      = 1;
                Lote             = LoteController.CreateLote(43, 1249);
                repo             = new LicitacaoRepository();
                Cidades          = CidadeController.GetNameToCidade(Constants.TCMCE_UF);
                NameToOrgao      = OrgaoController.GetNomeUfToOrgao();
                NameToModalidade = ModalidadeController.GetNameToModalidade();

                HtmlDocument htmlDoc = WebHandle.GetHtmlDocOfPage(string.Format(Constants.TCMCE_PAGE, CurrentPage, DateTime.Today.ToString("dd-MM-yyyy"), DateTime.Today.AddYears(1).ToString("dd-MM-yyyy")), Encoding.GetEncoding("UTF-8"));

                //O GetLastPage pega o código Html e o vasculha para encontrar o valor da última página
                int lastPage = GetLastPage(htmlDoc);

                while (CurrentPage != lastPage)
                {
                    RService.Log("(Init) " + Name + ": Percorrendo os links da página.. " + CurrentPage + " at {0}", Path.GetTempPath() + Name + ".txt");

                    HtmlNode licList = htmlDoc.DocumentNode.Descendants("table").SingleOrDefault(x => x.Id.Equals("table"));

                    foreach (var lic in licList.Descendants("tr"))
                    {
                        if (!lic.InnerHtml.Contains("Licitação"))
                        {
                            HandleCreate(lic);
                        }
                    }

                    CurrentPage++;
                    htmlDoc = WebHandle.GetHtmlDocOfPage(string.Format(Constants.TCMCE_PAGE, CurrentPage, DateTime.Today.ToString("dd-MM-yyyy"), DateTime.Today.AddYears(1).ToString("dd-MM-yyyy")), Encoding.GetEncoding("ISO-8859-1"));
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (Init) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #13
0
        private static void HandleCreate(HtmlNode lic)
        {
            try
            {
                string   link     = string.Format(Constants.TCMCE_HOST + lic.ChildNodes[1].ChildNodes[0].GetAttributeValue("href", "").ToString());
                string[] licParts = link.Split('/');
                string   licNum   = licParts[7] + licParts[9];

                HtmlDocument licPage  = WebHandle.GetHtmlDocOfPage(link, Encoding.GetEncoding("UTF-8"));
                string       situacao = Regex.Replace(StringHandle.GetMatches(licPage.DocumentNode.InnerHtml, @"Situação:( *)<b>(.*)</b")[0].ToString(), @"Situação:|<b>|</b", "").Trim();

                if (!string.IsNullOrEmpty(licNum) && !LicitacaoController.Exists(licNum))
                {
                    Licitacao l = CreateLicitacao(licPage, link, licNum, situacao);
                    if (l != null)
                    {
                        repo = new LicitacaoRepository();
                        repo.Insert(l);
                        RService.Log("(HandleCreate) " + Name + ": Licitação nº" + licNum + " inserida com sucesso at {0}", Path.GetTempPath() + Name + ".txt");
                        NumLicitacoes++;

                        GetEditalAndArquivos(licPage, l);
                    }
                    else
                    {
                        RService.Log("Exception (HandleCreate) " + Name + ": Licitação não salva. Motivo: " + mensagemErro + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                }
                else if (!string.IsNullOrEmpty(licNum) && LicitacaoController.Exists(licNum) && LicitacaoController.SituacaoAlterada(licNum, situacao))
                {
                    Licitacao licitacao = LicitacaoController.GetByIdLicitacaoFonte(licNum);
                    licitacao.Situacao = situacao;

                    repo = new LicitacaoRepository();
                    repo.Update(licitacao);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (HandleCreate) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #14
0
        private static string GetScriptFillCaptcha(ChromeDriver web, string input)
        {
            RService.Log("(GetScriptFillCaptcha) " + Name + ": Resolvendo captcha... at {0}", Path.GetTempPath() + Name + ".txt");
            string script = string.Empty;
            Bitmap image;

            try
            {
                string tempImg     = Path.GetTempPath() + "tempImg.png";
                string tempImgCrop = Path.GetTempPath() + "tempImgCrop.png";
                web.GetScreenshot().SaveAsFile(tempImg, ScreenshotImageFormat.Png);

                using (Stream bmpStream = File.Open(tempImg, FileMode.Open))
                {
                    Image img = Image.FromStream(bmpStream);

                    image = new Bitmap(img);
                }

                GetCaptchaImg(web.FindElement(By.XPath("//*[@id=\"form1\"]/div[1]/img")), image, tempImgCrop);

                script = WebHandle.ResolveCaptcha(tempImgCrop);

                if (File.Exists(tempImg))
                {
                    File.Delete(tempImg);
                }
                if (File.Exists(tempImgCrop))
                {
                    File.Delete(tempImgCrop);
                }

                NumCaptcha++;
            }
            catch (Exception ex)
            {
                RService.Log("Exception (GetScriptFillCaptcha) " + Name + ": " + ex.Message + " / " + ex.StackTrace + " / " + ex.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }

            return(script);
        }
コード例 #15
0
        //Pega as licitações da modalidade Carta Convite
        private static void GetConvites(string uri)
        {
            RService.Log("(GetConvites) " + Name + ": Começando o processamento de licitações da modalidade Carta Convite " + "at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                /*Lista dos parametros do post*/
                NameValueCollection post = new NameValueCollection();

                /*Percorre cada uma das naturezas da modalidade*/
                foreach (var attr in WebHandle.GetHtmlDocOfPageDefaultEncoding(uri, post).DocumentNode.Descendants("span").Where(x => x.Attributes.Contains("id") &&
                                                                                                                                 x.Attributes["id"].Value.ToString().Contains(Constants.BEC_ID_NATUREZA)))
                {
                    /*Link para uma das naturezas*/
                    string urin = attr.SelectSingleNode("a").Attributes["href"].Value.ToString();

                    //post = new NameValueCollection();
                    CurrentPage = 2;
                    int count = 21;

                    /*Percorre as páginas de uma natureza (ex: 1;2;3)*/
                    HtmlDocument pagehtml = WebHandle.GetHtmlDocOfPageDefaultEncoding(urin, post);
                    while (pagehtml != null && count == 21)
                    {
                        RService.Log("(GetConvites) " + Name + ": Percorrendo os links da página.. " + (CurrentPage - 1) + " at {0}", Path.GetTempPath() + Name + ".txt");
                        //Teste para verificar licitação específica
                        //GetTestOC();

                        //Pega as licitações de cada página (OC's)
                        count = GetOC(pagehtml);
                        //Pega o html da próxima página
                        pagehtml = WebHandle.GetHtmlDocOfPageDefaultEncoding(urin, GetFormParameters(pagehtml, CurrentPage));
                        //Numero da proxima página
                        CurrentPage++;
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetConvites) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #16
0
        private static void HandleTermoHomologacao(string licitInfo, Licitacao licitacao)
        {
            try
            {
                var nums = HandleLicitInfo(licitInfo);

                var          termoHomologacaoUrl = string.Format(Constants.CN_TERMOHOMOLOGACAO, nums[0], nums[1], nums[2]);
                HtmlDocument homologDoc          = WebHandle.GetHtmlDocOfPage(termoHomologacaoUrl, Encoding.GetEncoding("ISO-8859-1"));

                var grupos = homologDoc.DocumentNode.ChildNodes[0].ChildNodes[3].ChildNodes.Where(g => g.InnerText.Contains("GRUPO")).ToList();

                foreach (var grupo in grupos)
                {
                    GetPrecos(grupo, licitacao);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (HandleTermoHomologacao) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", LogPath);
            }
        }
コード例 #17
0
ファイル: BBController.cs プロジェクト: FTorres41/WebCrawlers
        /*Resolve o captcha e preenche campo com a string obtida*/
        private static string GetScriptFillCaptchaXPath(string imageXPath, string inputId)
        {
            RService.Log("(GetScriptFillCaptcha) " + GetNameRobot() + ": Resolvendo captcha... " + " at {0}", Path.GetTempPath() + GetNameRobot() + ".txt");

            string tempImg = string.Empty, tempImgCrop = string.Empty;

            try
            {
                tempImg     = Path.GetTempPath() + Guid.NewGuid().ToString() + ".jpg";
                tempImgCrop = Path.GetTempPath() + Guid.NewGuid().ToString() + ".jpg";

                web.GetScreenshot().SaveAsFile(tempImg, ScreenshotImageFormat.Jpeg);
                Bitmap image = (Bitmap)Image.FromFile(tempImg);
                GetCaptchaImg(web.FindElement(By.XPath(imageXPath)), image, tempImgCrop);

                string script = string.Format("document.getElementById('{0}').value = '{1}'", inputId,
                                              WebHandle.ResolveCaptcha(tempImgCrop).ToLower());

                NumCaptcha++;

                return(script);
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetScriptFillCaptcha) " + GetNameRobot() + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + GetNameRobot() + ".txt");
                return(null);
            }
            finally
            {
                if (File.Exists(tempImg))
                {
                    File.Delete(tempImg);
                }
                if (File.Exists(tempImgCrop))
                {
                    File.Delete(tempImgCrop);
                }
            }
        }
コード例 #18
0
        private static void GetFiles(Licitacao licitacao)
        {
            try
            {
                if (!Directory.Exists(PathEditais))
                {
                    Directory.CreateDirectory(PathEditais);
                }

                web.FindElement(By.Id("showEdital")).Click();
                Thread.Sleep(3000);

                var html = web.PageSource;

                var fileRx = new Regex(Constants.CRJ_FILELINK_REGEX);

                if (fileRx.IsMatch(html))
                {
                    var matches   = fileRx.Matches(html);
                    var fileLinks = HandleMatchedContent(matches);

                    foreach (var link in fileLinks)
                    {
                        var fileName = link.Split('/')[9];
                        WebHandle.DownloadFileWebRequest(link, PathEditais, fileName);

                        if (LicitacaoArquivoController.CreateLicitacaoArquivo(Name, licitacao, PathEditais, fileName, web.Manage().Cookies.AllCookies))
                        {
                            RService.Log("(GetFiles) " + Name + ": Arquivo " + fileName + " inserido com sucesso para licitação " + licitacao.IdLicitacaoFonte + " at {0}", LogPath);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetFiles) " + Name + ": " + e.Message + " / " + e.StackTrace + " at {0}", LogPath);
            }
        }
コード例 #19
0
        private static void Init()
        {
            RService.Log("(Init) " + Name + ": Começando o processamento... " + "at {0}", Path.GetTempPath() + Name + ".txt");

            try
            {
                nameToModalidade         = ModalidadeController.GetNameToModalidade();
                nameToOrgao              = OrgaoController.GetNomeUfToOrgao();
                ufToCapital              = CityUtil.GetUfToCapital();
                ufToNomeCidadeToIdCidade = CidadeController.GetUfToNameCidadeToIdCidade();
                lote = LoteController.CreateLote(43, 508);
                repo = new LicitacaoRepository();

                HtmlDocument htmlDoc = WebHandle.GetHtmlDocOfPage(Constants.CN_COTACOES, Encoding.GetEncoding("ISO-8859-1"));

                RService.Log("(Init) " + Name + ": Percorrendo as cotações do dia " + DateTime.Today.ToShortDateString() + " at {0}", Path.GetTempPath() + Name + ".txt");

                foreach (var row in htmlDoc.DocumentNode.Descendants("tr").Where(x => x.Attributes.Contains("class") && x.Attributes["class"].Value.Contains("estiloLinhaTabela")).ToList())
                {
                    if (row.ChildNodes[5].InnerText == "Sim")
                    {
                        icms = true;
                    }
                    else
                    {
                        icms = false;
                    }

                    HandleCreate(htmlDoc, row);
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (Init) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #20
0
        /*Cria uma nova licitação para a modalidade Carta Convite*/
        private static Licitacao CreateLicitacao(HtmlDocument htmDoc, string ocnum, string situacao)
        {
            RService.Log("(CreateLicitacao) " + Name + ": Criando licitação.. " + ocnum + " at {0}", Path.GetTempPath() + Name + ".txt");
            Licitacao licitacao = new Licitacao();

            try
            {
                licitacao.Lote                     = Lote;
                licitacao.Num                      = ocnum;
                licitacao.IdLicitacaoFonte         = long.Parse(ocnum);
                licitacao.SegmentoAguardandoEdital = 0;
                licitacao.DigitacaoUsuario         = 43; //Robo

                licitacao.Modalidade = Modalidades[0];
                licitacao.LinkSite   = Constants.BEC_SITE;
                licitacao.Orgao      = Orgao;
                licitacao.IdFonte    = 507;
                licitacao.Excluido   = 0;
                licitacao.Situacao   = situacao;

                int count = 0;
                /*Tabela com as informações da OC*/
                var dadosOc = htmDoc.DocumentNode.Descendants().SingleOrDefault(x => x.Id == "ctl00_DetalhesOfertaCompra1_UpdatePanel1");
                /*Percorre todas as colunas de todas as linhas dessa tabela*/
                List <HtmlNode> inf = dadosOc.Descendants("td").ToList();
                foreach (var data in inf)
                {
                    if (data.InnerText.Trim().Contains("Proposta"))
                    {
                        MatchCollection matches = StringHandle.GetMatches(data.InnerText.Trim(), @"(\d{2}\/\d{2}\/\d{4}\s+\d{2}:\d{2}:\d{2})");
                        if (matches != null)
                        {
                            licitacao.EntregaData  = DateHandle.Parse(matches[0].Groups[1].Value, "dd/MM/yyyy hh:mm:ss");
                            licitacao.AberturaData = DateHandle.Parse(matches[1].Groups[1].Value, "dd/MM/yyyy hh:mm:ss");

                            if (licitacao.AberturaData < DateTime.Today)
                            {
                                return(null);
                            }
                        }
                    }
                    else if (data.InnerText.Trim().Contains("UC"))
                    {
                        licitacao.Departamento = data.InnerText.Split(':')[1].Trim();
                    }
                    count++;
                }

                var dadosUC = htmDoc.DocumentNode.Descendants().FirstOrDefault(x => x.Id == "formulario");
                /*Percorre todas as colunas de todas as linhas dessa tabela*/
                List <HtmlNode> infUC = dadosUC.Descendants("span").ToList();
                foreach (var info in infUC)
                {
                    if (info.Id.Equals("ctl00_c_area_conteudo_wuc_dados_oc1_txt_endereco_uge"))
                    {
                        licitacao.Endereco = info.InnerText.Trim();
                    }
                    else if (info.Id.Equals("ctl00_c_area_conteudo_wuc_dados_oc1_txt_local_entrega"))
                    {
                        string   localidade   = info.InnerText.Split('-').Last().ToString();
                        string[] cidadeEstado = localidade.Split('/');
                        string   cidade       = cidadeEstado.Last().ToString().ToLower().Trim();

                        //CultureInfo para poder tornar apenas as iniciais maiúsculas
                        var textInfo = new CultureInfo("pt-BR").TextInfo;

                        licitacao.Cidade      = textInfo.ToTitleCase(cidade).ToString();
                        licitacao.Estado      = Constants.BEC_ESTADO;
                        licitacao.EstadoFonte = Constants.BEC_UF;

                        cidade = licitacao.Cidade.ToString();

                        licitacao.CidadeFonte = Cidades.ContainsKey(cidade) ? Cidades[cidade] : CityUtil.GetCidadeFonte(cidade, Cidades);
                    }
                    else if (info.Id.Equals("ctl00_c_area_conteudo_wuc_dados_oc1_txt_natureza_despesa"))
                    {
                        licitacao.Objeto = "Contratação de " + info.InnerText.ToString().Trim();
                    }
                }

                NameValueCollection formData = new NameValueCollection();
                href = href.Replace("Fornecedores_Dados_OC", "OC_Item");
                var htmItens = WebHandle.GetHtmlDocOfPageDefaultEncoding(href, formData);
                licitacao.ItensLicitacao = licitacao.ItensLicitacao ?? new List <ItemLicitacao>();

                /*Contador das linhas da tabela*/
                CreateItensLicitacao(htmItens, licitacao);
            }
            catch (Exception e)
            {
                RService.Log("Exception (CreateLicitacao)" + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }

            return(LicitacaoController.IsValid(licitacao, out mensagemErro) ? licitacao : null);
        }
コード例 #21
0
        /*Cria o objeto licitacao arquivo, com o nome do arquivo do edital e a licitacao referente*/
        private static void CreateLicitacaoArquivo(Licitacao licitacao, string linkEdital)
        {
            RService.Log("(CreateLicitacaoArquivo) " + Name + ": Criando arquivo de edital da OC.. " + "at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                /*Transforma o html do edital em pdf, salva numa pasta temp e depois envia para um diretório FTP*/
                if (!Directory.Exists(PathEdital))
                {
                    Directory.CreateDirectory(PathEdital);
                }

                string fileName = FileHandle.GetATemporaryFileName();

                if (WebHandle.HtmlToPdf(linkEdital, PathEdital + fileName))
                {
                    #region FTP
                    //if (FTP.SendFileFtp(new FTP(PathEdital, fileName + WebHandle.ExtensionLastFileDownloaded, FTP.Adrss, FTP.Pwd, FTP.UName), Name))
                    //{
                    //    LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                    //    licitacaoArq.NomeArquivo = fileName + WebHandle.ExtensionLastFileDownloaded;
                    //    licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                    //    licitacaoArq.Status = 0;
                    //    licitacaoArq.IdLicitacao = licitacao.Id;

                    //    LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                    //    repoArq.Insert(licitacaoArq);

                    //    if (File.Exists(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded))
                    //    {
                    //        File.Delete(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded);
                    //    }
                    //}
                    //else
                    //{
                    //    RService.Log("(CreateLicitacaoArquivo) " + Name + ": error sending the file by FTP (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    //}
                    #endregion

                    #region AWS
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": Enviando arquivo para Amazon S3... " + fileName + " at {0}", Path.GetTempPath() + Name + ".txt");

                    if (AWS.SendObject(licitacao, PathEdital, fileName + ".pdf"))
                    {
                        LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                        licitacaoArq.NomeArquivo         = fileName + WebHandle.ExtensionLastFileDownloaded;
                        licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                        licitacaoArq.Status      = 0;
                        licitacaoArq.IdLicitacao = licitacao.Id;

                        LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                        repoArq.Insert(licitacaoArq);

                        if (File.Exists(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded))
                        {
                            File.Delete(PathEdital + fileName + WebHandle.ExtensionLastFileDownloaded);
                        }

                        RService.Log("(CreateLicitacaoArquivo) " + Name + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    else
                    {
                        RService.Log("Exception (CreateLicitacaoArquivo) " + Name + ": Erro ao enviar o arquivo para Amazon (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    #endregion
                }
                else
                {
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": erro ao converter HTML para PDF (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (CreateLicitacaoArquivo) " + Name + ":" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }
コード例 #22
0
        /*Cria uma nova licitacao.*/
        private static Licitacao CreateLicitacao(HtmlDocument htmDoc, string ocnum, string situacao)
        {
            RService.Log("(CreateLicitacao) " + Name + ": Criando licitação.. " + ocnum + " at {0}", Path.GetTempPath() + Name + ".txt");
            Licitacao licitacao = new Licitacao();

            try
            {
                licitacao.Lote        = Lote;
                licitacao.LinkSite    = Constants.BEC_SITE;
                licitacao.Modalidade  = Modalidade;
                licitacao.IdFonte     = 507;
                licitacao.EstadoFonte = Constants.BEC_UF;
                licitacao.CidadeFonte = 9668;
                licitacao.Orgao       = Orgao;
                licitacao.Cidade      = Constants.BEC_CIDADE;
                licitacao.Estado      = Constants.BEC_ESTADO;
                licitacao.Excluido    = 0;
                licitacao.SegmentoAguardandoEdital = 0;
                licitacao.DigitacaoUsuario         = 43; //Robo
                licitacao.Situacao = situacao;

                //licitacao.DigitacaoData = null;
                //licitacao.ProcessamentoData = null;

                licitacao.Num = ocnum;
                licitacao.IdLicitacaoFonte = long.Parse(ocnum);
                licitacao.Departamento     = htmDoc.DocumentNode.Descendants("span").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("ctl00_wucOcFicha_txtNomUge")).InnerText.Trim();
                int count;

                string city = htmDoc.DocumentNode.Descendants("span").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("ctl00_wucOcFicha_txtDescricaoEnteFederativo")).InnerText.Trim();
                if (city != "GOVERNO DO ESTADO DE SÃO PAULO")
                {
                    city = StringHandle.RemoveAccent(city);
                    foreach (var cidade in Cidades)
                    {
                        if (city.Contains(cidade.Key))
                        {
                            licitacao.Cidade      = cidade.Key;
                            licitacao.CidadeFonte = cidade.Value;
                            break;
                        }
                    }
                }

                /*Percorre os links da OC para montar o objeto licitação*/
                bool findFirstEditalLink = false;
                bool findFirstOcLink     = false;
                foreach (HtmlNode htmNode in htmDoc.DocumentNode.Descendants("li"))
                {
                    /*Link onde ficam os arquivos do edital*/
                    HtmlNode htmlNodeInNode = htmNode.SelectSingleNode("a");

                    if (htmlNodeInNode != null)
                    {
                        if (htmlNodeInNode.Attributes.Contains("href") && htmlNodeInNode.Attributes["href"].Value.Contains("bec_pregao_UI/Edital") && !findFirstEditalLink)
                        {
                            licitacao.LinkEdital = htmlNodeInNode.Attributes["href"].Value.Trim();
                            findFirstEditalLink  = true;
                        }
                        /*Link para a pag onde ficam as datas*/
                        if (htmlNodeInNode.Attributes.Contains("href") && htmlNodeInNode.Attributes["href"].Value.Contains("bec_pregao_UI/Agendamento"))
                        {
                            /*Html da pág onde ficam as datas*/
                            HtmlDocument htmDocAgendamento = WebHandle.GetHtmlDocOfPage(htmlNodeInNode.Attributes["href"].Value);
                            /*Tabela de datas, agendamentos*/
                            HtmlNode table = htmDocAgendamento.DocumentNode.Descendants("table").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("ctl00_conteudo_grd"));
                            /*Cada célula da tabela*/
                            List <HtmlNode> tds = table.Descendants("td").ToList();
                            count = 0;
                            foreach (HtmlNode inf in tds)
                            {
                                /*Célula com o label ENTREGA DE PROPOSTA, na célula seguinte ficam as datas*/
                                if (inf.InnerText.ToUpper().Trim().Contains("ENTREGA DE PROPOSTA"))
                                {
                                    MatchCollection matches = StringHandle.GetMatches(tds[count + 1].InnerText.Trim(), @"(\d{2}\/\d{2}\/\d{4}\s+\d{2}:\d{2})");
                                    licitacao.EntregaData  = DateHandle.Parse(matches[0].Groups[1].Value, "dd/MM/yyyy hh:mm");
                                    licitacao.AberturaData = DateHandle.Parse(matches[1].Groups[1].Value, "dd/MM/yyyy hh:mm");
                                    break;
                                }
                                count++;
                            }
                        }
                        /*Link com dados da OC*/
                        if (htmlNodeInNode.Attributes.Contains("href") && htmlNodeInNode.Attributes["href"].Value.Contains("bec_pregao_UI/OC") && !findFirstOcLink)
                        {
                            HtmlDocument htmDocFasePrep = WebHandle.GetHtmlDocOfPage(htmlNodeInNode.Attributes["href"].Value);
                            licitacao.Endereco = Regex.Replace(htmDocFasePrep.DocumentNode.Descendants("span").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("ctl00_conteudo_Wuc_OC_Ficha2_txtEndUge")).InnerText.Trim(), @"\s+", " ");
                            licitacao.Objeto   = "Contratação de " + Regex.Replace(htmDocFasePrep.DocumentNode.Descendants("span").SingleOrDefault(x => x.Attributes.Contains("id") && x.Attributes["id"].Value.Contains("ctl00_conteudo_Wuc_OC_Ficha2_txtNaturezaJuridica")).InnerText.Trim(), @"\s+", " ");
                            findFirstOcLink    = true;
                        }
                    }
                }

                licitacao.ItensLicitacao = licitacao.ItensLicitacao ?? new List <ItemLicitacao>();

                CreateItensLicitacao(htmDoc, licitacao);
            }
            catch (Exception e)
            {
                RService.Log("Exception (CreateLicitacao) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }

            return(LicitacaoController.IsValid(licitacao, out mensagemErro) ? licitacao : null);
        }
コード例 #23
0
        private static void ConsultaAtaPregao(Licitacao licitacao)
        {
            RService.Log("(ConsultaAtaPregao) " + Historic + ": Buscando itens da ata do pregão at {0}", Path.GetTempPath() + Historic + ".txt");
            try
            {
                if (!string.IsNullOrEmpty(licitacao.Uasg) && !string.IsNullOrEmpty(licitacao.NumPregao))
                {
                    List <LicitacaoHistorico> itens = new List <LicitacaoHistorico>();

                    string       _num    = Regex.Replace(licitacao.NumPregao, @"[^\d+]", "");
                    string       _url    = string.Format(Constants.CN_ATA_PREGAO, licitacao.Uasg, _num);
                    HtmlDocument htmlDoc = WebHandle.GetHtmlDocOfPage(_url, Encoding.GetEncoding("ISO-8859-1"));

                    string _valorRegex = Regex.Match(htmlDoc.DocumentNode.InnerHtml, @"exibeQuadro\(\d+").Value;
                    string _codPregao  = Regex.Match(_valorRegex, @"\d+").Value;

                    if (!string.IsNullOrEmpty(_codPregao))
                    {
                        Dictionary <string, string> tipos = new Dictionary <string, string>();
                        tipos.Add("A", "Aviso");
                        tipos.Add("E", "Esclarecimento");
                        tipos.Add("I", "Impugnação");

                        foreach (var tipo in tipos)
                        {
                            RService.Log("(ConsultaAtaPregao) " + Historic + ": Buscando itens do tipo: " + tipo.Value + " at {0}", Path.GetTempPath() + Historic + ".txt");

                            string _urlItem = string.Format(Constants.CN_PREGAO_AVISOS_DETALHE, _codPregao, tipo.Key);

                            htmlDoc = WebHandle.GetHtmlDocOfPage(_urlItem, Encoding.GetEncoding("ISO-8859-1"));

                            var listaQaCod = Regex.Matches(htmlDoc.DocumentNode.InnerHtml, @"qaCod=[\d]+&texto=T");

                            foreach (var linkQaCod in listaQaCod)
                            {
                                try
                                {
                                    //busca mensagem
                                    string _urlItemDesc = string.Format(Constants.CN_PREGAO_AVISOS_ITEM, linkQaCod.ToString());
                                    htmlDoc = WebHandle.GetHtmlDocOfPage(_urlItemDesc, Encoding.GetEncoding("ISO-8859-1"));

                                    LicitacaoHistorico historico = new LicitacaoHistorico();
                                    historico.IdLicitacao = licitacao.Id;

                                    var tds = htmlDoc.DocumentNode.Descendants("td").Where(p => !p.InnerText.Trim().Equals(""));

                                    //pega data e descrição
                                    foreach (var td in tds)
                                    {
                                        try
                                        {
                                            if (historico.DataCadastro == new DateTime() && Regex.IsMatch(td.InnerText, @"\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}"))
                                            {
                                                string   helper    = Regex.Match(td.InnerText, @"\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}").Value;
                                                DateTime valorData = new DateTime();
                                                historico.DataCadastro = DateTime.TryParse(helper, out valorData) ? valorData : new DateTime();

                                                historico.Historico = td.InnerText.Split(new string[] { helper }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
                                            }
                                            else
                                            {
                                                historico.Mensagem = td.InnerText;
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            RService.Log("Exception (ConsultaAtaPregao) getData" + Historic + " para a licitacao " + licitacao.IdLicitacaoFonte + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Historic + ".txt");
                                        }
                                    }

                                    //Caso tenha resposta
                                    string _codQa = linkQaCod.ToString().Replace("&texto=T", "");
                                    _urlItemDesc = string.Format(Constants.CN_PREGAO_AVISOS_ITEM, _codQa) + "&texto=R";
                                    htmlDoc      = WebHandle.GetHtmlDocOfPage(_urlItemDesc, Encoding.GetEncoding("ISO-8859-1"));
                                    tds          = htmlDoc.DocumentNode.Descendants("td").Where(p => !p.InnerText.Trim().Equals(""));

                                    if (tds.Count() > 2)
                                    {
                                        foreach (var td in tds)
                                        {
                                            if (!Regex.IsMatch(td.InnerText, @"\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}"))
                                            {
                                                historico.Resposta = td.InnerText;
                                            }
                                        }
                                    }

                                    if (LicitacaoHistoricoController.Insert(historico))
                                    {
                                        NumHistoricos++;
                                    }
                                }
                                catch (Exception e)
                                {
                                    RService.Log("Exception (ConsultaAtaPregao) getMensagem " + Historic + " para a licitacao " + licitacao.IdLicitacaoFonte + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Historic + ".txt");
                                }
                            }
                        }
                    }
                    else
                    {
                        RService.Log("(ConsultaAtaPregao) " + Historic + ": Pregão não contém ata pois não foi encerrado at {0}", Path.GetTempPath() + Historic + ".txt");
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (ConsultaAtaPregao) " + Historic + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Historic + ".txt");
            }
        }
コード例 #24
0
        /*Inicia o processamento do robot*/
        private static void Init()
        {
            RService.Log("(Init) " + Name + ": Começando o processamento.. " + "at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                AlreadyColected = new HashSet <long>();

                /*Lista das licitacoes que já existem para bec.sp.gov*/
                //AlreadyInserted = LicitacaoController.GetAlreadyInserted(Constants.BEC_SITE);

                /*Lista das cidades para o estado*/
                Cidades = CidadeController.GetNameToCidade(Constants.BEC_UF);

                Modalidade = ModalidadeController.FindById(24);
                Orgao      = OrgaoController.FindById(388);
                Lote       = LoteController.CreateLote(43, 507);
                Repo       = new LicitacaoRepository();

                //Define os pontos de partida, uri e argumentos do post
                List <string> urls = new List <string>();

                urls.Add(Constants.BEC_LINK_MODALIDADE_71);
                urls.Add(Constants.BEC_LINK_MODALIDADE_72);

                /*Percorre cada modalidade*/
                foreach (string uri in urls)
                {
                    /*Lista dos parametros do post*/
                    NameValueCollection post = new NameValueCollection();

                    /*Percorre as naturezas de cada modalidade*/
                    foreach (var attr in WebHandle.GetHtmlDocOfPage(uri, post).DocumentNode.Descendants("span").Where(x => x.Attributes.Contains("id") &&
                                                                                                                      x.Attributes["id"].Value.ToString().Contains(Constants.BEC_ID_NATUREZA)))
                    {
                        string urin = attr.SelectSingleNode("a").Attributes["href"].Value.ToString();

                        int page = 2, count = 20;

                        /*Percorre as páginas para cada uma das naturezas (ex: 1;2;3)*/
                        HtmlDocument pagehtml = WebHandle.GetHtmlDocOfPage(urin, post);
                        while (pagehtml != null && count == 20)
                        {
                            RService.Log("(GetOC) " + Name + ": Percorrendo os links da página.. " + (page - 1) + " at {0}", Path.GetTempPath() + Name + ".txt");

                            //Pega as licitações de cada página (OC's)
                            count = GetOC(pagehtml);
                            //Pega o html da próxima página
                            pagehtml = WebHandle.GetHtmlDocOfPage(urin, GetFormParameters(pagehtml, page));
                            //Numero da proxima página
                            page++;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (Init) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
            }
            finally
            {
                if (NumLicitacoes <= 0)
                {
                    LoteController.Delete(Lote);
                }
            }
        }
コード例 #25
0
        private static Licitacao CreateQuote(HtmlDocument htmlQuote, string quoteLink, out string situacao)
        {
            Licitacao l     = new Licitacao();
            int       count = 0;

            situacao = null;

            try
            {
                l.IdFonte    = 508;
                l.LinkEdital = string.Format(Constants.CN_COTACAO_LINK, quoteLink);
                l.LinkSite   = Constants.CN_HOST;
                l.Excluido   = 0;
                l.SegmentoAguardandoEdital = 0;
                l.DigitacaoUsuario         = 43; //Robo
                l.Lote           = lote;
                l.Modalidade     = nameToModalidade.ContainsKey("COTACAO ELETRONICA") ? nameToModalidade["COTACAO ELETRONICA"] : null;
                l.ItensLicitacao = l.ItensLicitacao ?? new List <ItemLicitacao>();

                foreach (var row in htmlQuote.DocumentNode.Descendants("tr").Where(x => x.Attributes.Contains("height")))
                {
                    switch (count)
                    {
                    case 0:
                        string uasg         = row.InnerText.Split('-')[0].TrimEnd().Replace("UASG: ", "");
                        string departamento = string.Empty;
                        if (row.InnerText.Split('-').Count() > 2)
                        {
                            for (int i = 1; i < row.InnerText.Split('-').Count(); i++)
                            {
                                if (i != 1)
                                {
                                    departamento = departamento + "-" + row.InnerText.Split('-')[i].TrimStart();
                                }
                                else
                                {
                                    departamento = row.InnerText.Split('-')[i].TrimStart();
                                }
                            }
                        }
                        else
                        {
                            departamento = row.InnerText.Split('-')[1].TrimStart();
                        }
                        l.Uasg         = uasg;
                        l.Departamento = departamento;
                        break;

                    case 1:
                        string numero = row.InnerText.Split(':')[1].TrimStart();
                        l.Num = numero;
                        break;

                    case 2:
                        string objeto = row.InnerText.Replace("Objeto: ", string.Empty);
                        l.Objeto = objeto;
                        break;

                    case 3:
                        string dataEntrega = row.InnerText.Split(':')[1].TrimStart();
                        l.EntregaData = Convert.ToDateTime(dataEntrega);
                        break;

                    case 4:
                        string       obsLink = row.ChildNodes[0].ChildNodes[1].Attributes["href"].Value.ToString().Remove(0, 8);
                        HtmlDocument htmlObs = WebHandle.GetHtmlDocOfPage(string.Format(Constants.CN_COTACAO_LINK, obsLink), Encoding.GetEncoding("ISO-8859-1"));
                        string       obs     = Regex.Replace(htmlObs.DocumentNode.InnerHtml.ToString(), "<.*?>", string.Empty)
                                               .Replace("\n\n\n\n  \tCOMPRASNET - O Portal de Compras do Governo Federal :: Observações Gerais da Cotação Eletrônica.\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\n\n    function erroLogin(){\n        window.opener.erroLogin();\n        window.close();\n    }\n\n\n\n    function popup(ev, elA, features) {\n        var url, target;\n        url = elA.getAttribute(\"href\");\n        target = elA.getAttribute(\"target\");\n        window.open(url, target, features);\n\n        if (ev.cancelBubble != undefined) { //IE\n            ev.cancelBubble = true; \n            ev.returnValue = false;\n        }\n        if (ev.preventDefault) ev.preventDefault(); //Outros\n    }\n\n\n\n\n\n\nAguarde!\n\n\nObservações Gerais da Cotação Eletrônica\n\r\n              ", string.Empty)
                                               .Replace("  ", string.Empty);
                        if (icms)
                        {
                            l.Observacoes = "ICMS: Sim\n\n" + obs;
                        }
                        else
                        {
                            l.Observacoes = "ICMS: Não\n\n" + obs;
                        }
                        break;

                    case 5:
                        situacao   = Regex.Replace(StringHandle.GetMatches(row.InnerHtml, @"Situação:( *)</b><span(.*?)>(.*?)</span")[0].ToString(), @"Situação:|</b><span(.*?)>|</span", "").Trim();
                        l.Situacao = situacao;
                        break;

                    case 6:
                        string dataAbertura = row.InnerText.Split(':')[1].TrimStart().Split('(')[0].Replace('h', ':');
                        l.AberturaData = DateHandle.Parse(dataAbertura, "dd/MM/yyyy hh:mm");
                        break;

                    case 7:
                        string valor = row.InnerText.Split(':')[1].TrimStart();
                        l.ValorMax = valor;
                        break;
                    }
                    count++;
                }

                l.IdLicitacaoFonte = Convert.ToInt64(l.Uasg + l.Num.ToString());

                Licitacao oldLic = LicitacaoRepository.FindByUASG(l.Uasg);

                if (oldLic != null)
                {
                    l.Orgao       = oldLic.Orgao;
                    l.EstadoFonte = oldLic.EstadoFonte;
                    l.CidadeFonte = oldLic.CidadeFonte;
                    l.Endereco    = oldLic.Endereco;
                    l.Cidade      = oldLic.Cidade;
                    l.Estado      = oldLic.Estado;
                }
                else
                {
                    l.Orgao = OrgaoRepository.FindOrgao(l.Departamento);
                    if (l.Orgao == null)
                    {
                        Orgao           org  = OrgaoRepository.CreateOrgao(l.Departamento, l.Observacoes);
                        OrgaoRepository repo = new OrgaoRepository();
                        repo.Insert(org);
                        l.Orgao = org;
                    }
                    l.Estado      = l.Orgao.Estado;
                    l.EstadoFonte = l.Orgao.Estado;
                    l.Cidade      = ufToCapital.ContainsKey(l.EstadoFonte) ? ufToCapital[l.EstadoFonte] : null;
                    Dictionary <string, int?> ufToCidade = ufToNomeCidadeToIdCidade.ContainsKey(l.EstadoFonte) ? ufToNomeCidadeToIdCidade[l.EstadoFonte] : null;
                    l.CidadeFonte = ufToCidade != null?ufToCidade.ContainsKey(StringHandle.RemoveAccent(l.Cidade.ToUpper())) ? ufToCidade[StringHandle.RemoveAccent(l.Cidade.ToUpper())] : CityUtil.GetCidadeFonte(l.Cidade, ufToCidade) : CityUtil.GetCidadeFonte(l.Cidade, ufToCidade);

                    l.Endereco = null;
                }

                GetItens(htmlQuote, l);

                return(LicitacaoController.IsValid(l, out mensagemErro) ? l : null);
            }
            catch (Exception e)
            {
                if (l.Orgao == null)
                {
                    RService.Log("Exception (CreateQuote) " + Name + ": Órgão não foi localizado - ver log do serviço RService" + " at {0}", Path.GetTempPath() + Name + ".txt");
                }
                else
                {
                    RService.Log("Exception (CreateQuote) " + Name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Name + ".txt");
                }

                return(null);
            }
        }
コード例 #26
0
        /*Criando licitação arquivo e enviando para pasta FTP*/
        public static bool CreateLicitacaoArquivo(string nomeRobo, Licitacao licitacao, string edital, string pathEditais, string nameFile, ReadOnlyCollection <OpenQA.Selenium.Cookie> AllCookies)
        {
            try
            {
                if (!Directory.Exists(pathEditais))
                {
                    Directory.CreateDirectory(pathEditais);
                }

                string fileName = FileHandle.GetATemporaryFileName() + WebHandle.GetExtensionFile(nameFile);

                RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Fazendo o download do arquivo... " + fileName + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                if (WebHandle.DownloadFileWebRequest(AllCookies, edital, pathEditais + fileName) && File.Exists(pathEditais + fileName))
                {
                    #region FTP
                    //RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Enviando arquivo por FTP... " + fileName + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                    //int fileCount = Directory.GetFiles(pathEditais).Length;
                    //int wait = 0;

                    //while (fileCount == 0 && wait < 6)
                    //{
                    //Thread.Sleep(5000);
                    //wait++;
                    //}

                    //if (FTP.SendFileFtp(new FTP(pathEditais, fileName, FTP.Adrss, FTP.Pwd, FTP.UName), nomeRobo))
                    //{
                    //LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                    //licitacaoArq.NomeArquivo = fileName;
                    //licitacaoArq.NomeArquivoOriginal = nomeRobo + DateTime.Now.ToString("yyyyMMddHHmmss");
                    //licitacaoArq.NomeArquivoFonte = nameFile;
                    //licitacaoArq.Status = 0;
                    //licitacaoArq.IdLicitacao = licitacao.Id;

                    //LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                    //repoArq.Insert(licitacaoArq);

                    //if (File.Exists(pathEditais + fileName))
                    //{
                    //File.Delete(pathEditais + fileName);
                    //}

                    //RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Arquivo " + fileName + " enviado com sucesso at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                    //return true;
                    //}
                    //else
                    //{
                    //RService.Log("Exception (CreateLicitacaoArquivo) " + nomeRobo + ": Erro ao enviar o arquivo por FTP (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + nomeRobo + ".txt");
                    //}
                    #endregion

                    #region AWS
                    RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Enviando o arquivo para Amazon S3... " + fileName + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                    if (AWS.SendObject(licitacao, pathEditais, fileName))
                    {
                        LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                        licitacaoArq.NomeArquivo         = fileName;
                        licitacaoArq.NomeArquivoOriginal = nomeRobo + DateTime.Now.ToString("yyyyMMddHHmmss");
                        licitacaoArq.NomeArquivoFonte    = nameFile;
                        licitacaoArq.Status      = 0;
                        licitacaoArq.IdLicitacao = licitacao.Id;

                        LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                        repoArq.Insert(licitacaoArq);

                        if (File.Exists(pathEditais + fileName))
                        {
                            File.Delete(pathEditais + fileName);
                        }

                        RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                        return(true);
                    }
                    else
                    {
                        RService.Log("Exception (CreateLicitacaoArquivo) " + nomeRobo + ": Erro ao enviar o arquivo para Amazon (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + nomeRobo + ".txt");
                    }

                    #endregion
                }
                else
                {
                    RService.Log("Exception (CreateLicitacaoArquivo) " + nomeRobo + ": Erro ao fazer o download do arquivo, no link: " + edital + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (CreateLicitacaoArquivo) " + nomeRobo + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");
            }
            return(false);
        }
コード例 #27
0
        private static void GetHistoricos(Licitacao l, string Historic)
        {
            try
            {
                string num        = Regex.Replace(l.Num, @"[^\d+]", "");
                string parametros = string.Format(@"coduasg={0}&modprp=5&numprp={1}", l.Uasg, num);

                HtmlDocument htmlDocument = WebHandle.HtmlParaObjeto(Constants.CN_HISTORICO_LINK + parametros, Encoding.GetEncoding("ISO-8859-1"));

                if (htmlDocument.DocumentNode.LastChild == null)
                {
                    return;
                }

                if (!Regex.IsMatch(htmlDocument.DocumentNode.InnerHtml, @"rico de eventos "))
                {
                    string          expRegular = "<tr bgcolor=\"#ffffff\" class=\"tex3a\">(.+?)</tr>";
                    MatchCollection matches    = Regex.Matches(Regex.Replace(htmlDocument.DocumentNode.InnerHtml, "\n", "").Replace("\r", ""), expRegular);

                    if (matches.Count > 0)
                    {
                        RService.Log("(GetHistoricos) " + Historic + ": Buscando histórico da licitação: " + l.IdLicitacaoFonte + " at {0}", Path.GetTempPath() + Historic + ".txt");

                        for (int i = 0; i < matches.Count; i++)
                        {
                            LicitacaoHistorico historico = new LicitacaoHistorico();
                            historico.IdLicitacao = l.Id;

                            var      helper    = Regex.Match(matches[i].Value, @"\d{2}/\d{2}/\d{4}( +)\d{2}\:\d{2}\:\d{2}").Value;
                            DateTime valorData = new DateTime();
                            historico.DataCadastro = DateTime.TryParse(helper, out valorData) ? valorData : new DateTime();

                            helper = Regex.Match(matches[i].Value, "<td align=\"left\">(.+?)</td>").Value;
                            helper = Regex.Replace(helper, @"&nbsp", " ");
                            helper = Regex.Replace(helper, "<td align=\"left\">", "");
                            helper = Regex.Replace(helper, "</td>", "");
                            historico.Historico = helper.Trim();

                            if (LicitacaoHistoricoController.Insert(historico))
                            {
                                RService.Log("(ConsultaAtaPregao) " + Historic + ": Histórico registrado com sucesso" + " at {0}", Path.GetTempPath() + Historic + ".txt");
                                NumHistoricos++;
                            }
                        }

                        if (matches.Count == 1)
                        {
                            RService.Log("(GetHistoricos) " + Historic + ": Encontrado 1 item de histórico at {0}", Path.GetTempPath() + Historic + ".txt");
                        }
                        else if (matches.Count > 1)
                        {
                            RService.Log("(GetHistoricos) " + Historic + ": Encontrados " + matches.Count + " itens de histórico at {0}", Path.GetTempPath() + Historic + ".txt");
                        }
                        else
                        {
                            RService.Log("(GetHistoricos) " + Historic + ": Não foram encontrados novos itens de histórico at {0}", Path.GetTempPath() + Historic + ".txt");
                        }
                    }
                    else
                    {
                        RService.Log("(GetHistoricos) " + Historic + ": Não foram encontrados itens de histórico at {0}", Path.GetTempPath() + Historic + ".txt");
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetHistoricos) " + Historic + " para licitação " + l.IdLicitacaoFonte + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " at {0}", Path.GetTempPath() + Historic + ".txt");
            }
        }
コード例 #28
0
        internal static bool CreateLicitacaoArquivo(string nomeRobo, Licitacao licitacao, string pathEditais, string nameFile, ReadOnlyCollection <Cookie> allCookies)
        {
            try
            {
                if (!Directory.Exists(pathEditais))
                {
                    Directory.CreateDirectory(pathEditais);
                }

                string fileName = FileHandle.GetATemporaryFileName() + WebHandle.GetExtensionFile(nameFile);
                System.Threading.Thread.Sleep(15000);

                if (File.Exists(pathEditais + "\\" + nameFile))
                {
                    if (nomeRobo.Contains("BB") || nomeRobo.Contains("PCP") || nomeRobo.Contains("TCERS") || nomeRobo.Contains("CRJ"))
                    {
                        File.Move(pathEditais + nameFile, pathEditais + fileName);
                    }

                    #region FTP
                    //RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Enviando arquivo por FTP... " + fileName + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                    //if (FTP.SendFileFtp(new FTP(pathEditais, fileName, FTP.Adrss, FTP.Pwd, FTP.UName), nomeRobo))
                    //{
                    //LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                    //licitacaoArq.NomeArquivo = fileName;
                    //licitacaoArq.NomeArquivoOriginal = nomeRobo + DateTime.Now.ToString("yyyyMMddHHmmss");
                    //licitacaoArq.NomeArquivoFonte = nameFile;
                    //licitacaoArq.Status = 0;
                    //licitacaoArq.IdLicitacao = licitacao.Id;

                    //LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                    //repoArq.Insert(licitacaoArq);

                    //if (File.Exists(pathEditais + fileName))
                    //{
                    //File.Delete(pathEditais + fileName);
                    //}

                    //return true;
                    //}
                    //else
                    //{
                    //RService.Log("Exception (CreateLicitacaoArquivo) " + nomeRobo + ": Erro ao enviar o arquivo por FTP (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + nomeRobo + ".txt");
                    //}

                    #endregion

                    #region AWS
                    RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Enviando o arquivo para Amazon S3... " + fileName + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                    if (AWS.SendObject(licitacao, pathEditais, fileName))
                    {
                        LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                        licitacaoArq.NomeArquivo         = fileName;
                        licitacaoArq.NomeArquivoOriginal = nomeRobo + DateTime.Now.ToString("yyyyMMddHHmmss");
                        licitacaoArq.NomeArquivoFonte    = nameFile;
                        licitacaoArq.Status      = 0;
                        licitacaoArq.IdLicitacao = licitacao.Id;

                        LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                        repoArq.Insert(licitacaoArq);

                        if (File.Exists(pathEditais + fileName))
                        {
                            File.Delete(pathEditais + fileName);
                        }

                        RService.Log("(CreateLicitacaoArquivo) " + nomeRobo + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");

                        return(true);
                    }
                    else
                    {
                        RService.Log("Exception (CreateLicitacaoArquivo) " + nomeRobo + ": Erro ao enviar o arquivo para Amazon (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + nomeRobo + ".txt");
                    }

                    #endregion
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (CreateLicitacaoArquivo) " + nomeRobo + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " at {0}", Path.GetTempPath() + nomeRobo + ".txt");
            }

            return(false);
        }
コード例 #29
0
        /*Cria uma licitação arquivo se o download e o envio do arquivo for efetuado com sucesso*/
        private static void CreateLicitacaoArquivo(Licitacao licitacao, string linkEdital)
        {
            RService.Log("(CreateLicitacaoArquivo) " + Name + ": Criando arquivo de edital da licitação num... " + licitacao.IdLicitacaoFonte + " at {0}", Path.GetTempPath() + Name + ".txt");
            try
            {
                if (!Directory.Exists(PathEditais))
                {
                    Directory.CreateDirectory(PathEditais);
                }
                string fileName = FileHandle.GetATemporaryFileName();

                if (WebHandle.DownloadData(linkEdital, PathEditais + fileName))
                {
                    #region FTP
                    //if (FTP.SendFileFtp(new FTP(PathEditais, fileName + WebHandle.ExtensionLastFileDownloaded, FTP.Adrss, FTP.Pwd, FTP.UName), Name))
                    //{
                    //LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                    //licitacaoArq.NomeArquivo = fileName + WebHandle.ExtensionLastFileDownloaded;
                    //licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                    //licitacaoArq.Status = 0;
                    //licitacaoArq.IdLicitacao = licitacao.Id;

                    //LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                    //repoArq.Insert(licitacaoArq);

                    //RService.Log("(CreateLicitacaoArquivo) " + Name + ": Arquivo de edital da licitação " + licitacao.IdLicitacaoFonte + " inserido com sucesso at {0}", Path.GetTempPath() + Name + ".txt");

                    //if (File.Exists(PathEditais + fileName))
                    //{
                    //File.Delete(PathEditais + fileName);
                    //}
                    //}
                    //else
                    //{
                    //RService.Log("Exception (CreateLicitacaoArquivo) " + Name + ": Erro ao enviar o arquivo para o FTP (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    //}
                    #endregion

                    #region AWS
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": Enviando arquivo para Amazon S3... " + fileName + " at {0}", Path.GetTempPath() + Name + ".txt");

                    if (AWS.SendObject(licitacao, PathEditais, fileName + WebHandle.ExtensionLastFileDownloaded))
                    {
                        LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                        licitacaoArq.NomeArquivo         = fileName + WebHandle.ExtensionLastFileDownloaded;
                        licitacaoArq.NomeArquivoOriginal = Name + DateTime.Now.ToString("yyyyMMddHHmmss");
                        licitacaoArq.Status      = 0;
                        licitacaoArq.IdLicitacao = licitacao.Id;

                        LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                        repoArq.Insert(licitacaoArq);

                        if (File.Exists(PathEditais + fileName))
                        {
                            File.Delete(PathEditais + fileName);
                        }

                        RService.Log("(CreateLicitacaoArquivo) " + Name + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    else
                    {
                        RService.Log("(CreateLicitacaoArquivo) " + Name + ": Erro ao enviar o arquivo para Amazon S3 (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                    }
                    #endregion
                }
                else
                {
                    RService.Log("(CreateLicitacaoArquivo) " + Name + ": Erro ao baixar o arquivo (CreateLicitacaoArquivo) {0}", Path.GetTempPath() + Name + ".txt");
                }
            }
            catch (Exception e)
            {
                RService.Log("RService Exception " + Name + ": (CreateLicitacaoArquivo)" + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException +
                             " at {0}", Path.GetTempPath() + Name + ".txt");
            }
        }